Calling web service using Async task in android? - android

I have my separate web service class in which i just pass response method, url and array list of data which is required for making the request and getting the response. I call this web service in my login activity like this
JifWebService webServices = new JifWebService();
webServices.Execute(RequestMethod.POST,
Jifconstant.LOGIN_URL, null, logindata);
loginResponse = webServices.getResponse();
loginResponseCode = webServices.getResponseCode();
In this login data is a array list which contains some data. Now i want to call this web service in background using async task. But i am just not getting it correctly. My web service logic is written in totally different java file and its working fine but i want to call my web service methods inside async task.enter code here

You can try below code for Async Task and also call web service in doInBackground:
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
public class AsyncExample extends Activity{
private String url="http://www.google.co.in";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new AsyncCaller().execute();
}
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("Loading...");
pdLoading.show();
}
#Override
protected Void doInBackground(Void... params) {
//this method will be running on a background thread so don't update UI from here
//do your long-running http tasks here, you don't want to pass argument and u can access the parent class' variable url over here
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
}
}
}
Done

Related

asyncTask from one activity running in another activity android

Im just wondering what would be the best and possibly easiest way to do this. I have two activites LoginAcitivty and Main Activity.
Ive coded an AsyncTask in my MainActivity as an inner class which sends updates to a web service. When i click the logout button of the MainActivity this returns the app to the Login Activity. Is it possible to still run the ASyncTask even though there is a different activity running or is there another way to do something like this?
Any suggestions would be greatly appreciated
Thanks
The Asynctask is tied to the "Entity" that created it, in your case it would be the MainActivity, so it will not survive the destroy of your activity (I trust you call the finis() method of the main activity once the user logs out)
What you can do is use a service that runs in background and use the async task to poll your server:
The service shall look like this:
public class PollService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
public void onStart(Intent intent, int startId) {
(new PollAsyncTask(this)).execute();
}
//callback used to retrieve the result from the asynctask
void callBack(String result) {
//here is your logic, taking the result back from the async task
//eventually re-run the asynctask
(new PollAsyncTask(this)).execute();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
The AsyncTask shall look like this:
private class PollAsyncTask extends AsyncTask<String, Void, String> {
private PollService caller;
PollAsyncTask(PollService caller) {
this.caller = caller;
}
#Override
protected String doInBackground(String... params) {
//do your polling here and return something meaningful to the service,
return SOMETHING_REFERRING_TO_THE_1_OF_3;
}
#Override
protected void onPostExecute(String result) {
//Give the result back to the caller:
this.caller.callBack(result);
}
#Override
protected void onPreExecute() {//nothing special here}
#Override
protected void onProgressUpdate(Void... values) {//nothing special here}
}
That way your async task will poll your server whatever activity is currently in foreground.
The service shall be started by your first activity when it is run the first time (i.e. in the onCreate method):
#Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState==null) {//only the first time
Intent serviceIntent = new Intent();
serviceIntent.setAction("com.yourcompany....PollService");
startService(serviceIntent);
}
}
Hope this helps.
For what I understand, you have an inner Class in your MainActivity.
So just make your AsyncTask in a separate Class and you can call it from both Activites.
Like: new YourAsyncTask().execute();
Greetings.

How run two AsyncTasks in one Activity?

I have two Activitys (mainActivity & downloadActivity) and I have 2 AsyncTasks in downloadActivity
In downloadActivity first it execute getFileAsyncTask for reading a JSON file for adding some images and create a ListView from images, if user clicks on an image, the downloadAsyncTask was called and it starts to download something from the internet.
My problem is here: when the second AsyncTask is running I go back to mainActivity and comeback again to downloadActivity the first AsyncTask wasn't called until the downloadAsyncTask completed.
public class downloadActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
new getFileAsyncTask().execute();
...
}
private class getFileAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
//fetch a json file from internet and add images in ListView
return null;
}
}
//there is a Base Adapter class
//if user clicks on an image it calls this downloadAsyncTask.execute()
private class downloadAsyncTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
//download the file
}
}
#Override
protected Void doInBackground(Void... unused) {
//download the file
}
}
note: I want to write something like shopping apps. For example, user can download file and surf into shop to see products .
If you want to run multiple AsyncTasks in parallel, you can call executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) instead of execute() on your task. By default, AsyncTasks run in serial, first come first serve.
Be careful that the two threads do not interact on the same data, this can cause some strange and hard to trace errors.
you can make it in one asynk class that have two methodes first fetch json file wait response in doInBackground ... if it is ok call download file methode. Those methodes will return an httpResponse object
You can override onBackPressed function in activity and finish the current activity before go to previous activity. When again you come to downloadActivity it call it's oncreate method and call first AsynctTask.
Make one class task like:
Declare progress bar globally in main thread.
Now what you have to do is start one async task in main thread like:
public class myactivity extends Activity {
private ProgressDialog _dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_screen);
new abc().execute();
}
class abc extends AsyncTask(String,String,String) {
#Override
protected void onPreExecute() {
_dialog = new ProgressDialog(_ctx);
_dialog.setCancelable(false);
_dialog.setMessage("Loading");
_dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
#Override
protected void onPostExecute(String result) {
// in post execute of this class you can run a new thread of your downaloder thread. and in post execute of last thread you have to dismiss the progess bar.
new download activity.execute();
}
}
}
}
}

How to code more than 2 ...extends AsyncTask .doInBackground() onPostExecute() within an Activity

By the time android apps onStart(),it would execute HttpRequestTask. I have done this part and it works fine.
After the apps open and display data,needs to click on a submit button to POST some data to spring rest web service.In my mind,I think I might need to write another extends AsyncTask ,doInBackground and onPostExecute
What should I code so that system could differentiate extends AsyncTask ,doInBackground and onPostExecute within same Activity?
protected void onStart(){
super.onStart();
new HttpRequestTask().execute();
}
private class HttpRequestTask extends AsyncTask<Void, Void, ArrayList<Item>> {
#Override
protected ArrayList<Item> doInBackground(Void... params) {
//....some code
}
#Override
protected void onPostExecute(ArrayList<PickerItemDetail> pickerList) {
//.....come code and logic
}
}

How to check if an activity is continuing

In my app, I am trying to run multiple photos through a photo editor (one at a time). I have it set up in a for-loop at the moment, but I feel like it is overloading the photo editor and not actually waiting until the current edit session is over, so I wanted to put a control statement in my for-loop to check if the session was still active.
Is this possible?
Easier to tell when the current is over than polling to see if it is still active. If you start it with startActivityForResult, your calling activity will be notified when the invoked activity ends.
Have a look at Starting Activities and Getting Results in the Activity docs for an example.
You might also want to consider running this in an async task. This will pull your heavy processing away from the UI thread. Async task let's you do progress updates as well.
http://developer.android.com/reference/android/os/AsyncTask.html
public class MainActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logo_page);
// Call async task.
my_async as = new my_async(this);
as.execute();
}
--
my_async:
public class my_async extends AsyncTask<Object, Integer, String> {
private parentClass activity;
public my_async (parentClass activity) {
this.activity = activity;
}
#Override
protected String doInBackground(Object... arg0) {
// Do stuff
return "MyString";
}
protected void onPostExecute(String contents) {
activity.contents = contents;
}

Updating an Activity from an AsyncTask

So I'm an iOS developer learning android, and I'm having a difficult time understanding some things. Right now I have a datamanager class. In that class it has an AsyncTask to update the data. OnPreExecute I pop an activity to show it is updating. I understand I could use extras to pass initial information to the UpdateActivity. My problem is I'm not sure how to send new information in OnProgressUpdate. Here is my code widdled down:
private class myTask extends AsyncTask<Integer,String,Void>{
#Override
protected void onCancelled() {
super.onCancelled();
isUpdating = false;
}
#Override
protected Void doInBackground(Integer... params) {
//My BG Code
}
#Override
protected void onPostExecute(Void result) {
// TODO Remove updating view
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Intent myIntent = new Intent(mContext,UpdateActivity.class);
mContext.startActivity(myIntent);
}
}
AsyncTask is designed to work best when nested in an Activity class.
What makes AsyncTask 'special' is that it isn't just a worker thread - instead it combines a worker thread which processes the code in doInBackground(...) with methods which run on the Activity's UI thread - onProgressUpdate(...) and onPostExecute(...) being the most commonly used.
By periodically calling updateProgress(...) from doInBackground(...), the onProgressUpdate(...) method is called allowing it to manipulate the Activity's UI elements (progress bar, text to show name of file being downloaded, etc etc).
In short, rather than firing your 'update' Activity from an AsyncTask, your update Activity itself should have a nested AsyncTask which it uses to process the update and publish progress to the UI.
You have two options:
1) Pass an instance of activity to your AsyncTask constructor in order to invoke some method on it:
new MyTask(this).execute();
So, you can do:
public MyTask (Activity activity) {
this.activity = activity;
}
public void onPostExecute(...) {
activity.someMethod();
}
2) Pass a Handler instance and send message from onPostExecute() to the activity.

Categories

Resources