I am using Async Task to perform some operations in my database. During the operation, I'm showing a progress dialog and when it operations are finish I want to dismiss it but it doesn't work.
private ProgressDialog progressDialog;
private void showProgressDialog(String title, String message)
{
progressDialog = new ProgressDialog(this);
progressDialog.setTitle(title); //title
progressDialog.setMessage(message); // message
progressDialog.setCancelable(true);
progressDialog.show();
}
private class InsertFoodAsyncTask extends AsyncTask<Void, Integer, String>{
#Override
protected String doInBackground(Void... arg0){
InsertFood p = new InsertFood(Food.this,mBDD);
p.InsertFood();
return "Executed";
}
#Override
protected void onPreExecute() {
showProgressDialog("Please wait...", "Your message");
}
#Override
protected void onPostExecute(String result) {
if(progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
}
}
Can you help me ? Thanks a lot !
Try it,
replace:
progressDialog.show();
for:
progressDialog = progressDialog.show();
It seems all correct in your code. onPostExecute() already make it run on ui thread. But still try to check with this also.
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if(progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
}
});
Related
I am trying to put together a login screen using the Stormpath framework in android. I used the standard Login screen provided in android studio and only modified the UserLoginTask. My problem is that it doesn't seem to wait for my call to Stormpath to finish. As soon as the class is called it goes straight in exectures doInBackground and then goes straight to onPostExecute. Here is my class:
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
private final String mEmail;
private final String mPassword;
private boolean loginResult;
String errorMessage;
UserLoginTask(String email, String password) {
mEmail = email;
mPassword = password;
}
#Override
protected Boolean doInBackground(Void... params) {
Stormpath.login(mEmail, mPassword, new StormpathCallback<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("debug", "sucess");
loginResult = true;
}
#Override
public void onFailure(StormpathError error) {
errorMessage = error.message();
Log.d("debug", "Error: " + error.message());
loginResult = false;
}
});
return loginResult;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
Toast.makeText(LoginActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
Since Stormpath.login() uses a callback, most likely it's already doing the network call on a background thread and returns you the result via the callback. If this is the case, then you don't really need an AsyncTask.
im using OptimusHTTP library on my android project. im trying to show loading if my app is contacting server. my problem is why my progress dialog does not dismiss. here is my code.
public void connectREST()
{
//using data json dummy
String SERVER = "http://jsonplaceholder.typicode.com/posts/1";
OptimusHTTP client = new OptimusHTTP();
client.enableDebugging();
client.setMethod(OptimusHTTP.METHOD_GET);
//parameter
ArrayMap<String, String> params = new ArrayMap<>();
params.put("email", "abc#abc.com");
params.put("pass", "abc");
//make request
ArrayList<HttpReq> refHttpReqList = new ArrayList<>();
try {
//mprogressdialog.show(this, "", "Loading", true);
// makeRequest() returns the reference of the request made
// which can be used later to call the cancelReq() if required
// if no request is made the makeRequest() returns null
HttpReq req = client.makeRequest(MainActivity.this, SERVER, params, responseListener);
if (req != null)
refHttpReqList.add(req);
mprogressdialog.show(this, "Loading", "Wait while loading...");
if (mprogressdialog != null && mprogressdialog.isShowing()) {
mprogressdialog.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private final OptimusHTTP.ResponseListener responseListener = new OptimusHTTP.ResponseListener() {
#Override
public void onSuccess(String msg) {
System.out.println(msg);
//mprogressdialog.dismiss();
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(String msg) {
System.out.println(msg);
}
};
i know that this library (OptimusHTTP) is using asnyc when contacting server.
is there any configuration whether im using sync or async on the http connection ?
what if im include get method in some async code (double async) ?
i know that my question seem like some newbie question. but it takes learn process to become a pro :) Thanks.
#navotera : You can show a ProgressDialogue just before making a request and when the request completes , under the listener just dismiss the progress dialogue.
i.e
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
...
// Initialize the progressdialog
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Connecting");
...
...
// Show the progressdialog just before making a request
progressDialog.show();
// Make the request
req = client.makeRequest(MainActivity.this, SERVER_URL, params,new OptimusHTTP.ResponseListener(){
#Override public void onSuccess(String msg) {
System.out.println(msg);
// Dismiss the progressdialog
progressDialog.dismiss();
}
#Override public void onFailure(String msg) {
System.out.println(msg);
// Dismiss the progressdialog
progressDialog.dismiss();
}
});
You see this library (OptimusHTTP) is using asnyc when contacting server.But why did you update UI on the same thread ?
private final OptimusHTTP.ResponseListener responseListener = new OptimusHTTP.ResponseListener() {
#Override
public void onSuccess(String msg) {
System.out.println(msg);
//mprogressdialog.dismiss();
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(String msg) {
System.out.println(msg);
}
};
I want create progressdialog in fragment but keep showing error is has leaked window com.android.internal.policy.impl.phonewindow that was originally added here. please help and this my code
private class ListDaftarHargaAsync extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("retrieving...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
}
#Override
protected String doInBackground(String... params) {
try {
modelPost.setDataVouchers();
} catch (JSONException e) {
e.printStackTrace();
}
String result = modelPost.resultString;
if (result.length() != 0) {
progressDialog.dismiss();
}
return null;
}
#Override
protected void onPostExecute(String result) {
progressDialog.dismiss();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
fillDaftarHarga();
}
});
}
}
check is progress dialog is showing or not
and you cant touch UI thread in doInBackground
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("retrieving...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
modelPost.setDataVouchers();
} catch (JSONException e) {
e.printStackTrace();
}
String result = modelPost.resultString;
return null;
}
#Override
protected void onPostExecute(String result) {
if (null != progressDialog && progressDialog.isShowing()) {
progressDialog.dismiss();
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
fillDaftarHarga();
}
});
}
}
leaked window com.android.internal.policy.impl.phonewindow that was originally added here.
Above error showing because you are calling progressDialog.dismiss(); on doInBackground.
Uploading information using AsyncTask in android and notifying user once the task is completed
What am i trying to Do:: I am trying to upload information to server from android
What have i tried:: I have done the image uploading part, I have used Async-task for this & the functionality works
What i am trying to do::
I want to show a Toast message once the file uploading is done as
"File Uploaded"
How can i achieve this ?
MainActivity.java
public class DataAcceptActivity extends Activity {
<----------------------Code-------------->
public class MainTest extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(DataAcceptActivity.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
postImageData();
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
pDialog.dismiss();
}
}
public class ImageAdapter extends BaseAdapter{
<_----------------- code _-------------->
}
Thanks !!
In AsyncTask you have to notified in onPostExecute method:
So use this:
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast toast = Toast.makeText(YourActivity.this, "Message Here", duration).show();
pDialog.dismiss();
}
It also depends on your Response that which type of message do you want to display.
If you are not using AsyncTask then you can also use Handler.
You can show the toast message in the onPostExecute() method of your async task.
You can simply display a toast in onPostExecute
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast toast = Toast.makeText(context, text, duration);
toast.show();
pDialog.dismiss();
}
on the your asynctask
#Override
protected void onPostExecute() {
Toast toast = Toast.makeText(getApplicationContextt, "File Uploaded", Toast.LENGTH_LONG).show();
}
public class MainTest extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(DataAcceptActivity.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... params) {
postImageData();
return true;
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
if(result)
{
Toast.makeText(_context , "Image uploaded.." , Toast.LENGTH_LONG).show();
}
/* else
{
Toast.makeText(_context , "Image is not uploaded.." , Toast.LENGTH_LONG).show();
}*/
if(pDialog.isShowing())pDialog.dismiss();
}
}
In your code addding some changes in onPostExecuteMethod
public class MainTest extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(DataAcceptActivity.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
postImageData();
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(pDialog.isShowing()){
// data=jobj.toString();
pDialog.dismiss();
}
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
I currently have an asyncTask which on preexecute begins a loading bar, in background send something to a server, and on post execute dismisses the dialog and enables a button. However, my post execute is not executing due to doInBackground returning null. I'm trying to figure out what I can do do get the postExecute to run. any ideas? thanks
code:
class DatabaseAsync extends AsyncTask<Void,Void,Void>{
#Override
protected void onPreExecute(){
dialog = ProgressDialog.show(MainFeedActivity.this, null, "Posting...");
}
#Override
protected Void doInBackground(Void... arg0) {
Log.d(TAG, "send to databse");
SendToDatabase();
Log.d(TAG, "sent to database - DONE");
//dialog.dismiss();
//sendButton.setEnabled(true);
return null;
}
protected void onPostExecute(){
Log.d(TAG, "p execute");
dialog.dismiss();
sendButton.setEnabled(true);
Log.d(TAG, "done executing");
}
}
It is completely Ok to return null from doInBackground() in your case. Just make sure onPostExecute() looks like this:
#Override
protected void onPostExecute(Void result) {
Log.d(TAG, "p execute");
dialog.dismiss();
sendButton.setEnabled(true);
Log.d(TAG, "done executing");
}
change your DatabaseAsync class like this:
class DatabaseAsync extends AsyncTask<String, Void, String>{
protected void onPreExecute(){
dialog = ProgressDialog.show(MainFeedActivity.this, null, "Posting...");
}
protected String doInBackground(String... arg0) {
Log.d("TAG", "send to databse");
Log.d("", "sent to database - DONE");
//dialog.dismiss();
//sendButton.setEnabled(true);
return null;
}
protected void onPostExecute(String result){
Log.d("TAG", "p execute");
dialog.dismiss();
Log.d("TAG", "done executing");
}
read this link after the code works http://www.vogella.de/articles/AndroidPerformance/article.html