Asynchronous task not show Progress Dialog on click event of button - android

In my application when i click on Button it sometimes shows the progressdialog and sometimes not show the progressdialog on click of button.
Asynchronous Task code is:
public class LoadData extends AsyncTask<Void, Void, Void>
{
ProgressDialog pd;
#Override
protected void onPreExecute()
{
pd = ProgressDialog.show(MainActivity.this, "", "Loading...");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
LoadActivities(); // function to load data from url
}
});
return null;
}
#Override
protected void onPostExecute(Void unused)
{
pd.dismiss();
}
}
and on button click event call this as:
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new LoadMoreData().execute(null);
}
});

the wrong think you are doing is that in doInBackground you use runOnUiThreade . just remove that from your code . It solves your problem.
never use any thread in doInBackground.

Why you have taken run method again in doInBackground, doInBackground method performs computation on a background thread, so no need to take runOnUiThread
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
LoadActivities(); // function to load data from url
}
});
Just write
protected Boolean doInBackground(final String... args) {
try {
LoadActivities();
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
And also change new LoadMoreData().execute(); don't write null
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new LoadMoreData().execute();
}});

Nirali's answer seems correct, just to make further explaination and some edits.
Progress Dialog will be shown by the time doInBackground method returns value. and in your code it just create another thread, and completes execution, so to display progress dialog by the time LoadActivities exectues, execute this statement in the same thread doInBackground executes, so change to following:
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
MainActivity.this.runOnUiThread(new Runnable() {
LoadActivities(); // function to load data from url
return null;
}

Related

Android progress spinner loader stops spinning when the data starts fetching in background

I am using a progress spinner on pre execute method of Async task to show it on UI and the data starts fetching in the background from Api using volley library.The problem is when it starts fetching the data,the loader stops spinning and its like the UI is not responding.
need help,Thanks in advance..
`
ProgressDialog dialog;
public void open() {
dialog = new ProgressDialog(BuzoongaContacts.this);
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
dialog.setContentView(R.layout.progress_layout);
dialog.setCanceledOnTouchOutside(false);
}
public void stopLoading() {
Log.d("res", "stopLoading ");
try {
dialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
}
}`
Async Task:
class BuzoongaContactsAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
runOnUiThread( new Runnable() {
public void run() {
open();
}
});
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
ContactsDataTableOperations conDataTab = new ContactsDataTableOperations(BuzoongaContacts.this);
conDataTab.open();
JSONParsingForContactsB.count = 0;
count = 0;
if (fromRefresh)
{
if (isInternetConnected()) {
getBuzzongaContacts();
} else {
rl_sub_main_buzoongaContacts.startAnimation(animZoomOut);
alertDialog("Network Error !",getResources().getString(R.string.network_error));
rl_alert.startAnimation(animMoveUp);
}
} else
{
if (getContactsExistence() == 0) {
if (isInternetConnected()) {
getBuzzongaContacts();
} else {
rl_sub_main_buzoongaContacts.startAnimation(animZoomOut);
alertDialog("Network Error !", getResources().getString(R.string.network_error));
rl_alert.startAnimation(animMoveUp);
}
} else if (Constants.buzoongaContactsAdded)
{
if (isInternetConnected()) {
getBuzzongaContacts();
} else {
rl_sub_main_buzoongaContacts.startAnimation(animZoomOut);
alertDialog("Network Error !", getResources().getString(R.string.network_error));
rl_alert.startAnimation(animMoveUp);
}
} else {
stopLoading();
}
}
arr_list = conDataTab.getAllRecords();
conDataTab.close();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
cb_select_all.setChecked(false);
iv_quick_launch.setBackgroundResource(R.drawable.quick_lounch_icon_disable);
Constants.selected_buzoonga_contacts = 0;
rl_delete.setAlpha(0.5f);
rl_delete.setClickable(false);
rl_show_contacts.setVisibility(View.INVISIBLE);
mAdapter.notifyDataSetChanged();
}
}
Basically, you can't touch your UI elements in background threads, which means that all your calls to startAnimation() or stopLoading should be wrapped with runOnUiThread.
But I can see your UI code is so bound up with your background code. Maybe you could consider using Thread & Handler instead of AsyncTask.

Displaying error message in an activity from a seperate public asyncTask class

I am creating the user registration part of my app. I am using the AsyncTask class to handle this work on a separate thread. I have my AsyncTask class in a seperate class file. This
public class CreateAccountTask extends AsyncTask<String, Void, String>{
private ProgressDialog mpDialog;
private CreateAccountTask task;
private Context context;
private Activity activity;
private CreateAccount createAccount;
private AsyncTaskListener asyncTaskListener;
public CreateAccountTask(Activity activity, AsyncTaskListener asyncTaskListener){
this.activity = activity;
this.asyncTaskListener = asyncTaskListener;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mpDialog = new ProgressDialog(activity);
//mpDialog.setTitle("Creating Account");
mpDialog.setMessage("Please wait.");
mpDialog.setCancelable(false);
mpDialog.setIndeterminate(false);
mpDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
//task.cancel(true);
mpDialog.dismiss();
}
});
mpDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String fphoneNo = arg0[1];
String fpassword = arg0[0];
// create instance of the parseUser Class
ParseUser newUser = new ParseUser();
newUser.setUsername(fphoneNo);
newUser.setPassword(fpassword);
// here Check if progress dialog has been cancelled
if (!isCancelled()){
// if dialog has not been cancelled create the new user here
newUser.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
// Something went wrong Sorry!
if(e != null ){
if(!isCancelled()){
mpDialog.dismiss();
String errorMessage = e.getMessage().toString();
ErrorHappened(errorMessage);
}
else{
String errorMessage = "Registration Cancelled!";
ErrorHappened(errorMessage);
}
}
// No Problems
else {
if (!isCancelled()) {
// Wait for five seconds before starting the activity
//verifyingUser();
}
else {
String errorMessage = "Registration Cancelled2!";
ErrorHappened(errorMessage);
//Delete user in background
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
currentUser.deleteInBackground();
}
}
}
}
});
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
asyncTaskListener.onTaskComplete(result);
}
private void ErrorHappened(String errorMessage) {
Crouton CreateMagic = Crouton.makeText(createAccount, errorMessage, CroutonClass.ALERT);
CreateMagic.setConfiguration(CroutonClass.configure);
CreateMagic.show();
}
}
In my onPreExecute method, i start a progressDialog that shows while the background task is being executed. While in my doInBackground method i have i get the username and password supplied by the user in the main Activity and sign up the user. This is where my problem begins, If an error occurs during the user registration, i want to notify the user of this error using a Crouton (A cooler version of a toast). But the app crashes when it gets to the point of displaying the error with the crouton.
My question is:
How do i display the error message in my activity?
2.
here is my Activity:
public class CreateAccount extends ActionBarActivity implements AsyncTaskListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
mPassWord = (EditText) findViewById(R.id.password);
mcreateAccount = (Button) findViewById(R.id.createAcct);
mPhoneNumber = (EditText) findViewById(R.id.Phone_Number);
// create account Method
createAccount();
}//end of on create.
public void createAccount() {
mcreateAccount.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
CreateAccountTask newTask = new CreateAccountTask(CreateAccount.this, new CreateAccount());
newTask.execute(passwordString, fpartphoneNo);
});
}
private void verifyingUser() {
}
private void shitHappened(String errorMessage) {
// TODO Auto-generated method stub
Crouton CreateMagic = Crouton.makeText(this, errorMessage, CroutonClass.ALERT);
CreateMagic.setConfiguration(CroutonClass.configure);
CreateMagic.show();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Crouton.cancelAllCroutons();
super.onBackPressed();
}
#Override
public void onTaskComplete(String result) {
// TODO Auto-generated method stub
}
}
Notifications and any other UI manipulation is only allowed from the UIThread. If you look at the documentation of AsyncTask, doInBackground() runs on its own Thread, while onPreExecute(), onPostExecute() and onCancelled() run on the UIThread.
In your case, you should use protected void onCancelled(String result) for the Notification. This runs on the UIThread and helps you to distinguish between a successful and unsuccessful operations. To use this, call cancel() and check in doInBackground() if the operation was cancelled.
onCancelled() will then be executed instead of onPostExecute()
In your special case it could be a problem of the context, because you are storing your CreateAccount.this in the constructor in activity of your CreateAccountTask, but you are using createAccount. Try changing it to the following:
Crouton.makeText(activity, errorMessage, CroutonClass.ALERT);
Use runOnUiThread as below...
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
runOnUiThread(new Runnable() {
#Override
public void run() {
mpDialog = new ProgressDialog(activity);
//mpDialog.setTitle("Creating Account");
mpDialog.setMessage("Please wait.");
mpDialog.setCancelable(false);
mpDialog.setIndeterminate(false);
mpDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
//task.cancel(true);
mpDialog.dismiss();
}
});
mpDialog.show();
}
}

runOnUiThread is not running in AsyncTask

I'm coding a program which fetches the data from MySql from server (using JSON) and it updates the UI accordingly,
I'm fetching two types of data using AsyncTask from Server
1) Bubble Answers
2) Comments
The parseBubbleAnswers method successfully runs and Updates UI,
but parseComments class which is AsyncTask, and which call parseComments method in doInBackground, is not running runOnUiThread(new Runnable() { run() });
Can anyone help me in solving this
Here is my code :
public class FetchServer extends Activity
{
protected void onCreate(Bundle savedInstanceState)
{
String photoId = "1"; // photo id for which the data is fetched
checkBubbleData(photoId); // which call AsyncTask - 2 differnt calls
}
public void checkBubbleData(String photoId)
{
new parseBubbleAnswers().execute(photoId); // to fetch bubble answers
new parseComments().execute(photoId); // to fetch comments
}
class parseBubbleAnswers extends AsyncTask<String, Integer,String>
{
#Override
protected String doInBackground(String... params)
{
// TODO Auto-generated method stub
Looper.prepare();
parseBubbleAnswers(); // which has runOnUiThread(new Runnable() which updates (successfully !) the UI
return null;
}
}
class parseComments extends AsyncTask<String, Integer,String>
{
#Override
protected String doInBackground(String... params)
{
// TODO Auto-generated method stub
Looper.prepare();
String parseComReturn = parseComments();
if(parseComReturn=="end")
{
commentBuilder(); // which will update UI after fetch data by parseComments() method
}
}
}
public void commentBuilder()
{
runOnUiThread(new Runnable() // while debugging, it comes here, on Step Over it stick for 2 times and then move at the end of method without error
{
public void run()
{
// update UI code
}
});
}
}
Try this way :
First create one Handler :
Handler mHandler = new Handler();
Change this,
public void commentBuilder()
{
runOnUiThread(new Runnable() // while debugging, it comes here, on Step Over it stick for 2 times and then move at the end of method without error
{
public void run()
{
// update UI code
}
});
}
With,
public void commentBuilder()
{
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
try {
// Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// Write your code here to update the UI.
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
}
Stop thread by this once you are done with UI,
isRunning = false;
EDIT :
Try to Use Async Task in this way :
class parseComments extends AsyncTask<String, Integer,String>
{
protected String doInBackground(String... params) {
String parseComReturn = parseComments();
return parseComReturn;
}
protected void onPostExecute(String result) {
if(result.equals("end"))
{
commentBuilder();
}
}
}
Thanks.
runOnUiThread is a method of Activity, AsyncTask has no reference to Activity.
however, AsyncTask already runs on the UI thread and was designed to do exactly that.
just deal with the UI changes in onPostExecute.
I faced the similar issue.
Just pass the reference of the Activity class to the parseComments class.
class parseComments extends AsyncTask<String, Integer,String>{
Activity activity;
public parseComments(Activity activity){
this.activity = activity;
}
}
After that you can use runOnUiThread as
activity.runOnUiThread(new Runnable(){
#Override
public void run(){
}
});
It will only work with Activity class. Not Context class.

My ProgressDialog doesn't dismiss even after the view has been loaded.

I want to show a Progress-Dialog before my view has been loaded.
First i wrote the code in onCreate() but the dialog doesn't appear in that case. So i wrote it in onResume() but in this case, it doesn't disappear even after the view has been loaded. can anyone tell whats going wrong here?
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
dialog = ProgressDialog.show(this, "", "Please wait...", true);
//dialog.cancel();
new Thread()
{
public void run()
{
try
{
sleep(1500);
// do the background process or any work that takes time to see progress dialog
}
catch (Exception e)
{
Log.e("tag",e.getMessage());
}
// dismiss the progressdialog
dialog.dismiss();
}
}.start();
citySelected.setText(fetchCity);
spinner.setSelection(getBG);
}
You cant update UI(which is in main UIthread) from other threads. If you want to run any query in the background, you can use AsyncTask.
In onPreExecute method, show dialog and onPostExecute you can dismiss the dialog.
If you want to use Thread, then update UI using handlers.
Using AsyncTask
public class MyAsyncTask extends AsyncTask<String, Void, String> {
ProgressDialog dialog = new ProgressDialog(ActivityName.this);
#Override
protected void onPreExecute() {
dialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
super.onPostExecute(result);
}
}
In Activity onCreate Method,
MyAsyncTask task = new MyAsyncTask();
task.execute();
better to use Asynctask ......... but if you still want same or want to know the solution only then can try
new Thread()
{
public void run()
{
try
{
sleep(1500);
// do the background process or any work that takes time to see progress dialog
}
catch (Exception e)
{
Log.e("tag",e.getMessage());
}
YourActivity.this.runOnUIThread(new Runnable(){
#Override
public void run(){
// dismiss the progressdialog
dialog.dismiss();
});
}
}.start();
You can use AsyncTask. It is better than Thread
private class DownloadingProgressTask extends
AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(ShowDescription.this);
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
protected Boolean doInBackground(final String... args) {
try {
downloadFile(b.getString("URL"));
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}

progress Dialog simpel

i want to add a progress Dialog button when i click on this button before the new activity apperar, i think i don't need a thread, i did search but i find only that i need to do a thread and many other think it s not clear
i just want when i clik on a progress Dialog say to the user to wait so a few sec the other activity will appear that's all:
btn_newsfeed.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(getApplicationContext(), CustomizedListView.class);
startActivity(i);
}
});
There are three different different ways in which you can use a ProgressDailog -using threads, handlers and async tasks.
here a example of async task for using a progress Dialog
private class Operation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params)
{
// code to be executed in background thread
for(int i=0;i<5;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
// runs on UI thread and updated UI after executing doInBackground
progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
ProgressDialog progressDialog = ProgressDialog.show(MainActivity.this, "Title ", "Loading...");
progressDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
// runs on UI thread and starts first
}
}

Categories

Resources