Sending/receiving an ArrayList to/from AsyncTask - android

Using JSON I have trimmed the URL of an online gallery and filled an array list with the image sources, or image URLs.
I now want to return the ArrayList back to the MainActivity so that I can then convert the ArrayList to an Array and use that Array of Image URLs to download the images and put them in a gridview.
My problem is that I am not returning the ArrayList from the AsyncTask to the MainActivity. Any pointers would be greatly appreciated.
Thanks for your time.
Main Activity:
public class MainActivity extends Activity {
public static ArrayList<String> list = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new myAsyncTask().execute(list);
Log.v("jknfsda: ",list.get(1));
//TextView line1 = (TextView) findViewById(R.id.line1);
//for(int i=0; i<list.size(); i++){
// line1.append(i+1 + ": " + list.get(i));
}
}
AsyncTask:
public class myAsyncTask extends AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
static String quellaGalleryInfo = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fwww.quellabicycle.com%2Fgallery%22&format=json&callback=";
public static ArrayList<String> urlArr = new ArrayList<String>();
#Override
protected ArrayList<String> doInBackground(ArrayList<String>... list) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(quellaGalleryInfo);
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null; // Hold all of the data from the URL
try{
HttpResponse response = httpclient.execute(httppost); //Response from webservice (may or may not get)
HttpEntity entity = response.getEntity(); // all the content from the requested URL along with headers etc.
inputStream = entity.getContent(); // get maincontent from URL
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"),8);// Read all data from inputStream until buffer is full
StringBuilder theStringBuilder = new StringBuilder();//Store all the data
String line = null;
while((line = reader.readLine())!=null){
theStringBuilder.append(line + "\n");
}
//read all the data from the buffer until nothing is left
result = theStringBuilder.toString(); // everything now inside result
}
catch (Exception e){
e.printStackTrace();
}
finally { //close inputstream
try{
if(inputStream !=null) inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
JSONObject jsonObject;
try{
Log.v("JSONParser Result: ", result);
jsonObject = new JSONObject(result);//object of all the data
JSONObject queryJSONObject = jsonObject.getJSONObject("query");//get query objects
JSONObject resultsJSONObject = queryJSONObject.getJSONObject("results");//get results object inside of query object
JSONObject bodyJSONObject = resultsJSONObject.getJSONObject("body");
JSONArray divJSONArray = bodyJSONObject.getJSONArray("div");
JSONObject div_position_zero = divJSONArray.getJSONObject(0);
JSONArray ulJSONArray = div_position_zero.getJSONArray("ul");
JSONObject ul_position_two = ulJSONArray.getJSONObject(2);
JSONArray liJSONArray = ul_position_two.getJSONArray("li");
for(int i=0; i < liJSONArray.length(); i++){
JSONObject li_position = liJSONArray.getJSONObject(i);
JSONObject a_JSONObject = li_position.getJSONObject("a");
JSONObject imgJSONObject = a_JSONObject.getJSONObject("img");
urlArr.add(imgJSONObject.getString("src"));//final object where data resides
}
for(String item : urlArr){
Log.v("JSONParser list items: ", item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
//protected void onPostExecute(ArrayList<String>... list){
// if(MainActivity.list.size()>0){
// MainActivity.list.clear();
//for(int i =0; i<urlArr.size();i++){
// Log.v("ope urlarr: ", urlArr.get(i));
//MainActivity.list.add(urlArr.get(i));
//}
}
}
}
It works up until here
Log.v("JSONParser list items: ", item);
and then my LogCat just goes blank.
Thanks again.

You can override the postexecute in the main activity as seen below.
new myAsyncTask({
#Override
void onPostExecute(ArrayList<String> Param){
//Should be able to do something here
}
}).execute();
reference
Returning an ArrayList in android AsyncTask class

As I can see, there are two mistakes:
The first is you are passing an instance of the list to the asynctask, but never filling it with result: instead you are creating and filling a new ArrayList called urlArr. You should fill the one retrieved in the doInBackground() parameters. Because of the varargs syntax, you can do it in this way:
ArrayList<String> myList = list[0];
This is because, in the vararg syntax, you can pass a variable number of arguments, and they will be represented as an array called, in your case, "list".
The second error is you cannot know when the asynctask execution will terminate. In the onCreate method you are going to read the result just after the call. But asynctask is basically a wrapper to a Java Thread, and is intended to execute code asyncronously. When you call
Log.v("jknfsda: ",list.get(1));
your array is probably still empty. You should use a callback to notify the activity the results are ready. A simple way to do it is to pass an activity instance to your asynctask class
new myAsyncTask(this).execute(list);
, retrieve it in the asynctask class and store it in a field
protected ArrayList<String> myAsyncTask(MainActivity context){...}
and, in the end, notify the activity in the onPostExecute calling a method in the activity. In example, if you created a method called myResultsAreReady() in the activity, you can call it as:
protected void onPostExecute(ArrayList<String>... list){
context.myResultsAreReady();
}
Obviously you can use that method for sending data to the activity, if you wish ;)

In your AsyncTask:
Return the correct value at the end of doInBackground, you are always returning null.
for(String item : urlArr){
Log.v("JSONParser list items: ", item);
}
return urlArr;
And you will have access to it in the onPostExecute, just uncomment yours and use the list parameter (you can can use a non static ArrayList too).

Related

Insert element in List with AsyncTask

I'm trying to load some JSON inside my Android App. On the MainActivity I have created one AsyncTask to download the JSON and to Parse it. Everything here works, but I have a problem to put everything inside a ListView.
I have created a Model (with 6 Strings) and the Adapter.
The problem is, I can't update the List with the new content inside the "doInBackground" function, and I don't know how to put everything inside the list.
If your Adapter is set up properly to listen to a List as its data source, then you will simply need to change the elements in the List and then notify the Adapter by calling one of the notify methods, such as adapter.notifyDataSetChanged().
However, since this is modifying UI elements, this will need to be run on the UI thread. The doInBackground() method of an AsyncTask is run on a separate thread than the UI thread so we need to do one of two things:
Wait until we're done in the separate thread and then notify the adapter
Tell the UI thread to notify the adapter
The first is easily done if we call adapter.notifyDataSetChanged() in the onPostExecuted method of an AsyncTask.
The second is easily done if we have a reference to an Activity object, by calling the runOnUiThread(Runnable) method.
Hope this helps.
doInBackground() method didn't have access to UI thread, so you can't do it. In your case you should update your ListView in onPostExecute method or you can use for this runOnUiThread() method directly in your doInBackground() method.
You can't update or put data in listview in doInBackground() method. You have to assign Adpter to Listview, onCreate() method of MainActivity and onPostExecute() Method update listview. I have posted below code snippet will be helpful.
public class MainActivity extends AppCompatActivity {
String json_string;
JSONObject jsonObject;
JSONArray jsonArray;
ContactAdapter contactAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new BackegroundTask().execute();
listView = (ListView)findViewById(R.id.listview);
contactAdapter = new ContactAdapter(this,R.layout.row_layout);
listView.setAdapter(contactAdapter);
}
class BackegroundTask extends AsyncTask<Void,Void,String>
{
String json_url;
String JSON_STRING;
#Override
protected void onPreExecute() {
json_url = "http://10.0.2.2/webapp/index.php";
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null){
stringBuilder.append(JSON_STRING+"\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
json_string = result;
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String id,username;
while (count<jsonArray.length()){
JSONObject job = jsonArray.getJSONObject(count);
id = job.getString("id");
username = job.getString("username");
Contacts contacts = new Contacts(id,username);
contactAdapter.add(contacts);
contactAdapter.notifyDataSetChanged();
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}

While sending Spinner Value to php file first time only its working

I want to pass the Spinner value to php and get some result and display into my TextView. when i use Toast to display the Selected value its working perfect.but while pass the value to the php file i am struck. I tried some ways. can some to fix my problem.
java file:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide(); //<< this for hide title bar
setContentView(R.layout.sales_order);
fg.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
public void onItemSelected(
AdapterView<?> parent, View view, int position, long id) {
if(goods_name1.getSelectedItem() !=null && goods_name1.getSelectedItem() !=""){
// WebServer Request URL
String serverURL = "http://IP/fs/getProductOneStock.php";
// Use AsyncTask execute Method To Prevent ANR Problem
new LongOperation().execute(serverURL);
}
}
public void onNothingSelected(AdapterView<?> parent) {
showToast("Spinner1: unselected");
}
});
}
// Class with extends AsyncTask class
private class LongOperation extends AsyncTask<String, Void, Void> {
// Required initialization
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(Sales_Order.this);
String data ="";
int sizeData = 0;
TextView pro_stock1 = (TextView)findViewById(R.id.tv_stock1);
Spinner fgStock = (Spinner)findViewById(R.id.spinner1);
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
try{
// Set Request parameter
data +="&" + URLEncoder.encode("data", "UTF-8") + "="+fgStock.getSelectedItem();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
pro_stock1.setText("Output : "+Error);
} else {
// Show Response Json On Screen (activity)
pro_stock1.setText( Content );
/****************** Start Parse Response JSON Data *************/
String OutputData = "";
JSONObject jsonResponse;
try {
/****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
jsonResponse = new JSONObject(Content);
/***** Returns the value mapped by name if it exists and is a JSONArray. ***/
/******* Returns null otherwise. *******/
JSONArray jsonMainNode = jsonResponse.optJSONArray("Finish_goods_mas");
/*********** Process each JSON Node ************/
int lengthJsonArr = jsonMainNode.length();
for(int i=0; i < lengthJsonArr; i++)
{
/****** Get Object for each JSON node.***********/
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
/******* Fetch node values **********/
String Stock1 = jsonChildNode.optString("Finish_goods_mas").toString();
OutputData += Stock1;
}
/****************** End Parse Response JSON Data *************/
//Show Parsed Output on screen (activity)
//jsonParsed.setText( OutputData );
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
my php file
<?php
require "db_config.php";
$Goods_name=$_POST['Goods_name'];
$sql = "select goods_min_level from Finish_goods_mas where Goods_name='".$Goods_name."'";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
//echo $row['cus_id']."<br />";
$json['Finish_goods_mas'][]=$row;
}
sqlsrv_free_stmt( $stmt);
echo json_encode($json);
?>
after make changes of doInBackground and onPreExecute() the Spinner value not pass to php file also i cannot get back result from php
When an asynchronous task is executed, the task goes through 4 steps:
1.onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
2.doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
3.onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
4.onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.
so textView.setText(strOrderNo); do it in onPostExecute(Result) override method

No value error in json parsing

This is my
I want to parse it but i am getting no value for theater how can i solve this problem?
My code is:
CustomizedListView.java
public class CustomizedListView extends Activity {
// All static variables
static final String URL ="";
// XML node keys
JSONArray theaters = null;
JSONObject json = null;
ListView list;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
json=new JSONObject();
try {
// Getting Array of Contacts
theaters = json.getJSONArray(KEY_SONG);
// looping through All Contacts
for(int i = 0; i < theaters.length(); i++){
JSONObject c = theaters.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(KEY_TITLE);
String distance = c.getString(KEY_DURATION);
String pincode = c.getString(KEY_ARTIST);
//String image = c.getString(TAG_MOVIEIMAGE);
// Phone number is agin JSON Object
// creating new HashMap
HashMap<String, String> map1 = new HashMap<String, String>();
// adding each child node to HashMap key => value
map1.put(KEY_TITLE,distance);
map1.put(KEY_DURATION,pincode);
map1.put(KEY_ARTIST,name);
//map.put(TAG_MOVIEIMAGE, image);
// adding HashList to ArrayList
songsList.add(map1);
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("this is error" +e);
}
// adding HashList to ArrayList
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, songsList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
}
I want to parse it but i am getting no value for theater how can i solve this problem?
My code is:I want to parse it but i am getting no value for theater how can i solve this problem?
My code is:
pl help me to resolve error..
You are not assigning any value to the json object, you have to do it in Async Task to fetch the feed from your service.
As #Abed El Majeed K has already said, you need to do it as an async task.
i've found that any downloading, or internet actions are required to be preformed on a separate thread & not on the MainUI.
An example:
public class task extends AsyncTask<String, Void, String>{
private StringBuilder inputStreamToString(InputStream is){
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedRead rd = new Buffer3edReader(new InputStreamReader(is));
while((rLine = rd.readLine()) != null){
answer.append(rLine);
}
return answer;
}
protected String doInBackground(String... param){
String uRL = "http://example.com";
URL url = new URL(uRL);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
return jsonResult;
}
protected void onPostExecute(String result){
JSONObject jsonResponse = new JSONObject(result);
JSONArray jsonNode = jsonResponse.getJSONArray(whatever_your_json_stream_is_called);
for(int i = 0; i < jsonMainNode.length(); i++){
JSONObject jsonchild = jsonNode.getJSONObject(i);
String some_value = jsonchild.getString(some_key);
...
}
}
}
by running requests on AsyncTask, you are not causing the MainUiThread to pause, or wait for the download to complete.
With that said, the JSON source you are using is incorrect.
JSON structure is like this:
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
here might help: http://json.org/

How to parse or read json file from external storage on Android app

I currently implemented parsing json from a server (url). But I couldn't find a way to parse json from sdcard (/Download/example.json). Can someone help me to solve this issue/change this code?
I used asyncTask for this. sample tutorial or sample code is more appreciated. (sorry for my English.)
public class Main extends Activity {
private TextView shopsDisplay;
private static String searchURL = "http://example.com/sample.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.baby);
//reference throughout class
shopsDisplay = (TextView)findViewById(R.id.tweet_txt);
new GetShops().execute(searchURL);
}
private class GetShops extends AsyncTask<String, Void, String> {
/*
* Carry out fetching task in background
* - receives search URL via execute method
*/
#Override
protected String doInBackground(String... shopsURL) {
//start building result which will be json string
StringBuilder shopsFeedBuilder = new StringBuilder();
//should only be one URL, receives array
for (String searchURL : shopsURL) {
HttpClient shopsClient = new DefaultHttpClient();
try {
//pass search URL string to fetch
HttpGet shopsGet = new HttpGet(searchURL);
//execute request
HttpResponse shopsResponse = shopsClient.execute(shopsGet);
//check status, only proceed if ok
StatusLine searchStatus = shopsResponse.getStatusLine();
if (searchStatus.getStatusCode() == 200) {
//get the response
HttpEntity shopsEntity = shopsResponse.getEntity();
InputStream shopsContent = shopsEntity.getContent();
//process the results
InputStreamReader shopsInput = new InputStreamReader(shopsContent);
BufferedReader shopsReader = new BufferedReader(shopsInput);
String lineIn;
while ((lineIn = shopsReader.readLine()) != null) {
shopsFeedBuilder.append(lineIn);
}
}
else
shopsDisplay.setText("Whoops - something went wrong!");
}
catch(Exception e){
shopsDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}
}
//return result string
return shopsFeedBuilder.toString();
}
/*
* Process result of search query
* - this receives JSON string representing shops with search term included
*/
protected void onPostExecute(String result) {
//start preparing result string for display
StringBuilder shopsResultBuilder = new StringBuilder();
try {
//get JSONObject from result
JSONObject resultObject = new JSONObject(result);
//get JSONArray contained within the JSONObject retrieved - "results"
JSONArray shopsArray = resultObject.getJSONArray("shops");
//loop through each item in the shops array
for (int t=0; t<shopsArray.length(); t++) {
//each item is a JSONObject
JSONObject shopsObject = shopsArray.getJSONObject(t);
//for if condition
String id = (String) shopsObject.get("id");
//get the name and description for each shops
if (id.equals("550")){
shopsResultBuilder.append(shopsObject.getString("name")+": ");
shopsResultBuilder.append(shopsObject.get("description")+"\n\n");
}
}
}
catch (Exception e) {
shopsDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}
//check result exists
if(shopsResultBuilder.length()>0)
shopsDisplay.setText(shopsResultBuilder.toString());
else
shopsDisplay.setText("Sorry - no shops found for your search!");
}
}
}
For JSONObject, use standard Java file I/O to read the file into a String, then pass it to the JSONObject constructor.
If you have a large JSON file, though, you may wish to switch to some other JSON parser (e.g., JsonReader), which may give you different options (e.g., use a FileReader with JsonReader).

Multiple Async Tasks for post in same activity

i wrote those threads:
How to manage multiple Async Tasks efficiently in Android
Running multiple AsyncTasks at the same time -- not possible?
but didnt find answer for my question, maybe someone can help..
I have android app which makes Login POST and getting json response,
if the Json is OK i need to POST another data to get another response.
i have extends Async Class which doing the post to the URL:
public class AsyncHttpPost extends AsyncTask<String, String, String> {
private HashMap<String, String> mData = null;
public AsyncHttpPost(HashMap<String, String> data) {
mData = data;
}
#Override
protected String doInBackground(String... params) {
byte[] result = null;
String str = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL
try {
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
Iterator<String> it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "UTF-8");
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (Exception e) {
return null;
}
return str;
}
#Override
protected void onPostExecute(String result) {
try {
JSONArray Loginjson = new JSONArray(result);
strStt = Loginjson.getJSONObject(0).getJSONObject("fields").getString("status");
if (strStt.equals("ERR")) {
ErrorMsg("Authentication failed");
} else if (strStt.equals("OK")) {
ErrorMsg("Login OK!!!");
ClientPage();
} else {
ErrorMsg("Connection Error");
}
} catch (JSONException e) {
ErrorMsg("Connection Error");
}
}
}
Now - i need to get another POST if the status is Error. do i need to make another Async class? with the same all procedures ? the issue is only the onPostExecute part is different.. actually the "doInBackground" will be always the same..
any idea how can i easily do multiple posts in the same activity?
Firstly, since your doInBackground() code will always stay the same, I recommend you move it into a general utility class.
Beyond that, you can go one of two ways:
Create a new AsyncTask for each type of request that can call your utility class, and have its own onPostExecute()
Create one AsyncTask that has a flag in it, which can be checked in the onPostExecute() method to see what code needs to be executed there. You will have to pass the flag in in the constructor or as a parameter in execute.
You can use a parameter at AsyncHttpPost constructor/execute or global variable to indicate if it is first or second POST (by other words - a flag). Then just create and execute another instance of AsyncHttpPost in onPostExecute (only if parameter/variable is set as "first POST").

Categories

Resources