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:

publicclassJSONParserextendsAsyncTask<String, Void, JSONObject> {
    publicinterfaceMyCallbackInterface {
        publicvoidonRequestCompleted(JSONObject result);
    }

    privateMyCallbackInterface mCallback;

    publicJSONParser(MyCallbackInterface callback) {
        mCallback = callback;
    }

    publicJSONObjectgetJSONFromUrl(String url) { /* Existing Method */ }

    @OverrideprotectedJSONObjectdoInBackground(String... params) {
        String url = params[0];            
        returngetJSONFromUrl(url);
    }

    @OverrideprotectedonPostExecute(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:

publicclassMyActivityextendsActivityimplementsMyCallbackInterface {
    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //...existing code...JSONParser parser = newJSONParser(this);
        parser.execute("http://my.remote.url");
    }

    @OverridepublicvoidonRequestComplete(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.

privateclassMyTaskextendsAsyncTask<Void, Void, JSONObject> {
    protectedJSONObjectdoInBackground(Void... params) {
        ...
        return json;
    }
    protectedvoidonPostExecute(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?"