-1

I'm trying to populate my ListView with JSONObjects, which I have obtained from a RESTApi.

I'm calling the following method to get the Json string "result".

protected void onPostExecute(String result) {
    try {

        //Filling the JSONArray "list" with the given result
        item = new JSONArray(result);

        Toast.makeText(getBaseContext(), "Received!" + item.toString(), Toast.LENGTH_LONG).show();

        //LIST DOES EXIST WITH THE TOAST!

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

But whenever I try to call it, where I'm checking to see if the JSONArray contains the JSONObjects, the JSONArray is empty.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //This is where I call the function from above
    new HttpAsyncTask().execute("http://rest-chaase.rhcloud.com/api/products");

    //Testing to see if the list exists
    Toast.makeText(getBaseContext(), "Received!" + item.toString(), Toast.LENGTH_LONG).show();

    //LIST DOESN'T EXIST (NullPointerException)
}

Why does the JSONArray "list" reset?

Detilium
  • 2,729
  • 7
  • 26
  • 60
  • The value you are accessing its not available yet, because the AsyncTask is still processing. I think what you want is in on this link http://stackoverflow.com/a/7423631/706833 – iGoDa Mar 04 '15 at 12:44
  • Ofcourse. That makes sense – Detilium Mar 04 '15 at 12:59

1 Answers1

0

I should've done my research before posting this question.

The fix is simple.

To fill the array simply use

item = new JSONArray(new HttpAsyncTask().execute("REST-LINK").get());
Detilium
  • 2,729
  • 7
  • 26
  • 60