aim not able at all to Stop both httpClient AND httpget
when i click on progress dialog cancel button the Request and AsyncTask shall Stop and abort but its not , the request still running until its finished
this is my AsyncTask Test code
public class getAlbuminfo extends AsyncTask<String,String, String> {
ProgressDialog progressDialog;
JSONObject data = null;
boolean prependMore = false;
//Http
HttpClient httpClient;
HttpGet httpget;
/**********
* Begien
*/
#SuppressWarnings("deprecation")
#Override
protected void onPreExecute() {
if ( onlypagenat == false )
{
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.setMessage(context.getResources().getString(R.string.opening_album));
progressDialog.setButton(context.getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
cancel(true);
finish();
}});
progressDialog.show();
}
prependMore = appendMore;
appendMore = false;
}
/**************
* IF Canceled
*/
#Override
protected void onCancelled() {
Log.i("Http Response:", "Aborted");
if ( httpget != null )
{
httpClient.getConnectionManager().shutdown();
httpget.abort();
}
}
/****************
* Make Request
*/
#Override
protected String doInBackground(String... params) {
String response = null;
String url = Api.foruminfo.forum_api_url+"/album.php?albumid="+albumid+"&page="+page+"&onlypagenat="+(onlypagenat?1:0);
httpClient = new DefaultHttpClient();
httpget = new HttpGet(url);
//Add Values User Headers and Cookies
httpget.addHeader("Cookie", Api.forumCookies());
httpget.setHeader("Accept-Charset", "utf-8");
// Making HTTP Request
try {
HttpResponse serverResponse = httpClient.execute(httpget);
Log.i("Http HttpResponse:", serverResponse.toString());
//Set Response
response = EntityUtils.toString(serverResponse.getEntity());
} catch (ClientProtocolException e) {e.printStackTrace();
} catch (IOException e) { e.printStackTrace();}
return response;
}
/**********************
* Done
*/
#Override
protected void onPostExecute(String response) {
Log.i("Http HttpResponse:", response);
if ( onlypagenat == false )
{
progressDialog.dismiss();
}
}
}
Any advice Please how to Full stop Get or Post http request in android !!
The AsyncTask.cancel() method has nothing to do with the cancel of a http request. cancel(true) only prevents that onPostExecute() will be invoked after doInBackground finished the job. Instead onCancelled() will be called.
If you wanna cancel a http request use HttpClient.getConnectionManager().shutdown();
public void onClick(DialogInterface dialog, int which) {
cancel(true);
httpClient.getConnectionManager().shutdown();
finish();
}});
Related
I have multiple images and i am uploading on php server using asynctask my problem is i want to show circular progress bar on every image individually like whatsapp but don't know how to do. here is my code
/**
* Uploading the file to server
* */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected String doInBackground(Void... params)
{
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(serviceurl+"conversations.php");
try {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
/* example for setting a HttpMultipartMode */
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File sourceFile = new File(imgDecodableString);
// Progress listener - updates task's progress
MyHttpEntity.ProgressListener progressListener =
new MyHttpEntity.ProgressListener() {
#Override
public void transferred(float progress) {
publishProgress((int) progress);
}
};
// Adding file data to http body
entity.addPart("file", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addTextBody("from_user",(prefid.getString("userid", null)),ContentType.TEXT_PLAIN);
entity.addTextBody("to_user",touser_id,ContentType.TEXT_PLAIN);
entity.addTextBody("message_type", msg_type,ContentType.TEXT_PLAIN);
httppost.setEntity(new MyHttpEntity(entity.build(),
progressListener));
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
I am calling above code in my main activity and i am using this to upload images and video.
please help me how i can set progress bar on multiple images same as in whatsapp
Thanks
You could pass the View to the AsyncTask, by create new constructor then show/hide it, notice that you have to runOnUIThread for the view.
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
ImageView iv_loading;
public UploadFileToServer(ImageView iv_loading){
this.iv_loading = iv_loading;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
runOnUiThread(new Runnable() {
#Override
public void run() {
iv_loading.setVisibility(View.VISIBLE);
}
}
);
}
...
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv_loading.setVisibility(View.GONE);
}
}
);
}
}
I am uploading an image on server by using async task and in the end I want to return value of uploaded file url. How can I do that
I am calling asynctask as
new Config.UploadFileToServer(loginUserInfoId, uploadedFileURL).execute();
and my asynctask function is as:
public static final class UploadFileToServer extends AsyncTask<Void, Integer, String> {
String loginUserInfoId = "";
String filePath = "";
long totalSize = 0;
public UploadFileToServer(String userInfoId, String url){
loginUserInfoId = userInfoId;
filePath = url;
}
#Override
protected void onPreExecute() {
// setting progress bar to zero
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
// updating progress bar value
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.HOST_NAME + "/AndroidApp/AddMessageFile/"+loginUserInfoId);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("file", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
responseString = responseString.replace("\"","");
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
Try my code as given below.
public Result CallServer(String params)
{
try
{
MainAynscTask task = new MainAynscTask();
task.execute(params);
Result aResultM = task.get(); //Add this
}
catch(Exception ex)
{
ex.printStackTrace();
}
return aResultM;//Need to get back the result
}
You've almost got it, you should do only one step. As I can see, you are returning the result at the doInBackground method (as a result of calling uploadFile). Now, this value is passed to the onPostExecute method, which is executed on the main thread. In its body you should notify components, which are waiting for result, that result is arrived. There are a lot of methods to do it, but if you don't want to used 3rd party libs, the simplest one should be to inject listener at the AsyncTask constructor and call it at the onPostExecute. For example, you can declare the following interface:
public interface MyListener {
void onDataArrived(String data);
}
And inject an instance implementing it at the AsyncTask constructor:
public UploadFileToServer(String userInfoId, String url, MyListener listener){
loginUserInfoId = userInfoId;
filePath = url;
mListener = listener;
}
Now, you can simply use it at the onPostExecute:
#Override
protected void onPostExecute(String result) {
listener.onDataArrived(result);
super.onPostExecute(result); //actually `onPostExecute` in base class does nothing, so this line can be removed safely
}
If you are looking for a more complex solutions, you can start from reading this article.
I am getting can't create handler inside thread in asynchronous background task. Below is my code. I made the necessary modifications to progress bar after searching in google but still the error is rising. Please help me with this. Will be thankful.
My code:
private class LongOperation1 extends AsyncTask<String, Void, String> {
private final WeakReference<MainActivity> mainActivityWeakRef;
ProgressDialog dialog;
public LongOperation1(MainActivity mainActivity) {
super();
this.mainActivityWeakRef = new WeakReference<MainActivity>(
mainActivity);
// this.activity = mainActivity;
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://.............php");
// This is the data to send
// String MyName = 'adil'; //any data to send
// publishProgress(5);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("param1", "1"));
nameValuePairs.add(new BasicNameValuePair("param2",
"Cities"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
// This is the response from a php application
String reverseString = response;
Toast.makeText(MainActivity.this, "response" + reverseString,
Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
Toast.makeText(MainActivity.this,
"CPE response " + e.toString(), Toast.LENGTH_LONG)
.show();
// TODO Auto-generated catch block
} catch (IOException e) {
Toast.makeText(MainActivity.this,
"IOE response " + e.toString(), Toast.LENGTH_LONG)
.show();
// TODO Auto-generated catch block
}
return "All Done!";
}
#Override
protected void onPostExecute(String result) {
Log.d("onpostexecute", (mainActivityWeakRef.get() != null) + "");
if (mainActivityWeakRef.get() != null
&& !mainActivityWeakRef.get().isFinishing()) {
AlertDialog alertDialog = new AlertDialog.Builder(
mainActivityWeakRef.get()).create();
alertDialog.setTitle(result);
alertDialog.setMessage("On post execute");
alertDialog.setCancelable(false);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
dialog.incrementProgressBy(5);
}
}
You can not update the UI thread(Main Thread) from another thread.. If you want to do it
1) Return your response String from doInbackground, and update the UI in PostExecute()
2)Otherwise you can wrap the Toast Message in runonUiThread(){}
3) Use Handler to update the UI from another thread.
You cannot use Toast in the do in background operation because you need the UIThread to show them. Instean of doing that as you did. Use a variable an save it for different states.
In onPostExecute check the variable and show the corresponding Toast.
Hope it helps.
This is my function that is in LoginActivity.java.So onclick of button i am calling this function.
public void postHttpRequest(String userId,String pass,TextView error){
RequestClient reqClient = new RequestClient(LoginActivity.this);
String AppResponse = null;
try {
url = "myurl";
Log.d("URL", url);
AppResponse = reqClient.execute().get();
String status = ValidateLoginStatus.checkLoginStatus(AppResponse);
Log.d("Status recived", status);
if(status.equals("200")){
saveInformation(userId,pass);
startingActivity(HOST_URL);
}else{
error.setText("Incorrect UserName or Password");
}
} catch (Exception e) {
Log.e("Exception Occured", "Exception is "+e.getMessage());
}
}
From this function i am calling a AsynkTask for Http Communication.So onclick of button when i am geeting the response then my processDialog in opening just for one sec.I want as i click the buttoon my processDialog should get open utill i got the response
public class RequestClient extends AsyncTask<String, Void, String>{
ProgressDialog pDialog;
Context context;
public RequestClient(Context c) {
context = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Authenticating user...");
pDialog.show();
}
#Override
protected String doInBackground(String... aurl){
String responseString="";
DefaultHttpClient httpClient=new DefaultHttpClient();
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(LoginActivity.url);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_ERROR", responseString);
httpClient.getConnectionManager().shutdown();
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if(pDialog!=null)
pDialog.dismiss();
}
}
So please suggest me what changes i have to make so that processDialog should display properly in the center of the device
//add style in your progressbialog
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("Authenticating user...");
if (pDialog != null && !pDialog.isShowing()) {
pDialog.show();
}
}
AsyncTask return value only after using get() method
Drawing from the above link
Calling the get() method of AsyncTask will block the main thread and wait for the result to be returned. This effectively makes using an AsyncTask become a synchronous operation in which case there's no point in using an AsyncTask.
The only reason I can think of to use the get() method would be from a thread other than the main (UI) thread although I can't think of many reasons to do that.
On Button click
RequestClient reqClient = new RequestClient(LoginActivity.this,new TheInterface() {
#Override
public void theMethod(String result) {
Log.i("Result =",result);
}
});
reqClient.execute(url); // no get(). pass url to doInBackground()
In your activity class
public interface TheInterface {
public void theMethod(String result);
}
}
AsyncTask
public class RequestClient extends AsyncTask<String, Void, String>{
ProgressDialog pDialog;
Context context;
TheInterface listener;
public RequestClient(Context c,TheInterface listen) {
context = c;
listener = listen;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Authenticating user...");
pDialog.show();
}
#Override
protected String doInBackground(String... aurl){
String responseString="";
HttpClient client;
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(aurl[0]); // url
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_ERROR", responseString);
client.getConnectionManager().shutdown();
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
pDialog.dismiss();
if (listener != null)
{
listener.theMethod(result);
}
}
}
It seems that your button code is not correct, because it's async, but you are trying to use it as standart sync code.
Try to move this code into onPostExecute:
String status = ValidateLoginStatus.checkLoginStatus(response);
Log.d("Status recived", status);
if(status.equals("200")){
saveInformation(userId,pass);
startingActivity(HOST_URL);
}else{
error.setText("Incorrect UserName or Password");
}
and make this button click code:
public void postHttpRequest(String userId,String pass,TextView error){
RequestClient reqClient = new RequestClient(LoginActivity.this);
String AppResponse = null;
try {
url = "myurl";
Log.d("URL", url);
reqClient.execute();
} catch (Exception e) {
Log.e("Exception Occured", "Exception is "+e.getMessage());
}
}
Can someone tell me, why progressbar isnt showing when picture is being uploaded. I copied asynctask structure from my old project where it works. In my old project i use asynctask to download pictures from web server, and to show progressbar while downloading.
Here is my code:
public class PreviewPostActivity extends Activity {
ImageView imageView;
TextView tvComment;
Button submit;
MyLocationListener locationListener;
List<NameValuePair> list = new ArrayList<NameValuePair>();
private final String url = "***"; //Url of php script
ProgressDialog pDialog;
String responseMessage="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preview_post);
Intent intent = this.getIntent();
imageView = (ImageView)findViewById(R.id.imgPerview);
tvComment = (TextView)findViewById(R.id.txtPreviewComment);
submit = (Button)findViewById(R.id.btnPreviewSubmit);
Bitmap image = (Bitmap)intent.getParcelableExtra("picture");
String comment = intent.getStringExtra("comment");
locationListener = (MyLocationListener)intent.getSerializableExtra("location");
String imagePath = intent.getStringExtra("imagePath");
String date = intent.getStringExtra("date");
imageView.setImageBitmap(image);
tvComment.setText(comment);
//tvComment.append("\n"+locationListener.latitude + "\n"+locationListener.longitude);
list.add(new BasicNameValuePair("image", imagePath));
list.add(new BasicNameValuePair("comment", comment));
list.add(new BasicNameValuePair("longitude", Double.toString(locationListener.longitude)));
list.add(new BasicNameValuePair("latitude", Double.toString(locationListener.latitude)));
list.add(new BasicNameValuePair("date", date));
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new uploadPost().execute();
}
});
}
public void post(List<NameValuePair> nameValuePairs) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
HttpConnectionParams.setSoTimeout(httpParameters, 200000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity();
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File(nameValuePairs.get(index).getValue()),"image/jpeg"));
} else {
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity httpEntity = response.getEntity();
String responseMessage = EntityUtils.toString(httpEntity);
tvComment.setText(responseMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
class uploadPost extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PreviewPostActivity.this);
pDialog.setMessage("Uploading post. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
//post(list);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
HttpConnectionParams.setSoTimeout(httpParameters, 200000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity();
for(int index=0; index < list.size(); index++) {
if(list.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(list.get(index).getName(), new FileBody(new File(list.get(index).getValue()),"image/jpeg"));
} else {
// Normal string data
entity.addPart(list.get(index).getName(), new StringBody(list.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity httpEntity = response.getEntity();
responseMessage = EntityUtils.toString(httpEntity);
//tvComment.setText(responseMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
tvComment.setText(responseMessage);
pDialog.dismiss();
}
}
So when i hit button for upload, screen freezes and stay frozen until upload is complete, and progress bar isnt showing at all. Sometimes it shows, but its rly rear and i dont know why. I have tried calling Post() method from class in doInBackground body insted of whole code (code in body is the same as in post() method) but effect is the same, so i guess i didnt do something right in creating progressbar. But again i say i copied whole asynctask code from old project in witch it worked fine.
EDIT:
I just tryed creating progress bar in constructor of PreviewPostActivity.class and after that i made constructor for asynctask class but it still dosent work. I am rly confused becouse it worked in my old program.
Here is code from him:
class GetSlike extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(KlubSlikeActivity.this);
pDialog.setMessage("Ucitavanje u toku. Molimo vas sacekajte...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
String id = Integer.toString(k.getId());
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("klub",id));
slikeUrl = JSONAdapter.getSlike(params);
gv.setAdapter(new SlikeAdapter(slikeUrl,KlubSlikeActivity.this));
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
Only thing changed is doInBackground body...
Edited:
Dialog is display after runOnUiThread() is executed.
I found this library which is perfect to accomplish the upload task and also provide a progress handler which could be used to set the value of a ProgressBar:
https://github.com/nadam/android-async-http
It could be used like the following... Set onClickHandler for the upload Button:
#Override
public void onClick(View arg0) {
try {
String url = Uri.parse("YOUR UPLOAD URL GOES HERE")
.buildUpon()
.appendQueryParameter("SOME PARAMETER IF NEEDED 01", "VALUE 01")
.appendQueryParameter("SOME PARAMETER IF NEEDED 02", "VALUE 02")
.build().toString();
AsyncHttpResponseHandler httpResponseHandler = createHTTPResponseHandler();
RequestParams params = new RequestParams();
// this path could be retrieved from library or camera
String imageFilePath = "/storage/sdcard/DCIM/Camera/IMG.jpg";
params.put("data", new File(imageFilePath));
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, httpResponseHandler);
} catch (IOException e) {
e.printStackTrace();
}
}
then add this method to your activity code:
public AsyncHttpResponseHandler createHTTPResponseHandler() {
AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
}
#Override
public void onProgress(int position, int length) {
super.onProgress(position, length);
progressBar.setProgress(position);
progressBar.setMax(length);
}
#Override
public void onSuccess(String content) {
super.onSuccess(content);
}
#Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
}
#Override
public void onFinish() {
super.onFinish();
}
};
return handler;
}
Run on ui thread in asynctask doinbackground() is not correct. Also you are returning null in doInBackground() and you have parameter file_url in onPostExecute(). Return value in doInbackground() recieve value in onPostExecute().
doInBackGround() runs in background so you cannot access or update ui here.
To update ui you can use onPostExecute().
Your AsyncTask should be something like below. You are doing it the wrong way.
http://developer.android.com/reference/android/os/AsyncTask.html. See the topic under The 4 steps
pd= new ProgressDialog(this);
pd.setTitle("Posting data");
new PostTask().execute();
private class PostTask extends AsyncTask<VOid, Void, Void> {
protected void onPreExecute()
{//display dialog.
pd.show();
}
protected SoapObject doInBackground(Void... params) {
// TODO Auto-generated method stub
//post request. do not update ui here. runs in background
return null;
}
protected void onPostExecute(Void param)
{
pd.dismiss();
//update ui here
}