Skip to content Skip to sidebar Skip to footer

JSON And Network Operation From An Asynctask?

I found an excellent JSON parser online, and I want to use it in my project. There will be lots of JSON requests, so I'd like to be able to reuse code. Here's the JSON parser: impo

Solution 1:

You can make the class you've already written into an AsyncTask where the doInBackground() method returns a JSONObject. In AsyncTask land, the value returned from doInBackground() (the method called on a background thread) is passed to onPostExecute() which is called on the main thread. You can use onPostExecute() to notify your Activity that the operation is finished and either pass the object directly through a custom callback interface you define, or by just having the Activity call AsyncTask.get() when the operation is complete to get back your parsed JSON. So, for example we can extend your class with the following:

public class JSONParser extends AsyncTask<String, Void, JSONObject> {
    public interface MyCallbackInterface {
        public void onRequestCompleted(JSONObject result);
    }

    private MyCallbackInterface mCallback;

    public JSONParser(MyCallbackInterface callback) {
        mCallback = callback;
    }

    public JSONObject getJSONFromUrl(String url) { /* Existing Method */ }

    @Override
    protected JSONObject doInBackground(String... params) {
        String url = params[0];            
        return getJSONFromUrl(url);
    }

    @Override
    protected onPostExecute(JSONObject result) {
        //In here, call back to Activity or other listener that things are done
        mCallback.onRequestCompleted(result);
    }
}

And use this from an Activity like so:

public class MyActivity extends Activity implements MyCallbackInterface {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //...existing code...

        JSONParser parser = new JSONParser(this);
        parser.execute("http://my.remote.url");
    }

    @Override
    public void onRequestComplete(JSONObject result) {
        //Hooray, here's my JSONObject for the Activity to use!
    }
}

Also, as a side note, you can replace all the following code in your parsing method:

is = httpEntity.getContent();           

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            is, "iso-8859-1"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "n");
     }
    is.close();
    json = sb.toString();
} catch (Exception e) {
    Log.e("Buffer Error", "Error converting result " + e.toString());
}

With this:

json = EntityUtils.toString(httpEntity);

Hope that Helps!


Solution 2:

Check AsyncTask documentation, 3rd generic type parameter is a Result, the type of the result of the background computation.

private class MyTask extends AsyncTask<Void, Void, JSONObject> {
    protected JSONObject doInBackground(Void... params) {
        ...
        return json;
    }
    protected void onPostExecute(JSONObject result) {
        // invoked on the UI thread
    }
}

make your task inner class of your activity, create activity's member private JSONObject mJSON = null; and in onPostExecute() do assignement mJSON = result;


Post a Comment for "JSON And Network Operation From An Asynctask?"