Get returned JSON from AsyncTask - android

So I have this loader class which extends AsyncTask. Then I do new loader().execute(); but I want to use the JSONArray response which my loader class returns how do I do that? Because I need it in several different places? Or should I just move my code to onPostExecute and do everything from there?
public class loader extends AsyncTask<String, Integer, JSONArray> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(ChallengeList.this, "", "Laddar...");
dialog.setCancelable(true);
}
#Override
protected JSONArray doInBackground(String... params) {
JSONArray response = null;
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(listURL);
try {
HttpResponse resp = client.execute(httppost);
StatusLine statusLine = resp.getStatusLine();
int statusCode = statusLine.getStatusCode();
Log.i("Statuscode", "statusCode"+statusCode);
if (statusCode == 200) {
final JSONObject json = new JSONObject();
json.put("userID", prefs.id());
response = SendHttp.parseHttp(listURL, json);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return response;
}
protected void onPostExecute(JSONArray result) {
dialog.dismiss();
}
}

The method onPostExecute has as parameter the JSONArray you returned from the doInBackground method.
onPostExecute runs on your main (caller) activity's thread, so besides dismissing the dialog in that method, you can process the result array further, pass it safely to other methods, etc:
#Override
protected void onPostExecute(JSONArray result)
{
super.onPostExecute(result);
final Message msg = new Message();
msg.obj = result;
if (youWantToUseHandler)
handler.dispatchMessage(msg);
else
writeJSONArray(result);
}
the handler:
final Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
final JSONArray result = (JSONArray)msg.obj;
writeJSONArray(result);
};
};
Some other method:
private void writeJSONArray(final JSONArray result)
{
for (int i = 0; i < result.length(); i++)
{
try
{
Log.d("SAMPLE", result.get(i).toString());
}
catch (JSONException e)
{
Log.e("SAMPLE", "error getting result " + i, e);
}
}
}
Since onPostExecute "Runs on the UI thread after doInBackground. The specified result is the value returned by doInBackground or null if the task was cancelled or an exception occured." ~API Docs
You can call any method you've declared in your class, and pass this array as a parameter to it.

After downloading the content web you can use the code below in onPostExecute method:
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for (int i=0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
Log.i("main",jsonPart.getString("main"));
Log.i("description",jsonPart.getString("description"));
}
} catch (Exception e) {
e.printStackTrace();
}
}

Related

Image duplicates in custom listview on scrolling

Whenever I am trying to remove an object from JsonArray , It shows there is no such method exists. My target API version is 8. I look up for other questions regarding this but could not find a suitable solution. please help me with this.
class JSONAsync extends AsyncTask<String, Void, JSONArray>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = Util.setProgressDialog(Activity.this, "Please Wait",
"loading....", false);
progressDialog.show();
}
#Override
protected JSONArray doInBackground(String... urls)
{
try
{
HttpGet httppost = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200)
{
HttpEntity entity = response.getEntity();
String resString = EntityUtils.toString(entity);
JSONObject jso= new JSONObject(resString);
JSONArray jsono= jso.getJSONArray("jobmasterto");
Log.e("jason array is this", ""+jsono);
for (int i = 0; i < jsono.length(); i++) {
if (jsono.getJSONObject(i).getString("jobName").equals(null) || jsono.getJSONObject(i).getString("jobName").equals("null") || jsono.getJSONObject(i).getString("jobName").equals("")) {
Log.e("Output : : ", jsono.getJSONObject(i).getString("jobName"));
jsono.remove(i);
}
}
if(jsono.length()>=0)
{
jobname = new String[(jsono.length())];
jobid = new String[(jsono.length())];
for(int i=0;i<jsono.length();i++)
{
JSONObject js = jsono.getJSONObject(i);
Log.e("Name : ", jsono.getJSONObject(i).getString("jobName"));
jobname[i] = jsono.getJSONObject(i).getString("jobName");
Log.e("Id : ", jsono.getJSONObject(i).getString("jobId"));
jobid[i] = jsono.getJSONObject(i).getString("jobId");
}
return jsono;
}
else
{
Toast.makeText(getApplicationContext(), "No Workers available : "+ logedinUserId , Toast.LENGTH_LONG).show();
return null;
}
}
} catch (IOException e)
{
e.printStackTrace();
} catch (JSONException e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONArray result)
{
progressDialog.dismiss();
}
}
Do you really want a headache supporting a bit amount of so old devices?
Nevertheless, use this:
JSONObject jso= new JSONObject(resString);
JSONArray jsonArray = jso.getJSONArray("jobmasterto");
Log.e("jason array is this", ""+jsonArray);
ArrayList<Integer> i_ar = new ArrayList<Integer>();
for (int i = 0; i < jsonArray.length(); i++) {
if (jsonArray.getJSONObject(i).getString("jobName").equals(null) || jsonArray.getJSONObject(i).getString("jobName").equals("null") || jsonArray.getJSONObject(i).getString("jobName").equals("")) {
Log.e("Output : : ", jsonArray.getJSONObject(i).getString("jobName"));
i_ar.add(i);
}
}
JSONArray jsono = new JSONArray();
int len = jsonArray.length();
if (jsonArray != null) {
for (int i=0;i<len;i++)
{
//Excluding the item at position
if (i_ar.indexOf(i) == -1)
{
list.put(jsonArray.get(i));
}
}
}
if(jsono.length()>=0)
{
//.... continue...

Progress Bar not visible with Stand alone asynctask

I am trying to fetch some data from Web Server through JSON. I am using asynctask to do so. Normally it is taking 5-10 seconds to be shown in my ListView.
Hence I want to put spinner progress bar. My code is working fine only problem is the progress bar is not visible.
MyActivity code to call asyntask
try{
JSONObject output = new AsyncTaskJsonParse(this,status, A, B, city).execute().get();
try {
JSONObject output = new AsyncTaskJsonParse(ListViewDisplay.this,status, bgrp, antigen, city).execute().get();
JSONObject src = output.getJSONObject("data");
String flag = output.getString("success");
String flagmsg = output.getString("message");
if (flag == "1") {
JSONArray jarr_name = new JSONArray(src.getString("name"));
JSONArray jarr_fathername = new JSONArray(src.getString("fathername"));
JSONArray jarr_moh = new JSONArray(src.getString("moh"));
JSONArray jarr_city = new JSONArray(src.getString("city"));
JSONArray jarr_phone = new JSONArray(src.getString("phone"));
int n = jarr_name.length();
name_array = new String[n];
fathername_array = new String[n];
moh_array = new String[n];
phone_array = new String[n];
city_array = new String[n];
for (int i = 0; i < n; i++) {
name_array[i] = (String) jarr_name.get(i);
fathername_array[i] = (String) jarr_fathername.get(i);
moh_array[i] = (String) jarr_moh.get(i);
phone_array[i] = (String) jarr_phone.get(i);
city_array[i] = "Vadodara";
Log.d("Inside StringArray", i + "");
}
String msg = src.getString("name");
list = (ListView) findViewById(R.id.listView);
CustomListAdapter custAdaptor = new CustomListAdapter(this, name_array, fathername_array, mohalla_array, city_array, phone_array);
list.setAdapter(custAdaptor);
}else
{
Toast.makeText(this, "Data not found" + flagmsg, Toast.LENGTH_LONG).show();
}
}catch(ExecutionException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(InterruptedException e)
{
e.printStackTrace();
}catch(JSONException je)
{
}
Standalone asyntask with progressbar code
public class AsyncTaskJsonParse extends AsyncTask<String, String, JSONObject>
{
String A,B;
private String url = "abc.com/check.php";
List<NameValuePair> param=new ArrayList<NameValuePair>();
private Context context;
private ProgressDialog progress;
public AsyncTaskJsonParse(Context context,String A,String B,String antigen,String city)
{
this.A=A;
this.B=B;
this.city=city;
this.context=context;
progress=new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.e("In preexecution ", "Preexecution 1");
progress.setMessage("Processing...");
progress.setIndeterminate(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setCancelable(true);
Log.e("In preexecution azam", "Preexecution 2");
progress.show();
if(progress.isShowing())
{
Log.d("In preexecution ", "Showing 2");
}
}
//rest of code i.e. doInBackground and postexecute come after this.
#Override
protected JSONObject doInBackground(String... arg0) {
// TODO Auto-generated method stub
try
{
JsonParsor parse=new JsonParsor();
Log.d("diInbackgrnd ","Dialog box");
jsonobj = parse.getJSONFromUrl(url, param);
}
catch(Exception e)
{
Log.e(TAG, " "+e );
}
return jsonobj;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//pDialog.dismiss();
if(progress.isShowing())
{
Log.e("In onPost ", "Showing 2");
}
progress.dismiss();
}
}
In my log I can see the message "In preexecution Showing 2". And the appliaction is working as expected but the Spinner progressbar is not visible.
Note: I did not add any progressbar component in any xml file. Does i need to add it? if yes then where and how?
class JsonParser.java
public class JsonParsor {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String str = "";
public JSONObject getJSONFromUrl(String url,List<NameValuePair> params) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(is,"iso-8859-1"), 8);
StringBuilder builder=new StringBuilder();
String line=null;
while((line=br.readLine())!=null)
{
builder.append(line + "\n");
}
is.close();
str=builder.toString();
}
catch(Exception e)
{
}
try {
jObj=new JSONObject(str);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jObj;
}
}
I suspect your problem is that your AsyncTask finishes immediately as parse.getJSONFromUrl... is also Async. So whats happening is that progress.dismiss(); in onPostExecute invoked also immediately.
Try removing progress.dismiss(); from onPostExecute and see what happens
This should work. But without the progress.setMessage("Processing...");
You can still set that.
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity(),R.style.MyTheme);
dialog.setCancelable(false);
dialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
dialog.show();
}

How to use json object as return type of do in background asynchronous task android?

I am working with android.I had created an app in which json data is loaded in asynchronous task and do something in the onpost execute method. I used the following code
public class Feat extends Activity {
JSONArray user = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AsyncTask<Void, Void,Void> t = new AsyncTask<Void, Void,Void>()
{
#Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient httpclient2 = new DefaultHttpClient();
HttpPost httppost2 = new HttpPost("MY URL");
HttpResponse response2 = httpclient2.execute(httppost2);
HttpEntity entity2 = response2.getEntity();
is = entity2.getContent();
Log.e("log_tag", "connection success2222 ");
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
try
{
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb2 = new StringBuilder();
String line = null;
while ((line = reader2.readLine()) != null)
{
sb2.append(line + "\n");
}
is.close();
result2=sb2.toString();
res=result2.substring(3);
Log.i("result",""+res);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
try
{
jArray2 = new JSONArray(result2);
Log.w("Lengh",""+jArray2.length());
final String imgArray[] = new String[jArray2.length()];
String name[] = new String[jArray2.length()];
for(int i=0;i<jArray2.length();i++){
JSONObject json_data2 = jArray2.getJSONObject(i);
imgArray[i] = json_data2.getString("track_url");
name[i] = json_data2.getString("campaign_name");
} }
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray2;
}
#Override
protected void onPostExecute(Void result) {
setContentView(R.layout.ss);
t1=(TextView)findViewById(R.id.cat1);
}
};
t.execute();
}
Now how can i use return type of do in background in post execute method ??
This is the class I have used:
public class GetJSON extends AsyncTask<JSONObject, Integer, JSONObject> {
#Override
protected JSONObject doInBackground(JSONObject... arg0) {
//All the try, catch etc.
//be sure to end it with
return (yourJSONObject)
}
protected void onPostExecute(JSONObject result) {
//Your code
}
read json inside postexecute() like this
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return GET(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
try {
JSONObject json = new JSONObject(result);
JSONArray articles = json.getJSONArray("images");
image_first =new String[json.getJSONArray("images").length()]; //initializtion
image_second =new String[json.getJSONArray("images").length()];
for(int i=0;i<json.getJSONArray("images").length()/2;i++){
image_first[i] = (articles.getJSONObject(i).optString("image_first"));
}
for(int j=json.getJSONArray("images").length()/2;j<json.getJSONArray("images").length();j++){
image_second[j]= (articles.getJSONObject(j).optString("image_second"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Resuse of Async task code in my various file

I want to create an class file for Async task operation and from creating the object of that class file i want to access these method of async task with no of different class files with different parameters.
Methods of Async task include:-
OnPreExecute()-Want to start progress dialog same for each class.
doInbackground()-Want to perform background operation(like getting data from server) means passing parameter different for each class.
onPostExecute()-Dismiss the progress dialog and update the UI differnt for each class.
Now I'm writing the async task in my every class as inner class like the following:-
class loaddata extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddNewLineitem.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
}
});
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
"GET", params1);
compoment = json.getJSONArray(COMPONENT_CODE);
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
loadSpinnerData();
pDialog.dismiss();
}
}
And JSON parser class is as follows:-
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// 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();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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;
}
}
And in oncreate() I call this and it works fine:-
new loaddata().execute();
We can reuse Aysntask with different parameters. For this
1.Create an Interface so that we can reuse,pass and receive parameters
public interface BackgroundListener {
public Object[] startBackgroundWork(Object... objs);
public void endBackgroundWork(Object... objs);
public void beforeBackgroundWork();
}
2.Create a Class Extending Asyntask
BackgroundHandler.java
import android.os.AsyncTask;
public class BackgroundHandler extends AsyncTask<Object, Object[], Object[]>{
BackgroundListener backgroundListener;
public void setBackgroundListener(BackgroundListener aBackgroundListener)
{
this.backgroundListener = aBackgroundListener;
}
#Override
protected void onPreExecute() {
backgroundListener.beforeBackgroundWork();
}
#Override
protected Object[] doInBackground(Object... objs) {
return backgroundListener.startBackgroundWork(objs);
}
#Override
protected void onPostExecute(Object result[]) {
backgroundListener.endBackgroundWork(result);
}
}
Using in Activity
A.java
Class A extends Activity implements BackgroundListener
{
...onCreate()
{
BackgroundHandler backgroundHandler = new BackgroundHandler()
backgroundHandler.setBackgroundListner(this);
backgroundHandler.execute(new Object[]{url1});//pass any number of parameters of any object type
// show loading bar
}
public void beforeBackgroundWork()
{
pDialog = new ProgressDialog(A.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
.....
}
public Object[] startBackgroundWork(Object... objs)
{
// access and type convert the passed parameters like objs[0], objs[1]
//.... some time consuming stuff
//.... some time consuming stuff
String url_foralldropdowns = objs[0].toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url_foralldropdowns,
"GET", params1);
JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
//Create new list_compoment here instead of global declaration
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
retrun new Object[]{list_compoment};
}
public void endBackgroundWork(Object ...obj)
{
pDialog.dismiss();// hide loading bar
//access resultant parameters like objs[0], objs[1]
//user list_component will be in obj[0]
}
}
Similarly we can reuse in B.java
Class B extends Activity implements BackgroundListener
{
...
....
public void beforeBackgroundWork()
{
pDialog = new ProgressDialog(B.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
.....
}
public Object[] startBackgroundWork(Object... objs)
{
// access and type convert the passed parameters like objs[0], objs[1]
//.... some time consuming stuff
//.... some time consuming stuff
String url2 = objs[0].toString();
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
JSONObject json = jparser.makeHttpRequest(url2,
"GET", params1);
JSONArray compoment = json.getJSONArray(COMPONENT_CODE);
//Create new list_compoment here instead of global declaration
for (int i = 1; i < compoment.length(); i++) {
JSONObject c = compoment.getJSONObject(i);
String code = c.getString(CODE);
list_compoment.add(code);
}
retrun new Object[]{list_compoment};
}
public void endBackgroundWork(Object ...obj)
{
pDialog.dismiss();
.....
//user list_component will be in obj[0]
}
}
Asyntask is just a class like others. Apart from the main inhertited methods of AsyncTask you can create your own methods, constructor etc. So just create a separate class in separate file. pass the context as parameter of the constructor. you can pass other values also to define the tasks.
class Loaddata extends AsyncTask<String, String, String> {
public Loaddata( pass the params){
... set the params
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading Data. Please wait...");
pDialog.show();
}
protected void onPostExecute() {
// pDialog.dismiss();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
}

Asynctask never dies

I use asynctask to show data from json but asynctask show loading never dies, no error but loading and loading this code doInBackground function
#Override
protected void onPreExecute() {
progressDialog.show();
}
#Override
protected Integer doInBackground(String... arg0) {
// check for login response
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
//DatabaseHandler db = new DatabaseHandler(
// activity.getApplicationContext());
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL+id_user);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// Getting Array of Following
user = json.getJSONArray(KEY_USER);
// looping through All Following
for (int i = 0; i < user.length(); i++) {
JSONObject c = user.getJSONObject(i);
// Storing each json item in variable
nama = c.getString(KEY_NAMA);
instansi = c.getString(KEY_INSTANSI);
status = c.getString(KEY_STATUS);
responseCode = 1;
}
} else{
responseCode = 0;
}
}
} catch (NullPointerException e) {
e.printStackTrace();
}
catch (JSONException e) {
e.printStackTrace();
}
return responseCode;
}
#Override
protected void onPostExecute(Integer responseCode) {
if (responseCode == 1) {
headerNama = (TextView)activity.findViewById(R.id.headerNama);
headerInstansi = (TextView)activity.findViewById(R.id.headerInstansi);
buttonStatus = (Button)activity.findViewById(R.id.buttonStatus);
headerNama.setText(nama);
headerInstansi.setText(instansi);
buttonStatus.setText(status);
}else {
progressDialog.dismiss();
activity.showDashboardError(responseCode);
}
}
i think no probleme in doinbackground, please help thanks
You should dismiss your dialog like:
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}

Categories

Resources