Please can anyone tell me how to make an http post to work in the background with AsyncTask and how to pass the parameters to the AsyncTask? All the examples that I found were not clear enough for me and they were about downloading a file.
I'm running this code in my main activity and my problem is when the code sends the info to the server the app slows down as if it is frozen for 2 to 3 sec's then it continues to work fine until the next send. This http post sends four variables to the server (book, libadd, and time) the fourth is fixed (name)
Thanks in advance
public void SticketFunction(double book, double libadd, long time){
Log.v("log_tag", "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SticketFunction()");
//HttpClient
HttpClient nnSticket = new DefaultHttpClient();
//Response handler
ResponseHandler<String> res = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://www.books-something.com");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("book", book+""));
nameValuePairs.add(new BasicNameValuePair("libAss", libass+""));
nameValuePairs.add(new BasicNameValuePair("Time", time+""));
nameValuePairs.add(new BasicNameValuePair("name", "jack"));
//Encode and set entity
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
//Execute
//manSticket.execute(postMethod);
String response =Sticket.execute(postMethod, res).replaceAll("<(.|\n)*?>","");
if (response.equals("Done")){
//Log.v("log_tag", "!!!!!!!!!!!!!!!!!! SticketFunction got a DONE!");
}
else Log.v("log_tag", "!!!!!!!?????????? SticketFunction Bad or no response: " + response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? SticketFunction Client Exception");
} catch (IOException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? IO Exception");
}
}
}
At first,
You put a class like following:
public class AsyncHttpPost extends AsyncTask<String, String, String> {
interface Listener {
void onResult(String result);
}
private Listener mListener;
private HashMap<String, String> mData = null;// post data
/**
* constructor
*/
public AsyncHttpPost(HashMap<String, String> data) {
mData = data;
}
public void setListener(Listener listener) {
mListener = listener;
}
/**
* background
*/
#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 {
// set up post data
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 str;
}
/**
* on getting result
*/
#Override
protected void onPostExecute(String result) {
// something...
if (mListener != null) {
mListener.onResult(result)
}
}
}
Now.
You just write some lines like following:
HashMap<String, String> data = new HashMap<String, String>();
data.put("key1", "value1");
data.put("key2", "value2");
AsyncHttpPost asyncHttpPost = new AsyncHttpPost(data);
asyncHttpPost.setListener(new AsyncHttpPost.Listener(){
#Override
public void onResult(String result) {
// do something, using return value from network
}
});
asyncHttpPost.execute("http://example.com");
First i would not recommend do a Http request in a AsyncTask, you better try a Service instead. Going back to the issue on how to pass parameter into an AsyncTask when you declared it you can defined each Object class of the AsyncTask like this.
public AsyncTask <Params,Progress,Result> {
}
so in your task you should go like this
public MyTask extends<String,Void,Void>{
public Void doInBackground(String... params){//those Params are String because it's declared like that
}
}
To use it, it's quite simple
new MyTask().execute("param1","param2","param3")
Related
I'm trying to get data by calling a web service, and for that I'm using an Async task class.
I want to use an “animated circle” while loading stuff (complete async task process). It will be really helpful if anyone can give me some idea how to do it.
I was looking at this answer by DBragion in Animated loading image in picasso, but doesn't explain exactly where to use those in the project.
Activity.java
new AddressAsyncTask(getBaseContext(), new OnTaskCompletedObject() {
#Override
public void onTaskCompletedObject(JSONObject responseJson) {
Constants.dataAddress = responseJson.toString();
loaddata();
}
}).execute(email);
OnTaskCompletedObject.java
public interface OnTaskCompletedObject {
void onTaskCompletedObject(JSONObject responseJson);
}
AddressAsyncTask.java
public class AddressAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private OnTaskCompletedObject listener;
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
String email;
public AddressAsyncTask(Context context, OnTaskCompletedObject onTaskCompletedObject) {
this.contxt = context;
this.listener=onTaskCompletedObject;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the email and password
Log.i("Email", params[0]);
try {
path = "http://xxxxxxxxxxxxxxxxx/MemberDetails";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
listener.onTaskCompletedObject(responseJson);
}
}
Show Progress Dialog in the onpreExecute method of AsyncTask and dismiss the dialog in Post Execute.I hope that gets your problem solved
I'm trying to get data by calling webservices, for that I'm using a Async task class. As I have shon in the screen shot I'm getting json response successfully. But it crashes in listener.onTaskCompletedObject(responseJson); inside the onPostExecute().
Can anyone spot the reason wht this is not working for me.
Activity.java
new AddressAsyncTask(getBaseContext(), new OnTaskCompletedObject() {
#Override
public void onTaskCompletedObject(JSONObject responseJson) {
Constants.dataAddress = responseJson.toString();
loaddata();
}
}).execute(email);
OnTaskCompletedObject.java
public interface OnTaskCompletedObject {
void onTaskCompletedObject(JSONObject responseJson);
}
AddressAsyncTask.java
public class AddressAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private OnTaskCompletedObject listener;
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
String email;
public AddressAsyncTask(Context context, OnTaskCompletedObject onTaskCompletedObject) {
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the email and password
Log.i("Email", params[0]);
try {
path = "http://xxxxxxxxxxxxxxxxx/MemberDetails";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
listener.onTaskCompletedObject(responseJson);
}
}
Screenshot of the exception
Screenshot of the jsonresponse
NullPointerException exception even after getting data from json
response
Because listener is null.
Initialize listener as :
public AddressAsyncTask(Context context, OnTaskCompletedObject listener) {
this.contxt = context;
this.listener=objListener;
}
Try changing
listener.onTaskCompletedObject(responseJson);
to
listener.onTaskCompletedObject(result);
You have forgotten to initialize your listener in the asyn task constructor.
You have forgotten to initialize your listener in AddressAsyncTask constructor.
public AddressAsyncTask(Context context, OnTaskCompletedObject onTaskCompletedObject) {
this.contxt = context;
this.listener=onTaskCompletedObject;
}
I am trying to create a Login function so i can verify the users. I pass the Username , Password variables to AsyncTask class but i don't know hot to get results in order to use them. Any help? (I am posting part of the source code due to website restrictions)
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(txtUsername.getText().toString().trim().length() > 0 && txtPassword.getText().toString().trim().length() > 0)
{
// Retrieve the text entered from the EditText
String Username = txtUsername.getText().toString();
String Password = txtPassword.getText().toString();
/*Toast.makeText(MainActivity.this,
Username +" + " + Password+" \n Ready for step to post data", Toast.LENGTH_LONG).show();*/
String[] params = {Username, Password};
// we are going to use asynctask to prevent network on main thread exception
new PostDataAsyncTask().execute(params);
// Redirect to dashboard / home screen.
login.dismiss();
}
else
{
Toast.makeText(MainActivity.this,
"Please enter Username and Password", Toast.LENGTH_LONG).show();
}
}
});
Then i use the AsynkTask to do the check but do not know how to get the results and store them in a variable. Any help?
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
// do stuff before posting data
}
#Override
protected String doInBackground(String... params) {
try {
// url where the data will be posted
String postReceiverUrl = "http://server.com/Json/login.php";
Log.v(TAG, "postURL: " + postReceiverUrl);
String line = null;
String fail = "notok";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", params[0]));
nameValuePairs.add(new BasicNameValuePair("Password", params[1]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
line = resEntity.toString();
Log.v(TAG, "Testing response: " + line);
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v(TAG, "Response: " + responseStr);
Intent Hotels_btn_pressed = new Intent(MainActivity.this, Hotels.class);
startActivity(Hotels_btn_pressed);
// you can add an if statement here and do other actions based on the response
Toast.makeText(MainActivity.this,
"Error! User does not exist", Toast.LENGTH_LONG).show();
}else{
finish();
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
}
Not the best code refactoring, but just to give you a hint.
I would create an interface (lets call it 'LogInListener'):
public interface LoginListener {
void onSuccessfulLogin(String response);
void onFailedLogin(String response);
}
The 'MainActivity' class would implement that interface and set itself as a listener the 'PostDataAsyncTask'. So, creating the async task from the main activity would look like this:
String[] params = {Username, Password};
// we are going to use asynctask to prevent network on main thread exception
PostDataAsyncTask postTask = new PostDataAsyncTask(this);
postTask.execute(params);
I would move 'PostDataAsyncTask' class into a new file:
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
private static final String ERROR_RESPONSE = "notok";
private LoginListener listener = null;
public PostDataAsyncTask(LoginListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... params) {
String postResponse = "";
try {
// url where the data will be posted
String postReceiverUrl = "http://server.com/Json/login.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", params[0]));
nameValuePairs.add(new BasicNameValuePair("Password", params[1]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
postResponse = EntityUtils.toString(resEntity).trim();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return postResponse;
}
#Override
protected void onPostExecute(String postResponse) {
if (postResponse.isEmpty() || postResponse.equals(ERROR_RESPONSE) ) {
listener.onFailedLogin(postResponse);
} else {
listener.onSuccessfulLogin(postResponse);
}
}
}
So, 'doInBackground' returns the response to 'onPostExecute' (which runs on the UI thread), and 'onPostExecute' routes the result (success or failure) to the MainActivity, which implements the 'LogInListener' methods:
#Override
public void onSuccessfulLogin(String response) {
// you have access to the ui thread here - do whatever you want on suscess
// I'm just assuming that you'd like to start that activity
Intent Hotels_btn_pressed = new Intent(this, Hotels.class);
startActivity(Hotels_btn_pressed);
}
#Override
public void onFailedLogin(String response) {
Toast.makeText(MainActivity.this,
"Error! User does not exist", Toast.LENGTH_LONG).show();
}
I just assumed that that's what you wanted to do on success: start a new activity, and show a toast on fail.
public class GetUserDetail extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mProgressDialog=ProgressDialog.show(PropertyDetailActivitys.this, "Wait", "User Detail");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
System.out.println("Size mArrayListReviewDetails "+mArrayListReviewDetails.size());
for (int i = 0; i < mArrayListReviewDetails.size(); i++) {
String jsonStr = sh.makeServiceCall("https://graph.facebook.com/"+mArrayListReviewDetails.get(i).getFromid(), ServiceHandler.GET);
System.out.println("JSON OP USer"+"{"+"\"User\""+":"+jsonStr.toString()+"}");
try {
JSONObject jsonObj = new JSONObject(jsonStr);
System.out.println("Name "+jsonObj.getString("name"));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (mProgressDialog!=null) {
mProgressDialog.dismiss();
}
}
}
ServiceHandler.Java
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
Hello friends this is my code in this i have mArrayListReviewDetails Arraylist which include size and as per that size i want to get user name which i call next web service as below ,,right now this arraylist size is 11 but when i call this service it will get only 2 data and progress dialog progress continueouly so how can i solve it any idea?
you just make change in doINBackground fun. Take
ServiceHandler sh = new ServiceHandler(); line inside for loop
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Making a request to url and getting response
System.out.println("Size mArrayListReviewDetails "+mArrayListReviewDetails.size());
for (int i = 0; i < mArrayListReviewDetails.size(); i++) {
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall("https://graph.facebook.com/"+mArrayListReviewDetails.get(i).getFromid(), ServiceHandler.GET);
System.out.println("JSON OP USer"+"{"+"\"User\""+":"+jsonStr.toString()+"}");
try {
JSONObject jsonObj = new JSONObject(jsonStr);
System.out.println("Name "+jsonObj.getString("name"));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
return null;
}
You could pass your parameters to the async task:
public class GetUserDetail extends AsyncTask<String, Void, Void> {
// ...
#Override
protected Void doInBackground(String... usernames) {
for (int i = 0; i < usernames.length; i++) {
String jsonStr = sh.makeServiceCall("https://graph.facebook.com/" + usernames[i], ServiceHandler.GET);
// ...
}
}
}
Of course, instead of String, feel free to pass your own type. To call the async task:
new GetUserDetail().execute( "test1", "test2" );
Other option is to have each async task perform exactly one single webservice call and create many of them. Advantage: on Android 3.0+, the task executions will be done in parralel.
I think instead of using that...you can use "Volley" library...it's simple and having build-in functionality like;
Request queuing and prioritization
Effective request cache and memory management
Extensibility and customization of the library to our needs
Cancelling the requests
volley reference
volley tutorial
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;
}
}