Java: Accessing a String outside of a function

I am a hobby programmer and am trying to access returnJson outside of the onSuccess function. Inside of the function, I can see that it returns as expected. Could somebody explain why I cannot view it outside and what I can do to make it accessible on the outside?

String returnJson;
client.post(context, url, entity, "application/json", new JsonHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
        returnJson = response.toString();
    }
});

Log.d("get json",returnJson);

Answers


You can access it fine, but it is not initialized until the onSuccess() is called, which is likely after the Log.d() is called, due to client.post() being executed asyncronously.

Because of this, at the moment you try to log returnJson, it is not yet initialized and the logging won't work as you expect.


You need to make returnJson a global variable.

Let's say this is what your class looks like:

public class MyClass {
    public void myMethod() {
        String returnJson;
        client.post(context, url, entity, "application/json", new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                 returnJson = response.toString();
            }
        });
        Log.d("get json",returnJson);
    }
}

The returnJson variable is only initialized inside of the myMethod() method. To fix this, your class should look like this:

public class MyClass {
    String returnJson;
    public void myMethod() {
        client.post(context, url, entity, "application/json", new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                 returnJson = response.toString();
            }
        });
        Log.d("get json",returnJson);
    }
}

So now it's a global variable and can be accesed from all your methods. Enjoy!


Need Your Help

get selected date from calender and save it to sql server

c# sql-server

I want to get selected date from monthCalender1 and retrieve my data from a SQL Server table. But I get exception messages

RewriteCond to skip rule if file or directory exists

regex apache .htaccess mod-rewrite url-rewriting

I am trying to adjust my htacess file to skip the rewrite rule if the file or directory exists, but when the file exists, it changes the URL to something different. I don't know why this is happeni...