Passing functions into a global AsyncTask Android - android

I'm trying to create a global actions file in which i can call certain functions globally anywhere within the app. so far i have got it working with functions etc but now what i'm wanting to do is put a standard AsyncTask into my global actions and pass it functions/voids from my Activity so i'd want to pass it a function to run in background and a function to run once finished. does anyone know how do this? and also advise me on running multiple functions on a background thread do i create one AsyncTask and feed in multiple functions or do i create multiple AsyncTasks?
heres an example of what i have managed to do globally so far and how i'm currently implementing my Asynctask. Just to reiterate i'm trying to move the asynctask into a global actions and make it as reusuable as possible
in my Global Actions im creating a function that formulates a URL and sends post variables to that url which then feedsback a JSON response. then in my Activity i have created a function to both call that request and then Log the response
My Global Actions
public final static JSONObject startAPICallRequest(Context activityContext, String requestReference, String callLocation, Map<String, String> postVarsMap, Map<String, String> getVarsMap){
long unixTimeStamp = System.currentTimeMillis() / 1000L;
StringBuilder extraGetVarsString = new StringBuilder();
if(getVarsMap != null){
Map<String, String> map = (Map)getVarsMap;
for (Entry<String, String> entry : map.entrySet()) {
extraGetVarsString.append("&" + entry.getKey() + "=" + entry.getValue());
extraGetVarsString.toString();
}
}
String appVersion = null;
try {
appVersion = activityContext.getPackageManager().getPackageInfo(activityContext.getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
appVersion = activityContext.getResources().getString(R.string.appVersion);
}
String getVarsString = "?timestamp=" + unixTimeStamp + "&app_version=" + appVersion + extraGetVarsString;
String apiLocation = activityContext.getResources().getString(R.string.apiLocation);
String fullAPIURL = apiLocation + callLocation + getVarsString;
Log.v("globals", "fullAPIURL=" + fullAPIURL);
String api_key = activityContext.getResources().getString(R.string.apiKey);
String api_user = activityContext.getResources().getString(R.string.apiUser);
String request_token = returnSHAFromString(api_key, fullAPIURL);
String device_id = returnStringFromPreference(activityContext,"device_id");
String user_token = returnStringFromPreference(activityContext,"user_token");
List<NameValuePair> postVarsList = new ArrayList<NameValuePair>();
postVarsList.add(new BasicNameValuePair("request_token", request_token));
postVarsList.add(new BasicNameValuePair("api_user", api_user));
postVarsList.add(new BasicNameValuePair("device_id", device_id));
postVarsList.add(new BasicNameValuePair("user_token", user_token));
if(postVarsMap != null){
Map<String, String> map = (Map)postVarsMap;
for (Entry<String, String> entry : map.entrySet()) {
postVarsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
JSONObject responseJSON = null;
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(fullAPIURL);
post.setEntity (new UrlEncodedFormEntity(postVarsList));
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String jsonResponse = reader.readLine();
Log.v("globals", "postList =" + postVarsList );
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responseJSON;
}
MY Activity
public void apiCall(){
responseJSON = GlobalActions.startAPICallRequest(this, "login", "my-network/", null, null);
}
public class PostTask extends AsyncTask<Void, String, Boolean> {
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Void... params) {
apiCall();
boolean result = false;
publishProgress("progress");
return result;
}
protected void onProgressUpdate(String... progress) {
StringBuilder str = new StringBuilder();
for (int i = 1; i < progress.length; i++) {
str.append(progress[i] + " ");
}
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
checkLoginData();
}
}
public void checkLoginData(){
Log.v("IntroLoader", "responseJSON = " + responseJSON);
Intent register = new Intent(getApplicationContext(), LoginForm.class);
startActivity(register);
}

Using AsyncTask for calling REST API methods is not really correct approach. Your code has 2 problems:
There is no guarantee that your API call will be finished when Activity is closed because process can be killed
You have memory leak because PostTask can hold Activity reference even while Activity can be already destroyed
Consider using IntentService for making background requests and e. g. ResultReceiver for handling results in your Activity.

It looks like you need a Handler and a Looper. You will be able to post() and postDelayed(). http://developer.android.com/reference/android/os/Handler.html
See also:
Is AsyncTask really conceptually flawed or am I just missing something?

I'm no Java expert but I don't think you pass functions around in Java. To simplify the matter, what you want to do is call a function in your Activity class when AsyncTask is complete?

Related

Simplest straight forward way to get a JSON String from a REST URL

I am trying to get a JSON string from a url and save it into SQLite in my android app.
I was trying some tutorials then realize the suggested methods has a void return type. Are there a more simple straight forward way of getting a JSON String and putting it into an arraylist ready to be saved into SQLite?
Below is what I was stuck at a helper class that gets the data from the url
as they said that the main thread OnCreate does not allow a background process like this. Is there a way to change the return type of AsyncTask or is there a more simple way to fetch JSON String with android?
public class FetchData extends AsyncTask<Void, Void, Void> {
#Override
protected void doInBackground(ArrayList<String>... voids) {
try {
URL url = new URL("http://192.168.403.211/api/wordsupdate.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader (new InputStreamReader(inputStream));
String line ="";
while (line != null) {
line = bufferedReader.readLine();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Go with Volley API. Check the code below which demonstrate POST request. Hope you'll get useful information.
public void getAddress(final String uid) {
String url = "Add Url Here"; // Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray dataArray;
JSONObject jsonObject;
address_ids = new ArrayList<>();
address_names = new ArrayList<>();
address_line1 = new ArrayList<>();
address_line2 = new ArrayList<>();
address_state = new ArrayList<>();
address_district = new ArrayList<>();
address_taluka = new ArrayList<>();
address_pincode = new ArrayList<>();
address_status = new ArrayList<>();
address_default = new ArrayList<>();
try {
jsonObject = new JSONObject(response);
dataArray = jsonObject.getJSONArray(JSON_ARRAY);
//adding response values to respective array
for (int i = 0; i < dataArray.length(); i++) {
//Creating a json object of the current index
JSONObject obj;
try {
//getting json object from current index
obj = dataArray.getJSONObject(i);
address_ids.add(obj.getString(TAG_ADDRESS_ID));
address_names.add(obj.getString(TAG_ADDRESS_NAME));
address_line1.add(obj.getString(TAG_ADDRESSLINE_FIRST));
address_line2.add(obj.getString(TAG_ADDRESSLINE_SECOND));
address_state.add(obj.getString(TAG_STATE));
address_district.add(obj.getString(TAG_DISTRICT));
address_taluka.add(obj.getString(TAG_TALUKA));
address_pincode.add(obj.getString(TAG_PINCODE));
address_status.add(obj.getString(TAG_ADDRESS_STATUS));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//setting up response values to the fragment
//Toast.makeText(getActivity(), "Error:"+response, Toast.LENGTH_LONG).show();
Log.e(TAG, "onResponse: " + response);
address_name.setText("Name : " + address_names.get(0));
address.setText("Address : " + address_line1.get(0) + "," + address_line2.get(0) + "-" + address_pincode.get(0));
taluka.setText("Taluka : " + address_taluka.get(0));
district.setText("District : " + address_district.get(0));
state.setText("State : " + address_state.get(0));
mCircularProgressBar.setIndeterminate(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplication(), "Taking bit longer", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("mk_address_id", address_id);
return params;
}
};
queue.add(stringRequest);
}
Check this link from Android developer, you can find more info their.
In your code change the "extends" from
AsyncTask<Void, Void, Void>
to
AsyncTask<Void, Void, String>
and the doInBackground method to
protected String doInBackground(ArrayList<String>... voids)
and you will get the string back in the onPostExecute method
Yes there is a way to change the return types: Have a look at your extends AsyncTask: It says AsyncTask<Void, Void, Void>.
According to Android Developers, this means <Params, Progress, Result>.
This means that your
ArrayList<String>... voids won't work too, because you have the Params part set to Void but try to get an ArrayList<String>.
So, to solve your problem, change the three Voids to whatever you need it to input and output.
However, to deserialize JSON you should use an external library (or use a 3rd party library for REST calls altogether).
//AsyncTask has onPostExecute which will be called after background execution, where you will get the result in mainthread
class FetchData extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("http://192.168.403.211/api/wordsupdate.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
//Your result String is here which runs on MAIN THREAD
super.onPostExecute(result);
}
}
Retrofit 2 will help you - easy and simple
Edit : For Async task see the top answer here
What arguments are passed into AsyncTask<arg1, arg2, arg3>?
In your code snippet , you specified AsyncTask params types are Void. Void means , it does't have any return value. As per AsyncTask Syntax,
You have to specify three arguments.
1- InputType- DoInBanckground
2- ProgressType - Publish Progress.
3- OutputType - OnPostExecute.
The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
In your snippet doInBackground method and AsycTask types are mismatching .
For more information : https://developer.android.com/reference/android/os/AsyncTask.html

Checking the AsyncTask status seems not working correctly (log doesn't appear on log cat)

I'm trying to see how works an Asynctask class in android. In particular i want reveal in real time the status of the class for see when it is running and when it has finished. For do this, i have created a class that extend the main activity and another class that is the asynctaks class.
This is my main class:
public class PhotoManagement extends Activity{
private String numberOfSelectedPhotos;
private Bitmap currentImage;
private String initConfiguration = "http://www.something.com";
private String response;
private ArrayList<String> formatPhotoList = new ArrayList<String>(); //create a list that will contains the available format of the photos downloaded from the server
private ArrayList<String> pricePhotoList = new ArrayList<String>(); //create a list that will contains the available price for each format of the photos
DownloadWebPageTask webPage = new DownloadWebPageTask();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume(){
super.onResume();
webPage.execute(initConfiguration);
if(webPage.getStatus() == AsyncTask.Status.PENDING){
Log.i("STATUS","PENDING");
}
if(webPage.getStatus() == AsyncTask.Status.RUNNING){
Log.i("","RUNNING");
}
if(webPage.getStatus() == AsyncTask.Status.FINISHED){
Log.i("","FINISHED");
}
}
}
As you can see i want only see the passages of the status with a simple log.
And here there is the asynctask class.
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient(); //create a new http client
HttpGet httpGet = new HttpGet(url); //create a new http request passing a valid url
try {
HttpResponse execute = client.execute(httpGet); //try to execute the http get request
InputStream content = execute.getEntity().getContent(); //prepare the input stream to read the bytes of the request
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s; //until is present a line to read, the response variable store the value of the lines
}
} catch (Exception e) {
Log.i("MyApp", "Download Exception : " + e.toString()); //Print the error if something goes wrong
}
}
return response; //return the response
}
#Override
protected void onPostExecute(String result) {
result = doInBackground(initConfiguration); //take the result from the DownloadWebPageTask class
result = result.replace("null", "");
Log.i("RESULT",""+result);
//find the price and format value from the result using XmlPullParser
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader ( result ) );
int attributeNumber = xpp.getAttributeCount();
int eventType = xpp.getEventType();
String currentTag = null;
while(eventType != XmlPullParser.END_DOCUMENT){
if(eventType == XmlPullParser.START_TAG) {
currentTag = xpp.getName();
if (currentTag.equals("product")){
xpp.getAttributeValue(null, "name");
formatPhotoList.add(xpp.getAttributeValue(null, "name"));
Log.i("FORMAT PHOTO",""+xpp.getAttributeValue(null, "name"));
}
}
eventType = xpp.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
Log.i("","ERROR XML PULL PARSER");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("","ERROR IOEXCEPTION");
}
}
}
}
As you can see i have implemented also the method onPostExecute that should be called when the asynctask method has finished to execute the instructions right?
So at this point i don't understand why my log RUNNING and my log FINISHED never appear on the log cat.
What i'm doing wrong?
I'm tried to follow this topic Android, AsyncTask, check status? but in my case it isn't working.
Thanks
Problem :
You are creating object like
DownloadWebPageTask webPage = new DownloadWebPageTask();
But you are calling asynctask on different object,
new DownloadWebPageTask().execute(initConfiguration);
Solution :
It should be like
webPage.execute(initConfiguration);
#Override
protected void onResume(){
super.onResume();
new DownloadWebPageTask().execute(initConfiguration);
here do like this
#Override
protected void onResume(){
super.onResume();
webPage.execute(initConfiguration);
You didn't implement webPage.execute(), add it
Most probably the task hasn't finished or even started yet. As you probably know the AsyncTask is doing it's (background) work on a different thread, so your onResume is running in parallel with it. You can either use the task's get() method to wait for it to finish and get the result of the doInBackground() method and then query for it's status or notify your activity from the task's onPostExecute() method to let it know (and log) that it has finished. I don't recommend you the first option because it will actually block the UI thread and will make your usage of AsyncTask pointless.

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").

How to pass string array to my adapter in android

I am trying to pass a string array to my adapter. My problem is i initialized globally and try to create string array in my asynchronous task below. But i am getting as null. Below is my code. Actually in this example they taking it from resource folders bu i want it from my json response. Any help is appreciated.
String[] mString;
public ActionsAdapter(Context context) {
mInflater = LayoutInflater.from(context);
session = new SessionManager(context);
final Resources res = context.getResources();
new ConnectAppMenu(context).execute();
// mTitles = res.getStringArray(R.array.actions_names);
// mUrls = res.getStringArray(R.array.actions_links);
// mIcons = res.obtainTypedArray(R.array.actions_icons);
System.out.println("Menus"+ mString);
}
public class ConnectAppMenu extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
private final Context context;
public ConnectAppMenu(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// UI work allowed here
dialog = new ProgressDialog(context);
// setup your dialog here
dialog.setMessage("Connecting....");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
String returnConnect = doConnectAppMenu();
return returnConnect;
}
public String doConnectAppMenu() {
HashMap<String, String> user = session.getUserDetails();
String client_url = user.get(SessionManager.KEY_CLIENT);
// if(connection) {
HttpParams connectionParameters = new BasicHttpParams();
int timeoutConnection = 8000;
HttpConnectionParams.setConnectionTimeout(connectionParameters, timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(connectionParameters, timeoutSocket);
HttpClient httpClient = new DefaultHttpClient(connectionParameters);
HttpPost httpPost = new HttpPost(client_url+"/api/common/app_menu");
JSONObject json = new JSONObject();
try{
json.put("data", 1);
json.put("versionid", 1);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
//Execute HTTP post request
appmenu_res = httpClient.execute(httpPost);
appmenu_obj = new org.json.JSONObject(org.apache.http.util.EntityUtils.toString(appmenu_res.getEntity()));
appmenu_result = appmenu_obj.toString();
}
catch(JSONException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// }
return appmenu_result;
}
#Override
public void onPostExecute(String result) {
int status_code = appmenu_res.getStatusLine().getStatusCode();
if (status_code == 200) {
dialog.dismiss();
try {
menuObject = new JSONObject(result);
JSONArray names= menuObject.names();
JSONArray values = menuObject.toJSONArray(names);
for (int i = 0; i< values.length(); i++) {
JSONObject json2 = (JSONObject) values.get(i);
int menu_id = json2.getInt("menu_id");
if (menu_id > 0) {
if (json2.has("menu_name")) {
menu_list = json2.get("menu_name").toString();
mString = new String[] { menu_list };
//mUrls = menu_list.length();
}
}
}
System.out.println("Json Menu" + Arrays.toString(mString));
/*Iterator<String> iter = menuObject.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
Object value = menuObject.get(key);
//System.out.println("Hai" +value);
System.out.println("Post Execute" + value);
} catch (JSONException e) {
// Something went wrong!
}
}*/
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//dialog.dismiss();
}
}
}
well first of all if you're looking for the JSON object as a String don't do what you did here:
appmenu_obj = new org.json.JSONObject(org.apache.http.util.EntityUtils.toString(appmenu_res.getEntity()));
I'd suggest doing the following:
String Json = EntityUtils.toString(appmenu_res.getEntity());
return Json;
Now if you want to do the processing of your JSON on the UI thread (as you seem to want to based on the return type being a string) this should work. However this method is not recommended since the Json will need to be processed into objects which will take time and clog the UI thread.
A better solution would be to serialize your Json on the background thread and then pass the serialized object back to the main thread to update the UI.
If you have many types I would suggest using generics. I've already built a Loader which can do what you want if you want here. You will need touse the GSON library and build appropriate seralizers. Also working with the loader class is different to working with the AsyncTaskClass so please read the documentation here
Edit
Ok so what you want to do if you want get the Activity to have a callback from the AsyncTask is to do something along the lines of:
public class MyActivity extends Activity implements AsyncTaskCallback
where AsyncTaskCallback looks something like :
public interface AsyncTaskCallback
{
public processData(Object responseObject);
}
now in your onPostExecute code you'll need to do somehting like:
#Override
protected void onPostExecute(Object r){
if (r != null) {
l.processData(data);
}
}
and add the following function to your async task
public void addAsyncTaskListener (final AsyncTaskListener l){
mCallback = l;
}
and then finally add the listner and process the data as required in the Activity in the function processData function that the interface forces your activity to implement.
Instead of using String[] you can use ArrayList for Setting list in adaptor.

How to make a blocking Android HttpRequest

Here is my issue:
I have a list of values which I retrieve from server.
These values fill ListView in the UI.
I cannot continue loading the View and showing it to user until the list is full.
Since Android forces me to make http calls in separate thread, my question is how do I create 1 class that does the httprequests and in the calling class I wait until I get response from the HttpRequest and only then I proceed loading the View?
Right now I have this class that does the requests:
public class WapConnector extends AsyncTask<String, String, String>{
private static final String TAG = "WapConnector";
private String html = "";
private Handler mHandler;
private String server = "http://....whatever";
private String callUrl = "/api/";
private String params = "login?u=Admin&pw=234234&format=json";
private int _callstate = 1;
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
String fullUrl = "";
Log.i(TAG,fullUrl);
if(params.length() > 0){
fullUrl = server + callUrl + params + "&alf_ticket=" + Globals.getInstance().getTicket() + "&udid=" + Globals.getInstance().udid() + "&phoneNumber=" + Globals.getInstance().phoneNumber();
}
else{
fullUrl = server + callUrl + "?udid=" + Globals.getInstance().udid() + "&alf_ticket=" + Globals.getInstance().getTicket() + "&phoneNumber=" + Globals.getInstance().phoneNumber();
}
Log.i(TAG,fullUrl);
response = httpclient.execute(new HttpGet(fullUrl));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
Log.i(TAG,responseString);
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
e.printStackTrace();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.i(TAG + "onPostExecute",result);
activity.getClass().handleResponse();
//main load
JSONObject jobj;
JSONObject jvalue;
try {
jobj = new JSONObject(result);
if(_callstate == 1){
jvalue = jobj.getJSONObject("data");
String ticket = jvalue.getString("ticket");
Log.i("loginwap",ticket);
Globals.getInstance().setTicket(ticket);
_callstate = 2;
}
else{
jvalue = jobj.getJSONObject("countries");
JSONArray countries = jvalue.getJSONArray("countries");
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And this is how I make calls from Parent classes:
WapConnector wap = new WapConnector();
wap.setCallUrl("/anyurl/");
wap.callstate(3);
wap.setParams("");
wap.execute("");
Now my issue is that since the request runs in thread, once I call wap.execute(), my Activity continues to load, but I want it to wait until I get response, parse the response and only then continue to load.
thanks everyone for replies.!!!
Pass in a context to your class from the activity you are calling it from. Overload the onPreExecute() to show a ProgressDialog and then overload onPostExecute() to hide the ProgressDialog. This gives you blocking while letting the user you are loading.
There is a kinda hacky way to get more control. If you want to keep the AsyncTask as a separate class but allow it to update UI elements in another Activity, define a Handler in that Activity and then pass it in the constructor of the the AsyncTask. You can then send a message in the onPostExecute() method of your AsyncTask to the handler to tell it to update the UI. You will need to make sure the handler is properly handling the message your AsyncTask is sending back. Could be a little cleaner, but it works and will allow you to reuse an asyncTask that makes a network call across activities.

Categories

Resources