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:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
In my main activity, I need a way to retrieve the JSONObject that the parser returns. However, it needs to be done in a background thread.
I can't figure out how to return an object from an Asynctask. I was thinking about maybe wrapping the parser class in an Asynctask, and having it return when it's finished, but that gives the same conundrum.
Can anybody help?
Check AsyncTask documentation, 3rd generic type parameter is a Result, the type of the result of the background computation.
make your task inner class of your activity, create activity's member
private JSONObject mJSON = null;
and inonPostExecute()
do assignementmJSON = result;
You can make the class you've already written into an
AsyncTask
where thedoInBackground()
method returns aJSONObject
. InAsyncTask
land, the value returned fromdoInBackground()
(the method called on a background thread) is passed toonPostExecute()
which is called on the main thread. You can useonPostExecute()
to notify yourActivity
that the operation is finished and either pass the object directly through a custom callback interface you define, or by just having theActivity
callAsyncTask.get()
when the operation is complete to get back your parsed JSON. So, for example we can extend your class with the following:And use this from an Activity like so:
Also, as a side note, you can replace all the following code in your parsing method:
With this:
Hope that Helps!