Juan Pablo, checking your code, within doInBackground()
of your Asynctask
you get a String (surely a .json) from which you will get a JSONObject
which will be sent to onPostExecute()
:
public class JSONRequest extends AsyncTask <String, Void, JSONObject>{
private JSONCallback activity;
public JSONRequest(JSONCallback activity){
this.activity = activity;
}
@Override
protected JSONObject doInBackground(String... params) {
//Recibe un String en formato .json y obtiene un JSONObject.
JSONObject result = null;
}
protected void onPostExecute(JSONObject jsonObject) {
//Recibe el JSONObject obtenido en doInBackground().
super.onPostExecute(jsonObject);
activity.callBack(jsonObject);
}
Based on the above we will focus on the method doInBackground()
, here the question is what is the JSON object you want to obtain, in advance you need to know the name to obtain it, for example let's say your JSONObject is called "datos"
:
@Override
protected JSONObject doInBackground(String... params) {
//Recibe un String en formato .json y obtiene un JSONObject.
JSONObject data = params[0].getJSONObject("datos");
//JSONObject result = null;
}
I consider your question a bit broad, add an example of what you need, regularly a parameter to initialize your Asynctask should be the url of the Json file and from this you get either JSONObject
or% JSONArray
, This is an example:
class JSONParser extends AsyncTask<String, Void, JSONObject>{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
String url;
List<NameValuePair> params;
public JSONParser(String url, List<NameValuePair> params) {
this.url = url;
this.params = params;
}
@Override
protected JSONObject doInBackground(String... args) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException 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();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Error", e.getMessage());
}
// Parsea el string a JSONobject.
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// retorna el objeto JSON.
return jObj;
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
activity.callBack(jsonObject);
}
}