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.
Related
This question already has answers here:
How to show progress dialog in Android?
(17 answers)
Closed 3 years ago.
I wanted a progress dialog to appear while my activity gets some data. I used Async task but however it doesn't show up
I have tried all the answers of the previous Stack Overflow questions but none of them seem to work for me
private class BackgroundSync extends AsyncTask<Void,Void,Void> {
ProgressDialog progress = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
progress.setMessage("Loading");
progress.setTitle("Loading");
progress.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
/get data
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
progress.dismiss();
super.onPostExecute();
}
}
I have also tried this using
progress = ProgressDialog.show(MainActivity.this,"Loading","Loading");
as one stack overflow answer suggested but it still doesn't show
I also used the below code, but this time the ProgressDialog doesn't disappear
private class BackgroundSync extends AsyncTask<Void,Void,Void> {
ProgressDialog progress
#Override
protected void onPreExecute() {
progress = new ProgressDialog(MainActivity.this);
progress.show(MainActivity.this,"Loading","Loading");
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
SyncEvents();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
progress.dismiss();
}
}`
What do I do? This ProgressDialog issue has been taking more than 2 hours to solve
use this code
private class BackgroundSync extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
public BackgroundSync(MyMainActivity activity) {
dialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
dialog.setMessage("Loading");
dialog.setTitle("Loading");
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();
}
}
}
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
I know there was similiar problem to this, but I still haven't found an answer. The problem is that progress dialog for this long operation won't show up, but still process is being done. I think there is problem with the context, but dunno how to solve this.
public class MainActivity extends Activity {
Utilities uti = new Utilities();
SharedPreferences prefs = null;
private ContactServiceActivity contactService;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactService = new ContactServiceActivity(getApplicationContext());
doFirstRun();
Intent i = new Intent(getBaseContext(), ContactListActivity.class);
startActivity(i);
}
private void doFirstRun() {
SharedPreferences settings = getSharedPreferences("pl.stxnext.stxcontactsync", MODE_PRIVATE);
if (settings.getBoolean("isFirstRun", true)) {
new firstRunTask().execute();
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isFirstRun", false);
editor.commit();
}
}
private class firstRunTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Trwa synchronizacja danych");
mProgressDialog.setMessage("Może to zająć chwilę, proszę czekać.");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
contactService.getAssetsAtFirstRun();
return null;
}
#Override
protected void onPostExecute(Void result) {
mProgressDialog.dismiss();
uti.showToast(getBaseContext(), "Zapisano kontakty.");
}
}
}
create one constructor like:
Context _context;
public firstRunTask(Context context)
{
_context=context;
}
and use this _context for context in dialog.
Try like this
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// Do something
return "Executed";
}
#Override
protected void onPostExecute(String result) {
if(mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
}
#Override
protected void onPreExecute() {
ShowLoading();
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
private void ShowLoading(){
mProgressDialog = new ProgressDialog(this);
//mProgressDialog.setMessage("Loading Please wait ....");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
You are starting an activity after starting the asyctask by calling doFirstRun(); , and thus you are not seeing the progressdialog created. if you remove/comment the startActivity portion as follows, it should work:
doFirstRun();
// comment the following
//Intent i = new Intent(getBaseContext(), ContactListActivity.class);
//startActivity(i);
If you still want to start that activity anyway, then you should start the asynctask after that.
Do this-
private class firstRunTask extends AsyncTask<Void, Void, Void> {
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog=ProgressDialog.show(MainActivity.this, "Trwa synchronizacja danych", "Może to zająć chwilę, proszę czekać.");
}
#Override
protected Void doInBackground(Void... params) {
contactService.getAssetsAtFirstRun();
return null;
}
#Override
protected void onPostExecute(Void result) {
if(mProgressDialog != null)
{
if(mProgressDialog.isShowing())
{
mProgressDialog.dismiss();
uti.showToast(getBaseContext(), "Zapisano kontakty.");}
}
}
I have a simple class which extends activiy like this
public class About extends Activity
{
private ProgressDialog pdia;
private TextView tvAbout;
private WebView vwAbout;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
vwAbout = (WebView)findViewById(R.id.vwViewAbout);
String content = new String();
try {
URL url = new URL("http://xxx.prodevAbout.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null)
{
content+=str + "\n";
vwAbout.loadData(content, "text/html", null);
}
in.close();
} catch (Exception e)
{
vwAbout.loadData("error message", "text/html", null);
}
}
}
and what I want to do is I want to add a progressbar while loading content from website and I found this code
private ProgressDialog pdia;
#Override
protected void onPreExecute(){
super.onPreExecute();
pdia = new ProgressDialog(yourContext);
pdia.setMessage("Loading...");
pdia.show();
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
pdia.dismiss();
}
and added this code but onPreExecute method cannot be resolved What should I do ?
Thanks;
The way which I am adding progress dialogs in my apps (and I've never had any problems till now) is like this :
Runnable runable = new Runnable() {
#Override
public void run() {
SofiaLiveCafeActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB){
progressDialog = new ProgressDialog(SofiaLiveCafeActivity.this, ProgressDialog.THEME_HOLO_LIGHT);
} else {
progressDialog = new ProgressDialog(SofiaLiveCafeActivity.this);
}
progressDialog.setMessage("Loading! Pleasе wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
});
// CONNECT TO SERVER AND DOWNLOAD DATA
SofiaLiveCafeActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
progressDialog.dismiss();
}
});
}
}
};
new Thread(runable).start();
added this code but onPreExecute method cannot be resolved What should
I do ?
onPreExecute not resolved because this is method from AsyncTask so will need to extends AsyncTask class to use onPreExecute change your current code using AsyncTask as :
public class About extends Activity
{
[...your code here...]
public void onCreate(Bundle savedInstanceState)
{
[...your code here...]
// execute AsyncTask as
new LongOperation(About.this).execute("");
}
[...your code here...]
public class WebapiOperation extends AsyncTask<String, Void, String> {
Context context;
WebapiOperation(Context context){
this.context=context;
}
#Override
protected void onPreExecute() {
// show ProgressDialog here
pdia = new ProgressDialog(context);
}
#Override
protected String doInBackground(String... params) {
// make web service access task here
return null;
}
#Override
protected void onPostExecute(String result) {
// ProgressDialog here
}
}