Parse JSON objects in AsyncTask

One way of managing data is with JSON files. These files are often linked to websites in order to provide the user with data once the file is parsed. To begin, make a class that extends an AsyncTask. Within the class, initialize a progress dialogue to run while the parsing occurs. To begin the dialogue, override onPreExecute(), set the dialogue message, and show.


public class mGetPosts extends AsyncTask<String, List<String>, List<String>> {

private final ProgressDialog dialog = new ProgressDialog(this);

List<PostItem> postList = new ArrayList<PostItem>();

@Override

protected void onPreExecute() {

    super.onPreExecute();

    dialog.setMessage("Searching for item...");

    dialog.show();

}

Here is the sample json file we will be parsing. You can see that the main object is “posts”, which contains a JSONArray: “usr_id”, “usr_name”, “usr_drive”, “usr_numseats”, “loc_startaddress”, “loc_endaddress”, “loc_posttime”, and “loc_postdate”.

{"posts":[
{"usr_id":"1000010012342","usr_name":"Carpool Tester","usr_drive":"Y","usr_numseats":"4","loc_startaddress":"Tallahassee, Fl","loc_endaddress":"Orlando, Fl","loc_posttime":"03:00:00","loc_postdate":"2011-11-22"},
{"usr_id":"1000010012342","usr_name":"Carpool Tester","usr_drive":"Y","usr_numseats":"4","loc_startaddress":"Tallahassee, Fl","loc_endaddress":"Orlando, Fl","loc_posttime":"03:00:00","loc_postdate":"2011-11-22"},
{"usr_id":"100003144620265","usr_name":"Carpool Tester","usr_drive":"N","usr_numseats":"","loc_startaddress":"My house","loc_endaddress":"Your house","loc_posttime":"03:04:00","loc_postdate":"2011-11-22"}]}

Next, we want to perform the actual retrieval and parsing. To do this, within doInBackground(), set the url to where the json file is and execute the HttpGet. This returns an HttpResponse which contains the json data as a String. Next, build a JSONObject from the string.


@Override

protected List<String>doInBackground(String... params) {

    StringBuilder url = new StringBuilder(params[0]);

    HttpGet geturl = new HttpGet(url.toString());

    HttpClient client = new DefaultHttpClient();

    HttpResponse response;

    try {

        response = client.execute(geturl);

        int status = response.getStatusLine().getStatusCode();

        if (status == 200) {

            HttpEntity entity = response.getEntity();

            String data = EntityUtils.<em>toString</em>(entity);

            JSONObject item = new JSONObject(data);

            /* Starts function which performs the parsing and stores

               All PostItems in a List<PostItem> */

            postList = parseJson(item);

            return postList;
        }

    // Catches any errors from the url or JSONObject

    } catch (ClientProtocolException clientExcep) {

        clientExcep.printStackTrace();

    } catch (IOException ioExcep) {

        ioExcep.printStackTrace();

    } catch (JSONException jsonExcep) {

        jsonExcep.printStackTrace();
    }

        return null;

}

The parseJson() function performs the actual parsing. It iterates through the array of JSON objects and stores the data into a PostItem. Then, each individual PostItem is added to the List<PostItem>.


public static List<PostItem> parseJson(JSONObject item) {

    String userId;

    String userName;

    char userDrive;

    char numSeats;

    String locAddress;

    String endAddress;

    String postTime;,

    String postDate;

    List<PostItem> postList = new ArrayList<PostItem>();

    JSONArray jsonArray;

    PostItem post = new PostItem();

    if(item != null) {

        jsonArray = item.getJSONArray(“posts”);

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

            JSONObject postItem = jsonArray.getJSONObject(counter);

            post.setUserId(postItem.getString(“usr_id”));

            post.setUserName(postItem.getString(“usr_name”));

            post.setUserDrive(postItem.getString(“usr_drive”));

            post.setNumSeats(postItem.getString(“usr_numseats”));

            post.setStartAddress(postItem.getString(“loc_startaddress”));

            post.setEndAddress(postItem.getString(“loc_endaddress”));

            post.setPostTime(postItem.getString(“loc_posttime”));

            post.setPostDate(postItem.getString(“loc_postdate”));

            postList.add(post);

        }

    }

    return postList;

}

 


public class PostItem {

    private String mUserId;

    private String mUserName;

    private Char mUserDrive;

    private Char mNumSeats;

    private String mStartAddress;

    private String mEndAddress;

    private String mPostTime;,

    private String mPostDate;

    public static String setUserId(String userId) {

        mUserId = userId;

        return mUserId;

    }

    public static String getUserId() {

        return mUserId;

    }

    public static String setUserName(String userName) {

        mUserName = userName;

        return mUserName;

    }

    public static String getUserName() {

        return mUserName;

    }

    public static String setUserDrive(char userDriver) {

        mUserDrive = userDrive;

        return mUserDrive;

    }

    public static char getUserDrive() {

        return mUserDrive;

    }

    public static char setNumSeats(char numSeats) {

        mNumSeats = numSeats;

        return mNumSeats;

    }

    public static char getNumSeats() {

        return mNumSeats;

    }

    public static String setStartAddress(String startAddress) {

        mStartAddress = startAddress;

        return mStartAddress;

    }

    public static String getStartAddress () {

        return mStartAddress;

    }

    public static String setPostTime(String postTime) {

        mPostTime = postTime;

        return mPostTime;

    }

    public static char getPostTime() {

        return mPostTime;

    }

    public static String setPostDate(String postDate) {

        mPostDate = postDate;

        return mPostDate;

    }

    public static char getPostDate() {

        return mPostDate;

    }

}

Finally, after storing the List<PostItem>, we simply return postList from the doInBackground() function. However, we must also override the onPostExecute() function to dismiss the dialog before the List<PostItem> is returned.


protected void onPostExecute(List<String> posts) {

    dialog.dismiss();

}

In order to call the AsyncTask we use:


List<PostItem> postList = new mGetPosts().execute(/* URL */).get();