I'm using AsyncTask in my custom Dialog.
AsyncTask works fine in activity, but inside dialog doesn't show ProgressDialog.
Tried do privid context from dialog, from activity who showed dialog, app context.
Result is same: no ProgressDialog shown on my screen.
private class ClearCache_Task extends AsyncTask<Integer,Integer,Integer>
{
private ProgressDialog progressBar;
private ArrayList<String> m_subfolders;
private final Context m_con;
public ClearCache_Task(Context con, ArrayList<String> subfolders)
{
m_con = con;
m_subfolders = subfolders;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressBar = new ProgressDialog(m_con);
progressBar.setIndeterminate(true);
progressBar.setCancelable(false);
progressBar.setMessage("Please wait...");
progressBar.show();
}
#Override
protected void onPostExecute(Integer result)
{
super.onPostExecute(result);
progressBar.dismiss();
}
#Override
protected Integer doInBackground(Integer... params)
{
try
{
m_KFileStorage.ClearCache(m_subfolders);
}
catch (Exception e)
{
e.printStackTrace();
Log.e(AppTag, e.toString());
}
return 0;
}
how you attached dialog to activity?
That's how I did it:
In Activity:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(Application.string(R.string.dialog_message) + "...");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
In AsyncTask:
#Override
protected void onPreExecute() {
super.onPreExecute();
mActivity.showDialog(DIALOG_PROGRESS);
}
More information about Dialog can be read here: http://developer.android.com/guide/topics/ui/dialogs.html
Sorry for question.
I made mistake calling old code instead of calling asynctask.:)
Related
I have a function for copy file in storage. When I click to copy Button, the method copy action will execute. This method below:
public void actionCopy() {
Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progress_layout);
TextView progressTitle = (TextView) dialog.findViewById(R.id.progress_title);
progressTitle.setText("Copying...");
final ProgressBar progressBar = (ProgressBar) dialog.findViewById(R.id.progress_bar);
progressBar.setMax(listData.size());
progressBar.setProgress(0);
dialog.show();
for(int i = 0; i < listData.size(); i++) {
String value = new CopyDataUtils(listData.get(i)).execute().get();
progressBar.setProgress(i + 1);
Log.i(TAG, value);
}
}
And the CopyDataUtils AsyncTask:
public class CopyDataUtils extends AsyncTask<Void, Void, String> {
private DataItem item;
public CopyDataUtils(DataItem item) {
this.item = item;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
//...code copy file here
return ...;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
So My problem is: When actionCopy execute, I want dialog show display. But did not happen. After for(..) executed, the dialog was show.
What something wrong?. Is there any suggestion for show dialog before execute multi thread copy data?.
Sorry my bad english!
**UPDATE:
I tried put dialog to AsyncTask and show it in to method onPreExecute. But nothing change.
Problem is new CopyDataUtils(listData.get(i)).execute().get();. It blocks the UI thread and waits if necessary for the computation to complete, and then retrieves its result.
The way you are using AsyncTask and dialog is completly wrong. You should move these code to AsynTask. On onPreexecute you should show dialog. doInbackground do you task and at onPostexecute hide dialog.
u should show the progress bar in onPreEcecute() of Asynctask
public void onPreExecute()
{
progressDialog = new ProgressDialog(activity);
progressDialog.setMessage("your content");
progressDialog.setMax(listData.size());
progressDialog.setProgress(0);
for(int i = 0; i < listData.size(); i++) {
String value = new CopyDataUtils(listData.get(i)).execute().get();
Log.i(TAG, value);
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
return ...;
}
#Override
public void onPostExecute(String s)
{
progressBar.setProgress(i + 1);
}
You should make your ProgressBar as a global variable, then update the progress in onPostExcute() of AsyncTask
public void YouActiviy() {
ProgressBar progressBar;
int i = 0;
public onCreate(){
....
}
public void actionCopy() {
...
progressBar = (ProgressBar) dialog.findViewById(R.id.progress_bar);
...
dialog.show();
for(int i = 0; i < listData.size(); i++) {
new CopyDataUtils(listData.get(i)).execute();
//progressBar.setProgress(i + 1);
}
}
public class CopyDataUtils extends AsyncTask<Void, Void, String> {
...
#Override
protected void onPostExecute(String s) {
// update your progressbar here
progressBar.setProgress(i++);
super.onPostExecute(s);
}
}
}
For easy way, you follow this tutorial that will give you the correct way to use AsyncTask with ProgressBar
Hope this help
You should set progress in onProgressUpdate(), try this:
protected ProgressDialog mProgressDialog;
private class copyData extends AsyncTask<String, Integer, String> {
protected String doInBackground(Void... params) {
//copy data here
return ...;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
}
protected void onPostExecute(String result) {
try {
if ((mProgressDialog != null) && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} finally {
mProgressDialog = null;
}
}
}
I'm trying to show a progress dialog while the twitter feed is loading up...However the progress dialog remains on screen when the twitter feed appears. Any help is much appreciated.
public class MainActivity extends ListActivity {
final static String twitterScreenName = "CFABUK";
final static String TAG = "MainActivity";
private AsyncTask<Object, Void, ArrayList<TwitterTweet>> tat;
boolean done;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
done=false;
AndroidNetworkUtility androidNetworkUtility = new AndroidNetworkUtility();
if (androidNetworkUtility.isConnected(this)) {
TwitterAsyncTask syn=new TwitterAsyncTask();
syn.execute(twitterScreenName,this);
ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setMessage("loading");
pd.show();
do {
if(!(syn.getStatus()==AsyncTask.Status.RUNNING)) {
pd.dismiss();
pd.cancel();
done=true;
}
} while(done=false);
} else {
Log.v(TAG, "Network not Available!");
}
}
}
You must call ProgressDialog show() method on AsyncTasks onPreExecute(). For example:
class MyTask extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("loading");
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
// Do your request
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pd != null)
{
pd.dismiss();
}
}
}
You must use a onPreExecute and onPostExecute of AsyncTask class. For example:
class AsyncData extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
// init progressdialog
}
#Override
protected Void doInBackground(Void... arg0) {
// get data
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// dismiss dialog
}
}
The methods onPreExecute(), doInBackground() and onPostExecute() of AsyncTask are used for purpose that you mentioned -
public class MainActivity extends ListActivity {
final static String twitterScreenName = "CFABUK";
final static String TAG = "MainActivity";
private AsyncTask<Object, Void, ArrayList<TwitterTweet>> tat;
boolean done;
Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
done=false;
context = this;
new NetworkTask().execute();
}
}
class NetworkTask extends AsyncTask<String, String, String>
{
Context ctx = context ;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Working ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args)
{
//Do your background work here and pass the value to onPostExecute
AndroidNetworkUtility androidNetworkUtility = new AndroidNetworkUtility();
if (androidNetworkUtility.isConnected(ctx)) {
TwitterAsyncTask syn=new TwitterAsyncTask();
syn.execute(twitterScreenName,this);
while(done)
{
if(!(syn.getStatus()==AsyncTask.Status.RUNNING))
{
done=true;
}
else
{
Log.v(TAG, "Network not Available!");
}
}
return done + "";
}
protected void onPostExecute(String result)
{
//Do something with result and close the progress dialog
pDialog.dismiss();
}
ProgressBar is best alternative for ProgressDialog. A user interface element that indicates the progress of an operation.
ProgressDialog is deprecated in latest versions.
For more info see android developer official site: https://developer.android.com/reference/android/widget/ProgressBar.html
public void generateNumbers(){
progressBar.setVisibility(View.VISIBLE);
while(){
//approximately 5 second long procedure
}
printNumbers();
progressBar.setVisibility(View.GONE);
}
I want that the progress bar is visible when this long procedure in while loop is running and then dissapear. The code like this shown progressBar after the loop is finished and then also dissapear (setVisiblity(GONE)).
In while loop i don't have any new threads or AsyncTask
Use an asynctask like this
public class asyncTask extends AsyncTask<String, Void, String> {
private Context context;
private ProgressDialog dialog;
public asyncTask(Context cxt) {
context = cxt;
dialog = new ProgressDialog(context);
}
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog.setTitle("Please Wait...");
dialog.show();
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
}
#Override
protected String doInBackground(String... arg0) {
//Put your code here
}
}
I want to show ProgressDialog when I click on Login button and it takes time to move to another page. How can I do this?
ProgressDialog pd = new ProgressDialog(yourActivity.this);
pd.setMessage("loading");
pd.show();
And that's all you need.
You better try with AsyncTask
Sample code -
private class YourAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
public YourAsyncTask(MyMainActivity activity) {
dialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
dialog.setMessage("Doing something, please wait.");
dialog.show();
}
#Override
protected Void doInBackground(Void... args) {
// do background work here
return null;
}
#Override
protected void onPostExecute(Void result) {
// do UI work here
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
Use the above code in your Login Button Activity. And, do the stuff in doInBackground and onPostExecute
Update:
ProgressDialog is integrated with AsyncTask as you said your task takes time for processing.
Update:
ProgressDialog class was deprecated as of API 26
To use ProgressDialog use the below code
ProgressDialog progressdialog = new ProgressDialog(getApplicationContext());
progressdialog.setMessage("Please Wait....");
To start the ProgressDialog use
progressdialog.show();
progressdialog.setCancelable(false); is used so that ProgressDialog cannot be cancelled until the work is done.
To stop the ProgressDialog use this code (when your work is finished):
progressdialog.dismiss();`
Point one you should remember when it comes to Progress dialog is that you should run it in a separate thread. If you run it in your UI thread you'll see no dialog.
If you are new to Android Threading then you should learn about AsyncTask. Which helps you to implement a painless Threads.
sample code
private class CheckTypesTask extends AsyncTask<Void, Void, Void>{
ProgressDialog asyncDialog = new ProgressDialog(IncidentFormActivity.this);
String typeStatus;
#Override
protected void onPreExecute() {
//set message of the dialog
asyncDialog.setMessage(getString(R.string.loadingtype));
//show dialog
asyncDialog.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
//don't touch dialog here it'll break the application
//do some lengthy stuff like calling login webservice
return null;
}
#Override
protected void onPostExecute(Void result) {
//hide the dialog
asyncDialog.dismiss();
super.onPostExecute(result);
}
}
Good luck.
Simple coding in your activity like below:
private ProgressDialog dialog = new ProgressDialog(YourActivity.this);
dialog.setMessage("please wait...");
dialog.show();
dialog.dismiss();
Declare your progress dialog:
ProgressDialog progressDialog;
To start the progress dialog:
progressDialog = ProgressDialog.show(this, "","Please Wait...", true);
To dismiss the Progress Dialog :
progressDialog.dismiss();
ProgressDialog is now officially deprecated in Android O. I use DelayedProgressDialog from https://github.com/Q115/DelayedProgressDialog to get the job done.
Usage:
DelayedProgressDialog progressDialog = new DelayedProgressDialog();
progressDialog.show(getSupportFragmentManager(), "tag");
This is the good way to use dialog
private class YourAsyncTask extends AsyncTask<Void, Void, Void> {
ProgressDialog dialog = new ProgressDialog(IncidentFormActivity.this);
#Override
protected void onPreExecute() {
//set message of the dialog
dialog.setMessage("Loading...");
//show dialog
dialog.show();
super.onPreExecute();
}
protected Void doInBackground(Void... args) {
// do background work here
return null;
}
protected void onPostExecute(Void result) {
// do UI work here
if(dialog != null && dialog.isShowing()){
dialog.dismiss()
}
}
}
when you call in oncreate()
new LoginAsyncTask ().execute();
Here how to use in flow..
ProgressDialog progressDialog;
private class LoginAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
progressDialog= new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Please wait...");
progressDialog.show();
super.onPreExecute();
}
protected Void doInBackground(Void... args) {
// Parsse response data
return null;
}
protected void onPostExecute(Void result) {
if (progressDialog.isShowing())
progressDialog.dismiss();
//move activity
super.onPostExecute(result);
}
}
ProgressDialog dialog =
ProgressDialog.show(yourActivity.this, "", "Please Wait...");
ProgressDialog pd = new ProgressDialog(yourActivity.this);
pd.show();
Step 1:Creata a XML File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/btnProgress"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Progress Dialog"/>
</LinearLayout>
Step 2:Create a SampleActivity.java
package com.scancode.acutesoft.telephonymanagerapp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class SampleActivity extends Activity implements View.OnClickListener {
Button btnProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnProgress = (Button) findViewById(R.id.btnProgress);
btnProgress.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final ProgressDialog progressDialog = new ProgressDialog(SampleActivity.this);
progressDialog.setMessage("Please wait data is Processing");
progressDialog.show();
// After 2 Seconds i dismiss progress Dialog
new Thread(){
#Override
public void run() {
super.run();
try {
Thread.sleep(2000);
if (progressDialog.isShowing())
progressDialog.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
}
final ProgressDialog loadingDialog = ProgressDialog.show(context,
"Fetching BloodBank List","Please wait...",false,false); // for showing the
// dialog where context is the current context, next field is title followed by
// message to be shown to the user and in the end intermediate field
loadingDialog.dismiss();// for dismissing the dialog
for more info
Android - What is difference between progressDialog.show() and ProgressDialog.show()?
ProgressDialog is deprecated since API 26
still you can use this:
public void button_click(View view)
{
final ProgressDialog progressDialog = ProgressDialog.show(Login.this,"Please Wait","Processing...",true);
}
Simple Way :
ProgressDialog pDialog = new ProgressDialog(MainActivity.this); //Your Activity.this
pDialog.setMessage("Loading...!");
pDialog.setCancelable(false);
pDialog.show();
final ProgressDialog progDailog = ProgressDialog.show(Inishlog.this, contentTitle, "even geduld aub....", true);//please wait....
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Barcode_edit.setText("");
showAlert("Product detail saved.");
}
};
new Thread() {
public void run() {
try {
} catch (Exception e) {
}
handler.sendEmptyMessage(0);
progDailog.dismiss();
}
}.start();
Whenever you want ProgressDialog call this method
private void startLoader() {
progress = new ProgressDialog(this); //ProgressDialog
progress.setTitle("Loading");
progress.setMessage("Please wait");
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setCancelable(false);
progress.show();
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(7000);
} catch (Exception e) {
e.printStackTrace();
}
progress.dismiss();
}
}).start();
}
I have an android application which in its main activity, data are adapted from sqlite db and shown in list view. I tried to use Progress dialog to show 'loading' message to user during fetching data from db. But the dialog does not disappear.
Here is the code :
public class BirthdayAlarmActivity extends ListActivity {
List<BirthdayContact> listofAvailableBirthdays;
ProgressDialog pDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.birthday_list);
listofAvailableBirthdays=new ArrayList<BirthdayContact>();
ReinitializeList();
}
#Override
protected void onResume() {
ReinitializeList();
}
void ReinitializeList()
{
new LoadListView().execute();
if(listofAvailableBirthdays.size()>0)
{
//get ready the adapter
ArrayAdapter<BirthdayContact> ara=
new MyArrayAdapter(BirthdayAlarmActivity.this,listofAvailableBirthdays);
//set the adapter
setListAdapter(ara);
}
}
public class LoadListView extends AsyncTask<Void, Void, Void>
{
//ProgressDialog pDialog;
#Override
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(
BirthdayAlarmActivity.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... unused) {
runOnUiThread(new Runnable() {
public void run() {
// increment current page
listofAvailableBirthdays.clear();
listofAvailableBirthdays=BirthdayHandler.GetTenBirthDays(BirthdayAlarmActivity.this);
}
});
return (null);
}
protected void onPostExecute(Void unused) {
// closing progress dialog
pDialog.dismiss();
}
}
I'm not familiar with the technique you're using, but I'll share what works for me:
final ProgressDialog progress = ProgressDialog.show(activity, "",
activity.getString(R.string.please_wait), true);
new Thread(new Runnable() {
#Override
public void run()
{
try {
--- network activity to retrieve information ---
}
finally {
activity.runOnUiThread(new Runnable() {
#Override
public void run()
{
if ((progress != null) && progress.isShowing())
progress.dismiss();
}
});
}
}
}).start();
I think the problem here is that you're referring to your pDialog and trying to create it in a different class than the one you've declared it in.
You should try using showDialog, dismissDialog and onCreateDialog methods to add a layer of abstraction and that the dialog is being called in the correct class/thread. You can use a Handler aswell as an alternative.
try something like this:
public class BirthdayAlarmActivity extends ListActivity {
List<BirthdayContact> listofAvailableBirthdays;
ProgressDialog pDialog;
static final int LOADING_DIALOG = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.birthday_list);
listofAvailableBirthdays=new ArrayList<BirthdayContact>();
ReinitializeList();
}
#Override
protected void onResume() {
ReinitializeList();
}
void ReinitializeList()
{
new LoadListView().execute();
if(listofAvailableBirthdays.size()>0)
{
//get ready the adapter
ArrayAdapter<BirthdayContact> ara=
new MyArrayAdapter(BirthdayAlarmActivity.this,listofAvailableBirthdays);
//set the adapter
setListAdapter(ara);
}
}
#Override
protected Dialog onCreateDialog(int id)
{
switch(id)
{
case LOADING_DIALOG:
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(
BirthdayAlarmActivity.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
return pDialog;
}
}
public class LoadListView extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
showDialog(LOADING_DIALOG);
}
protected Void doInBackground(Void... unused) {
runOnUiThread(new Runnable() {
public void run() {
// increment current page
listofAvailableBirthdays.clear();
listofAvailableBirthdays=BirthdayHandler.GetTenBirthDays(BirthdayAlarmActivity.this);
}
});
return (null);
}
protected void onPostExecute(Void unused) {
dismissDialog(LOADING_DIALOG);
}
}
If this fails, you should look int using messaging via the Handler class.