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
Related
I have a class LoginTask which is a subclass of AsyncTask. I used that to execute login functionality. Simply my LoginTask looks like this
class LoginTask extends AsyncTask<JsonObject,Void,String>{
#Override
protected void onPreExecute() {
//Codes to show progressDialog
}
#Override
protected String doInBackground(JsonObject... params) {
Ion.with(MainActivity.this)
.load("--URL TO POST JSON DATA--")
.setJsonObjectBody(params[0])
.asJsonObject()
.withResponse()
.setCallback(new FutureCallback<Response<JsonObject>>() {
#Override
public void onCompleted(Exception e, Response<JsonObject> result) {
if (result != null) {
if (result.getHeaders().code() == 200) {
Toast.makeText(MainActivity.this, "Login Success", Toast.LENGTH_SHORT).show();
} else if (result.getHeaders().code() == 401) {
Toast.makeText(MainActivity.this, "Invalid Username or password", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Something wrong check connection !!!", Toast.LENGTH_SHORT).show();
}
}
}
});
return "some message";
}
#Override
protected void onPostExecute(String string) {
super.onPostExecute(string);
if(progressDialog.isShowing()){
progressDialog.dismiss();
//TODO Something
}
}
}
What I want and What was happened :
I want to call onPostExecute Only after getting the result from FutureCallback method But when I debug the app It is directly returning the value and onPostExecute Method called Immediately before FutureCallback method.
I have written code to Execute LoginTask at Login Button pressed Event, I want to show the ProgressDialog each time when Button is pressed, But the problem is ProgressDialog is shown only at the first time, It didn't appear when I pressed the Button second time.
I want to set some message to a variable and return that to onPostExecute method so that I can handle specific tasks based on the value of String parameter, But FutureCallback is called only after executing the whole Task.
Any Kind of Suggestions will be appreciated.
Here you are calling another thread inside asynctask. So whats happening is when the new thread is getting called. Asynctask is not waiting for your ion's thread to complete and so it is going to onPostExecute.
I think you don't need a asynctask here because Ion is already making the request asyncronously. Whatever you are doing inside onPostExecute(), you can put that inside onComplete() of the ion's call.
Do like this,
[Codes to show progressDialog]
Ion.with(MainActivity.this)
.load("--URL TO POST JSON DATA--")
.setJsonObjectBody(params[0])
.asJsonObject()
.withResponse()
.setCallback(new FutureCallback<Response<JsonObject>>()
{
#Override
public void onCompleted(Exception e, Response<JsonObject> result) {
if(progressDialog.isShowing()){
progressDialog.dismiss();
//TODO Something
}
if (result != null) {
if (result.getHeaders().code() == 200) {
Toast.makeText(MainActivity.this, "Login Success", Toast.LENGTH_SHORT).show();
} else if (result.getHeaders().code() == 401) {
Toast.makeText(MainActivity.this, "Invalid Username or password", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Something wrong check connection !!!", Toast.LENGTH_SHORT).show();
}
}
}
});
onCompleted() method you are passing in setCallback() method is a callback method that is an asynchronous call so this callback will be invoked when response is returned from server and its takes time that is why your onPostExecute method is called before futureTask.
Ion lib already uses async calls so you do not need to use AsyncTask. You just need to do following:
Ion.with(MainActivity.this)
.load("--URL TO POST JSON DATA--")
.setJsonObjectBody(params[0])
.asJsonObject()
.withResponse()
.setCallback(new FutureCallback<Response<JsonObject>>() {
#Override
public void onCompleted(Exception e, Response<JsonObject> result) {
if (result != null) {
if (result.getHeaders().code() == 200) {
Toast.makeText(MainActivity.this, "Login Success", Toast.LENGTH_SHORT).show();
} else if (result.getHeaders().code() == 401) {
Toast.makeText(MainActivity.this, "Invalid Username or password", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Something wrong check connection !!!", Toast.LENGTH_SHORT).show();
}
}
}
});
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();
}
}
});
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();
}
}
The question is simple. Actually When I try to toast message, It is not getting displayed. Could you please guide me to resolve this.
protected String doInBackground(Void... params) {
if (result.equals("200")) {
Toast.makeText(CallArduino,appliance + " Success ",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(CallArduino, "Failed", Toast.LENGTH_SHORT).show();
}
return "success";
}
Toast can't be shown in background thread you should call it within the UI thread, in onPostExecute() for example
You are trying to do a UI operation on a background thread, which is forbidden.
Any UI operation (including displaying a toast) must be done in the UI thread.
You could for instance display your toast in the onPostExecute method:
protected String doInBackground(Void... params) {
// do your background stuff
}
protected void onPostExecute (Result result) {
if (result.equals("200")) {
Toast.makeText(CallArduino,appliance + " Success ",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(CallArduino, "Failed", Toast.LENGTH_SHORT).show();
}
}