-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,868
  • 9
  • 30
  • 65

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,868
  • 9
  • 30
  • 65