onPostExecute never called? - android

public static class TestTask extends AsyncTask<Void, Integer, Integer> {
private String stacktrace;
public TestTask (String stacktrace){
this.stacktrace = stacktrace;
}
#Override
protected Integer doInBackground(Void... params) {
try {
Log.i("async", "doInBackground 1"); //this gets logged
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xx.xx:8080/android/service.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "logexception"));
nameValuePairs.add(new BasicNameValuePair("stacktrace", stacktrace));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.i("async", "doInBackground 2"); //this gets logged
return 1;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
protected void onPreExecute(){
Log.i("async", "onPreExecute"); //this gets logged
}
#Override
protected void onPostExecute(Integer result) {
Log.i("async", "onPostExecute"); //this doenst get logged!
}
}
I've been checking out the other SO threads regarding this, but according to them, my code looks correct as far as i can tell. So why do i never reach Log.i("async", "onPostExecute");? Thanks

Did you create your AsyncTask on UI Thread?
Others seems good. Generics and annotations are fine.
So probably problem is that your doInBackground method never returns because onPostExecute is automatic called when doInBackground something will return.

You have to call the super in onPostExecute()
So you code should be like this:
#Override
public void onPostExecute(Integer result) {
super.onPostExecute(result);
Log.i("async", "onPostExecute");
}
And this should work

Related

Toast from onProgressUpdate not showing up

Everything is working fine but the Toast from the onProgressUpdate is not showing up. I am surely doing something wrong. Please help me out.
The Code is:
private class MyTask extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
publishProgress("Sending...");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.projectyourself.96.lt/android.php");
//HttpPost httppost = new HttpPost("http://www.yembed.in/loans4you/form.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("message", params[0]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
}catch (Exception e){
return "fail";
}
return "sent";
}
protected void onProgressUpdate(String i) {
super.onProgressUpdate(i);
Toast.makeText(getBaseContext(),i,Toast.LENGTH_SHORT).show();
}
protected void onPostExecute(String r) {
if(r=="sent") {
t.setText("");
Toast.makeText(getBaseContext(), "Sent", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getBaseContext(),"Not Sent!",Toast.LENGTH_SHORT).show();
}
}
The parameter in the method onProgressUpdate(String... values) has to be an array. You created a whole new method that is never actually called.
To fix your problem, change this:
protected void onProgressUpdate(String i) {
super.onProgressUpdate(i);
Toast.makeText(getBaseContext(),i,Toast.LENGTH_SHORT).show();
}
to this:
protected void onProgressUpdate(String... i) {
super.onProgressUpdate(i);
Toast.makeText(getBaseContext(),i[0],Toast.LENGTH_SHORT).show();
}

send form and receive response android

The idea is duplicate on android this web
http://www.telekino.com.ar/
In the site there is a form to check if your lottery ticket won
I am confused on how do it. I tried at this way
my layout has three EditText for each one of the form data to be sent (emision,cupon,algoritmo), to be similar to the web, and a button to send the values.
This is my class
public class Control extends Activity {
private EditText Numerocarton;
private EditText Algoritmo;
private EditText Emision;
public static String emision, cupon, algo;
public TextView resultadocarton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.control);
Emision = (EditText)findViewById(R.id.emsion);
Numerocarton = (EditText)findViewById(R.id.numerocarton);
Algoritmo = (EditText)findViewById(R.id.algoritmo);
emision= Emision.getText().toString();
cupon= Numerocarton.getText().toString();
algo= Algoritmo.getText().toString();
Button resultados= (Button) findViewById(R.id.controlcartonbut);
resultados.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Title().execute();
}
});
resultadocarton =(TextView)findViewById(R.id.resultadocarton);
}
// Title AsyncTask
private class Title extends AsyncTask<Void, Void, Void> {
String responseString;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("http://www.telekino.com.ar/");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("emision", emision));
nameValuePairs.add(new BasicNameValuePair("cupon", cupon));
nameValuePairs.add(new BasicNameValuePair("algo", algo));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=client.execute(post);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
resultadocarton.setText(responseString);
}
catch(Exception e){
Log.e("exvcx", "error getting data" + e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
resultadocarton.setText(responseString);
}
}
}
I dont receive results,and mean there is no change on the EditText. Suggestions? maybe other way to create the clon
You need to know the complete endpoint of the service which is getting called after pressing the controla button. I checked the url given by you. It uses the ajax to contact the webservice and get the data.
Hello i am not sure but may be there is a issue in this line
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Should be like...
post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
Please check it and reply if you are still getting this issue.
also check all the parameters KeyName
Thanks!

Progress Dialog is not shown during execution of AsyncTask

I googled for hours and tried all answers of Stack Overflow but didn't solved my problem.
I made android program to download data in bytes which wroks perfectly. And for download working on background thread. I want to show a Progress Dialog(jus Spinning one). But I'm having really annoying problem. My download takes about 5 sec but my progress dialog is either not shown or just shown for last 1 sec.
Here's my code for AsyncTask.
public class ImageJSON extends AsyncTask<String, String, byte[]> {
private JSONObject jsonObject = new JSONObject();
private byte[] response;
private ProgressDialog pg;
private Context context;
public ImageJSON(Activity activity) {
pg = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pg.setMessage("Downloading, please wait.");
pg.show();
}
#Override
protected void onProgressUpdate(String... progress) {
super.onProgressUpdate(progress);
if (pg != null) {
pg.setProgress(Integer.parseInt(progress[0]));
}
}
protected void onPostExecute(byte[] result) {
if (pg.isShowing()) {
pg.dismiss();
}
}
#Override
protected byte[] doInBackground(String... params) {
HttpPost httpPost = new HttpPost("my file url....");
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
try {
jsonObject.put("imageId", params[0]);
StringEntity stringEntity = new StringEntity(jsonObject.toString());
httpPost.addHeader("Content_Type", "application/octet_stream");
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost, httpContext);
HttpEntity entity = httpResponse.getEntity();
if (entity!=null) {
response = EntityUtils.toByteArray(entity);
entity.consumeContent();
httpClient.getConnectionManager().shutdown();
}
} catch (JSONException|IOException e) {
e.printStackTrace();
}
return response;
}
And I called it from my activity using this code.
final ImageJSON imageTask = new ImageJSON(ReaderActivity.this);
byte[] response = imageTask.execute(imageId).get();
If anybody can help me, Thanks in advance.
You don't want to be using get() as it still freezes your UI thread thus denying the sense of using AsyncTask. You might want to implement onPostExecute in order to return your result properly.
try this -
public ImageJSON(Activity activity) {
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pg = new ProgressDialog(ReaderActivity.this);
pg.setMessage("Downloading, please wait.");
pg.show();
}
you forgot to initilise your progressDialogue in onPreExecute method
#Override
protected void onPreExecute() {
super.onPreExecute();
pg = new ProgressDialog(pass_context_here);
pg.setMessage("Downloading, please wait.");
pg.show();
}
Change this
public ImageJSON(Context ctx) {
this.context = ctx;
}
Now in your onPreExecute() method use this
#Override
protected void onPreExecute() {
super.onPreExecute();
pg = new ProgressDialog(context);
pg.setMessage("Downloading, please wait.");
pg.show();
}
You'r initializing your ProgressDialog in ImageJSON class which block your UI thread means freezes it. So need to initialize it in onPreExecute() method with reference of context.

ProgressBar in asynctask is not showing on upload

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
}

AsyncTask onPostExecute not Outputting

I am not reaching an onPostExecute in an AsyncTask Class.
I call the task this way, inside an onClick in a dialog box:
new HelpfulTask().execute(passing);
Note: When I hover over the above code, I get a warning:
A generic Array of ArrayList is created for a varargs
parameter.
I am not sure what that means and if that is preventing my Task from even running?
Here is the Task Code:
protected class UnHelpfulTask extends
AsyncTask<ArrayList<String>, Void, ArrayList<String>> {
ArrayList<String> passed;
protected ArrayList<String> doInBackground(ArrayList<String>... passing) {
passed = passing[0];
String url_select = "http://www.---.com/---/bad.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("item", passed.get(0)));
param.add(new BasicNameValuePair("text", passed.get(1)));
param.add(new BasicNameValuePair("category", passed.get(2)));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
return null;
}
InputStream is = null;
String result = "";
protected void onPostExecute(Void v) {
Toast.makeText(getContext(), "You have voted this down!",
Toast.LENGTH_SHORT).show();
}
}
I get no errors on run and in the onPostExecute, the Toast never shows. (Note: This is an inner class inside of an ArrayAdapter.) I also added a toast to see if my ArrayList was unwrapping properly and put that in the onPostExecute but it never showed either.
How can I test to see if this Task is even running?
Change
protected void onPostExecute(Void v) {
so it is
protected void onPostExecute(ArrayList<String> arr)
Or change your AsyncTask declaration so it
extends AsyncTask<ArrayList<String>, Void, Void>
Which is the better idea since you return null in doInBackground(). The reason why you weren't getting the toast is because you were making a different method than what your AsyncTask specifies. This is why we ususally use the #Override annotation - it forces a check for actual overrides, which you need to do in classes like AsyncTasks.

Categories

Resources