ProgressDialog hangs in asynctask - android

(I'm using 2.3.3)
The following code is an async task that puts up a progress dialog (pd), does an HttpPost in doInBackground(), and dismisses the progress dialog in onPostExecute(). It works perfectly about 75% of the time. But, 25% of the time the pd gets displayed and never goes away(the post gets done however). The only way the user can get rid of the pd is to go into settings and kill the app (even though "cancelable is set to true").
A timeout exception is NOT happening.
onPostExecute() is not getting executed or the pd.dismiss() is not working.
If I eliminate the pd everything always works perfectly 100% of the time.
What an be happening? Thanks.
class postStringToURLTask extends AsyncTask<URL, Void, String> {
String responseString = "";
#Override
protected void onPreExecute() {
String myEmailAddress = getPref("emailaddress");
pd = ProgressDialog.show(PSActivity.this,
"Emailing Trip to " + myEmailAddress, "", true);
}
#Override
protected String doInBackground(URL... urls) {
try {
URL onlyURL = urls[0]; //there is only one url
HttpResponse response = null;
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams,4000);
HttpConnectionParams.setSoTimeout(myParams, 4000);
HttpClient httpclient = new DefaultHttpClient(myParams);
HttpPost myPost = new HttpPost(onlyURL.toString());
StringEntity se = new StringEntity(payloadString);
myPost.setEntity(se);
myPost.setHeader("Accept", "application/json");
myPost.setHeader("Content-type", "text/plain");
response = httpclient.execute(myPost);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
responseString = line;
}
} catch (Exception e) {
debugLog("postStringToURLTask got exception" + e.getMessage().toString() , 1);
responseString = "error " + e.getMessage().toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
pd.dismiss();
debugLog("just dismissed progress dialog", 1);
result = result.replace("[","");
result = result.replace("\"","");
result = result.replace("]","");
////log.w(getClass().getName(), "onPostExecute received: " + result);
if (result == "") {
mpGood.start();
} else {
sdTripSentProblem(); //bad news dialog
logToServer(result);
}
}
}

Related

Could not get the value from Edit Text element

Fantastic morg. Below this code to get data from mysql database and displayed into the EditText element.There is no problem with getting data from db its working good using this asyn tesk new checkUserPermission().execute("");.
Problem is
I want to make some calculation from code and dispaly in another Edittext. so i need values thats why i get data from db.while OnCreate() to get the data from db(its working). whenever i call this calculatePL(); method i could not get value.
LOGCAT:
System.out: Empty Value
Why its empty or something. but above my edittext elements hold the
values.
...some declaration of variables and etc....
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
setContentView(R.layout.five_activity);
new checkUserPermission().execute(""); //call here
calculatePL();//call the method
}
class checkUserPermission extends AsyncTask<String, String, String> {
private ProgressDialog Dialog = new ProgressDialog(Five_Activity.this);
#Override
protected void onPreExecute() {
Dialog.setMessage("Please wait..");
Dialog.show();
super.onPreExecute();
userid = (TextView)findViewById(R.id.userID);
uid = userid.getText().toString();
System.out.println(uid);
}
#Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> values = new ArrayList<NameValuePair>();
values.add(new BasicNameValuePair("userid", uid));
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.13:8090/stat_api/shiftClose.php");
httppost.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is2 = entity.getContent();
Log.i("TAG", "Connection Successful");
} catch (Exception e) {
Log.i("TAG", e.toString());
//Invalid Address
}
try {
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is2, "iso-8859-1"), 8);
StringBuilder sb2 = new StringBuilder();
while ((line2 = reader2.readLine()) != null) {
sb2.append(line2 + "\n");
}
is2.close();
result2 = sb2.toString();
JSONObject json_data2 = new JSONObject(result2);
code2=(json_data2.getString("code"));
Allvalues = code2;
String[] splited = Allvalues.split("\\s+");
Totalkm=splited[0];
discountamt=splited[1];
receviedamt=splited[2];
totalamt=splited[3];
expen=splited[4];
//Log.d("Splited String ", "Splited String" + totalamt+expen);
runOnUiThread(new Runnable() {
#Override
public void run() {
totkm.setText(Totalkm);
discount.setText(discountamt);
recamt.setText(receviedamt);
totamt.setText(totalamt);
expenses.setText(expen);
}
});
Log.i("TAG", "Result Retrieved");
} catch (Exception e) {
Log.i("TAG", e.toString());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result){
// Close progress dialog
Dialog.dismiss();
}
}
public void calculatePL(){
try {
String a_value =totamt.getText().toString().trim();
System.out.println(a_value);
}catch(NumberFormatException numberEx)
{
System.out.println(numberEx);
}
}
Your checkUserPermission executes in background. And immediately you are calling calculatePL() so your main thread is not waiting for checkUserPermission execution to complete.
What you need to do is, make wait your main thread so that after full execution of checkUserPermission calculatePL() will get called. You can achieve it by adding ProgressDialog. Show the ProgressDialog in onPreExecute() and dismiss it in onPostExecute()
Hope it will do your job.
Override protected void onPostExecute in your asyncTask and call calculatePl() here. And you should set Edittext's text in onPostExecute too, because this method is main thread and you don't need to use runOnUIThread.
EDIT with example code:
class checkUserPermission extends AsyncTask<String, String, String> {
private ProgressDialog Dialog = new ProgressDialog(Five_Activity.this);
#Override
protected void onPreExecute() {
Dialog.setMessage("Please wait..");
Dialog.show();
super.onPreExecute();
userid = (TextView)findViewById(R.id.userID);
uid = userid.getText().toString();
System.out.println(uid);
}
#Override
protected String doInBackground(String... arg0) {
ArrayList<NameValuePair> values = new ArrayList<NameValuePair>();
values.add(new BasicNameValuePair("userid", uid));
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.13:8090/stat_api/shiftClose.php");
httppost.setEntity(new UrlEncodedFormEntity(values));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is2 = entity.getContent();
Log.i("TAG", "Connection Successful");
} catch (Exception e) {
Log.i("TAG", e.toString());
//Invalid Address
}
try {
BufferedReader reader2 = new BufferedReader(new InputStreamReader(is2, "iso-8859-1"), 8);
StringBuilder sb2 = new StringBuilder();
while ((line2 = reader2.readLine()) != null) {
sb2.append(line2 + "\n");
}
is2.close();
result2 = sb2.toString();
JSONObject json_data2 = new JSONObject(result2);
code2=(json_data2.getString("code"));
Allvalues = code2;
} catch (Exception e) {
Log.i("TAG", e.toString());
e.printStackTrace();
}
return Allvalues;
}
protected void onPostExecute(String result){
String[] splited = result.split("\\s+");
Totalkm=splited[0];
discountamt=splited[1];
receviedamt=splited[2];
totalamt=splited[3];
expen=splited[4];
totkm.setText(Totalkm);
discount.setText(discountamt);
recamt.setText(receviedamt);
totamt.setText(totalamt);
expenses.setText(expen);
// Close progress dialog
Dialog.dismiss();
calculatePL();
}
}
Make sure totamt is declared as a global. Try logging the value of totamt or an object of the same. Finally check where you have declared it.

httpclient.execute(httpget) Doesn't seem to work (Android)

I'm trying to get a daily quote from
http://quotesondesign.com/api/3.0/api-3.0.json?callback=json
I call this method in my onCreate
But when i try to execute the httpclient.execute();
it escapes to the catch statement...
What am I doing wrong?
I did include the <uses-permission android:name="android.permission.INTERNET" />
in my manifest file.
public String getJson(){
String quoteUrl = "http://quotesondesign.com/api/3.0/api-3.0.json?callback=?";
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(quoteUrl);
httpget.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
String aJsonString = null;
try {
HttpResponse response = httpclient.execute(httpget);
Toast.makeText(this, "It works", Toast.LENGTH_LONG).show();
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
JSONObject jObject = new JSONObject(result);
aJsonString = jObject.getString("quote");
} catch (Exception e) {
//Toast.makeText(this, "can't execute http request", Toast.LENGTH_LONG).show();
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return aJsonString;
}
EDIT: here is the onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//verbergt notificatiebalk
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splash);
jsonstring = getJson();
Log.d(jsonstring, "The jsonstring contains: " + jsonstring);
//Toast.makeText(this, jsonstring, Toast.LENGTH_LONG).show();
//tot hier testen
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
Thank you in advance!
Update: Actual answer with code now vailable:
private class AsyncQuoteDownload extends AsyncTask<Void, Void, String>{
#Override
protected String doInBackground(Void... params) {
String jsonData = getJson(); //or, if the jsonData var is available from everywhere, just put myR.run(); here, return null, and append the data directly in onPostExecute
return jsonData;
}
#Override
protected void onPostExecute(String result) {
(TextView)findViewById(R.id.Quote).append(result).append("\"");
} // \" makes it put an actual " inside a string
}
Old answer:
I bet your stacktrace (which isn't as an error because oyu catch it, but it's in the log) reads something like "Network on Main Thread"?
Because that's something you're trying to do, and that's something you aren't allowed to do. Instead, put it in an AsyncTask:
onCreate(){ //beware pseudo code because it doesn't matter
//do stuff
setContentView(...); //Above here, everything stays as is.
//below here, only that:
new GetQuoteTask.execute();
}
class GetQuoteTask extends AsyncTask<Void, Void, String>{
String doInBackground(...){ //<- pseudo code, code completion is your friend
String result = getJson();
Log.d(jsonstring, "The jsonstring contains: " + jsonstring);
return result;
}
onPostExecute(String result){
maybePutYourStringSomewhereAKAUpdateUI();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
In your code you have
String quoteUrl = "http://quotesondesign.com/api/3.0/api-3.0.json?callback=?";
While the URL you want to fetch is
http://quotesondesign.com/api/3.0/api-3.0.json?callback=json
Notice how in your code you have callback=? while the URL has callback=json.
After Android 4.2, you can't make Http Request on the UI-Thread (the "main" thread). You need to do it in a seperate thread.
You can find an example on this website or in this stackoverflow post: HttpClient.execute(HttpPost) on Android 4.2 error

How can I get filleUploaded URL as string from async task in android

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.

How to set instance variable of activity in onPostExecute?

I have an AsyncTask in my activity class and when I check some data in doInBackground(), I just want to change/set an instance variable of my activity class, but somehow there is nothing what is changing! :(
And if the variable is changed another AsyncTask should start.
Now here is the code:
public class LogIn extends Activity {
private boolean emailNotAvalaible;
private void setemailNotAvalaible(boolean emailNotAvalaible) {
this.emailNotAvalaible= emailNotAvalaible;
}
private Button loginBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
loginBtn = (Button) findViewById(R.id.login_btn);
loginBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Register().execute("");
if (emailNotAvalaible== true) {
new Installation().execute("");
}
}// end of onClick()
});// end of setOnClickListener
}// end of onCreate();
public class Register extends AsyncTask<String,Integer,String>{
#Override
protected void onPreExecute() {
...
}//end of onPreExecute()
#Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> postParamsEmail = new ArrayList<NameValuePair>();
postParamsEmail.add(new BasicNameValuePair("email", email));
try {
String emailCheck = executeHttpPost("http://.../doubleEmail.php", postParamsEmail);
try {
JSONArray jsonarr = new JSONArray( emailCheck );
String emailAvalaible = jsonarr.getString(0);
if( emailAvalaible.equals("no") ){ doubleEmail = "no"; }else{ doubleEmail = "yes"; }
} catch (JSONException e) {
e.printStackTrace();
}
} catch (Exception e1) {
e1.printStackTrace();
}
}
return "String";
}// end of doInBackground()
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
if (doubleEmail.equals("no")){
LogIn.this.setEmailNotAvalaible(true);
}
}
}//end of AsyncTask class
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}//end of getHttpClient()
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}//end of executeHttpPost()
}//end of activity class
Some code is not shown, but this code isn't important for the solution.
The php-file just checks if the entered email does exist in the database.
So, the major question is how can I easily change the variable 'emailNotAvalaible' in doInBackground or in onPostExecute?
Thanks for your help!!!
EDIT:
Hello again, thanks for everybodys help, to change the variable works fine, but I guess my problem is, that before my Register AsyncTask is allready finished, the new AsyncTask proofs the variable and wants to start, but just a second after that the variable is set. So, How can I ensure that the second AsyncTask only starts when the first AsyncTask is Allready finished? thanks for your help guys!!!
There are several ways but the postExecute method can solve your problem look this: how to pass the result of asynctask onpostexecute method into the parent activity android
this should not be an issue. here is an example that works fine:
public class Register extends AsyncTask<String,Integer,String>{
#Override
protected void onPreExecute() {
Log.d("", "on pre bool: " + bool);
}//end of onPreExecute()
#Override
protected String doInBackground(String... params) {
bool = true;
return "";
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
Log.d("", "on post, bool: " + bool);
}
}
where bool = private boolean in your main activity. here is the logcat:
07-19 11:57:25.943: D/(21843): on pre bool: false
07-19 11:57:29.736: D/(21843): on post, bool: true
my guess is that your variable, doubleEmail, is not getting set to "no".
So, I think I have found at least one solution for my problem, this is maybe not the best one, but it works fine.
Now, for those who are interested in my solution.
I have found it here : multithreading , thanks to Boris Strandjev
I have chosen the 'get' - option : new Register().execute("").get(2000, TimeUnit.MILLISECONDS);
If there is any better solution, please tell me, otherwise thanks for trying to help me!

check amount data uploaded to the server

how to check the amount of data in each time uploaded to the server, this is my code which I call inside a AsyncTask
public String conxDatosInPost(String Direccion, ArrayList<NameValuePair> Parametros) throws Exception {
BufferedReader in = null;
try {
HttpClient client = ClienteHttp();
HttpPost request = new HttpPost(Direccion);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(Parametros);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
//long logitud = response.getEntity().getContentLength();
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
Log.d("El resultado de cnxposin es :----------- ", result +"fn");
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This is my class CLienteHttp();
private HttpClient ClienteHttp() {
if (mHttpCliente == null) {
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
mHttpCliente = new DefaultHttpClient();
final HttpParams params = mHttpCliente.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpCliente;
}
And this is my class asyncTask
public class NuevoPostImagen extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
objAcceso = new AccesoBd();
String jsRes="";
SharedPreferences userDetails = getParent().getSharedPreferences("MisPreferencias", MODE_PRIVATE);
ArrayList<NameValuePair> ParametrosDeEnvio = new ArrayList<NameValuePair>();
ParametrosDeEnvio.add(new BasicNameValuePair("from",Integer.toString(userDetails.getInt("Id",0))));
ParametrosDeEnvio.add(new BasicNameValuePair("idrecurso",Integer.toString(idEvento)));
ParametrosDeEnvio.add(new BasicNameValuePair("texto","nada"));
ParametrosDeEnvio.add(new BasicNameValuePair("titulo",txtFTitulo.getText().toString()));
ParametrosDeEnvio.add(new BasicNameValuePair("imageFile",sImagenBsase64));
try{
//here
String jes=objAcceso.conxDatosInPost(params[0],ParametrosDeEnvio);
jsRes = "ok";
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{return jsRes;}
}
#Override
public void onProgressUpdate(Integer... args){
Pro.setProgress(args[0]);
}
#Override
protected void onPostExecute( String result) {
Pro.dismiss();
if (result.toString().equals("ok")){
LlenarEvento();
dOpciones.dismiss();
dHacerFoto.dismiss();
}
}
#Override
protected void onPreExecute() {
Pro = ProgressDialog.show(getParent(), "", "Enviando",true,true);
Pro.setCancelable(false);
}
}
Can I update my progress bar with the existing code?
Once the cliente.execute (httpost).
I wonder how I can put a listener or something to check the number of bytes uploaded being updated every second or every time you upload them? I need to update my progress bar, according to the quantity that has been uploaded.
Please, I can help?
You can use async task for this. you have to over ride 3 methods.
doinbackground()
onpreexecute()
onpostexecute()
onProgressUpdate
i think this will help u to understand hw to do it . How to implement file upload progress bar in android

Categories

Resources