Issue
I'm trying to create a class to retrieve a JsonArray from a url. This class extends AsyncTask to avoid creating multiple AsyncTasks on interfaces.
The class works fine on debugger, but I do not know what to do to get the return object. Can anyone help me?
Here's my class:
public class QueryJsonArray extends AsyncTask<String, Void, Void>{
JSONArray jsonRetorno = null;
@Override
protected Void doInBackground(String... params) {
InputStream is = null;
String result = "";
try {
Log.i(getClass().getName(), params[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet( params[0]);
HttpResponse response = httpclient.execute(httpGet);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity = response.getEntity();
is = entity.getContent();
}else{
is = null;
}
} catch(Exception e) {
e.printStackTrace();
}
if(is!=null){
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch(Exception e) {
e.printStackTrace();
}
try {
jsonRetorno = new JSONArray(result);
} catch(JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
And I want to retrieve like this:
QueryJsonArray obj = new QueryJsonArray();
JSONArray jArray = obj.execute(myUrl);
Thanks in advance.
Solution
You need to use a callback. Simply add the following…
variable:
private Callback callback;
inner-interface:
public interface Callback{
public void call(JSONArray array);
}
constructor:
public QueryJsonArray(Callback callback) {
this.callback = callback;
}
Additionally, change your class declaration to:
public class QueryJsonArray extends AsyncTask<Void, Void, JSONArray>
and change the return type of doInBackground
to JSONArray
.
At the end of doInBackground
, add:
return jsonRetorno;
Finally, add the following method with contents:
public void onPostExecute(JSONArray array) {
callback.call(array);
}
Now, to execute the task, just do:
QueryJsonArray obj = new QueryJsonArray(new Callback() {
public void call(JSONArray array) {
//TODO: here you can handle the array
}
});
JSONArray jArray = obj.execute(myUrl);
As a side note, you could greatly simplify all of this using a third party library, such as my droidQuery library, which would condense all of the above code to:
$.ajax(new AjaxOptions().url(myUrl).success(new Function() {
public void invoke($ d, Object… args) {
JSONArray array = (JSONArray) args[0];
//TODO handle the json array.
}
});
Answered By - Phil
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.