1

These are the instructions in my onCreate:

   protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);

   Client c = new Client();
   String p=c.get();
   ((TextView) findViewById(R.id.textView)).setText(p);}

and this is my Client class

public class Client {

public String prova;
public String get() {

    String url = "FILE_JSON_ONLINE_URL";
    AsyncHttpClient client = new AsyncHttpClient();

    client.get(url, null, new

            JsonHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                    prova = response.toString();
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {

                }
            });
    return prova;
}

But my texview is empty, it's like the command client.get doesn't works, somebody can help me

Tappo
  • 31
  • 3

1 Answers1

1

This is because your public String get() method of the Client class returns prova before the onSuccess() sets it a value.

This is normal because it is an asynchronous call.

In your case you have to create an interface to handle async call, in your public String get() method, like this:

public class Client {

    // This interface will be used in your get() method, and implement in your first snippet
    public interface MyClientCallback {
        public void onResponse(String value);
    }

    // Add your interface as param
    public void get(MyClientCallback callback) {

        ```
        // prova = response.toString();
        callback.onReponse(response.toString());
        ```

    }
}

Then you can call it like that:

TextView textView = (TextView) findViewById(R.id.textView);
c.get(new MyClientCallback() {
    @Override
    public void onResponse(String value) {
        textView.setText(value);
    }
});

I hope it will help you.

MrLeblond
  • 1,005
  • 9
  • 26