Muddz Muddz - 6 months ago 11
Android Question

my PostExecute dosn't execute in my Async

I'm trying to read data from this API: http://events.makeable.dk/api/getEvents with the AsyncTask method which Is first time I try this. I'm trying to only read all TITLES from the API, but I'm not getting any titles.

Instead I get this exception:

W/System.err: org.json.JSONException: (...)

Which shows me the whole API.

I have put Log.d(); around my code and I can se that my code never do or reach something in
onPostExecute(String s)
and thats is maybe why I never get any TITLES.

The many examples on the web of how to do this is so different from eachother and makes this very frustrating to solve!

private class JsonParser extends AsyncTask<String, Void, String> {

HttpURLConnection conn;
URL url = null;

@Override
protected void onPreExecute() {


super.onPreExecute();
Toast.makeText(MainActivity.this, "LOADING DATA FROM API", Toast.LENGTH_SHORT).show();
}


@Override
protected String doInBackground(String... params) {

try{

url = new URL(URL);
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);

if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){

InputStream inputStream = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder result = new StringBuilder();
String line;


while ((line = reader.readLine())!= null){
result.append(line);
}

return (result.toString());
}

}catch (MalformedURLException e){
e.printStackTrace();
}catch (Exception ee){
ee.printStackTrace();
}

return "";

}


@Override
protected void onPostExecute(String s) {


//------ never comes below this area //-----------
try{

JSONArray jsonArray = new JSONArray(s);

for(int i =0; i<jsonArray.length(); i++){

JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.d("TAG", "JSON: " + jsonObject.getString("TITLE"));
}

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

}

Answer

I viewed your API's response at this Website. It is a JSON Object because it is started by an open curly brace {. So therefore use JSONObject first.

The response looks like this:

    {
       "success": true,
       "message": "548 events returned successfully",
       "last_change": 1459515263,
       "events": [
          {
             "category": "Musik",
             "category_id": "75",
             "datelist": [
                {
                   "start": 1436536800,
                   "end": 1436544000
                }
             ],
             "description": "",
             "description_english": "",
             "description_german": "",
             "eventgroup": "",
             "eventid": "55815f7fe714a",
             "family_friendly": "0",
             "last_updated": 1436166668,
             "location_address": "Klostertorv 1",
             "location_city": "Århus C",
             "location_id": "1593",
             "location_latitude": 56.158092,
             "location_longitude": 10.206756,
             "location_name": "Klostertorv",
             "location_postcode": "8000",
             "organizer_email": "",
             "organizer_name": "Café Smagløs ",
             "organizer_phone": "",
             "picture_name": "http://www.jazzfest.dk/img/photos_big/tcha-badjo---strings-og-buttons.jpg",
             "price": "-1",
             "subcategory": "Musik",
             "subcategory_id": "84",
             "subtitle": "",
             "subtitle_english": "",
             "subtitle_german": "",
             "tags": "Swing/Mainstream",
             "tickets_url": "",
             "title": "Tcha Badjo + Strings & Buttons KONCERT AFLYST",
             "title_english": "Tcha Badjo + Strings & Buttons CONCERT CANCELLED",
             "title_german": "Tcha Badjo + Strings & Buttons CONCERT CANCELLED",
             "url": "http://www.jazzfest.dk/?a=reviews&lang=&kryds_id=2122&y=2015",
             "user_id": "23",
             "video_url": ""
          }]
    }

So therefore it is:

       try {
            JSONObject object = new JSONObject(s);
            JSONArray events = object.getJSONArray("events");
            int evSize = events.length();

            for (int x = 0; x < evSize; x++) {
                JSONObject object1 = events.getJSONObject(x);
                String title = object1.getString("title");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }