I try to show a progress dialog upon showing a sliding drawer.
this is opening drawer event handler:
public void onDrawerOpened(View drawerView) {
progress = ProgressDialog.show(activity, "dialog title",
"dialog message", true);
openDrawer();
}
Inside openDrawer() i call a function fillCommunityList() that i need to show the progress dialog while its execution
fillCommunityList() implementation is as the following:
private void fillCommunityList(){
new Thread(new Runnable() {
#Override
public void run() {
try {
// Here you should write your time consuming task...
UIManager manager = new UIManager(activity);
coms = manager.getCommunities();
progress.dismiss();
getOutTread = false;
} catch (Exception e) {
}
getOutTread = false;
}
}).start();
// to stop code till thread be finished
while(getOutTread){ }
SlidingMenuExpandableListAdapter adapter = new SlidingMenuExpandableListAdapter(this,
navDrawerItems, coms, mDrawerList);
mDrawerList.setAdapter(adapter);
}
Note:
I put a thread just to make progress dialog works
My problem is the following two points:
1- progress dialog appears too late for sudden and then disappears
2- Thread takes alot of time in its execution (without thread fillCommunityList() takes around 10 seconds but with a thread it takes more than a minute)
Note: manager.getCommunities() has asyncTask in its implementation
The problem is the following line
while(getOutTread){ }
this is call busy waiting. The UI Thread is busy looping and can't, at the same time, draw/update the ProgressDialog
Related
I am working on a program that searches the users phone for some date, which takes about 2-3 seconds. While it's computing I want to display a loading screen, so the user knows something indeed is happening. However, when I try to display a loading screen before the computations, nothing is displayed on the screen.
This is what I have:
ProgressDialog loading= new ProgressDialog(this);
loading.setTitle("Loading");
loading.setMessage("Please wait...");
loading.show();
//search stuff
loading.dismiss();
In addition to this, I have tried putting the ProgressDialog in a thread like the following,
new Thread(new Runnable(){
public void run(){
ProgressDialog loading= new ProgressDialog(this);//error here for "this"
loading.setTitle("Loading");
loading.setMessage("Please wait...");
loading.show();
}
});
//search stuff
but it fails due to the "this" keyword, I believe because its referring to an Activity and not a regular class, but I could be wrong...
How can I get the ProgressDialog to display properly?
Try to handle it in this way
mProgressDialog = ProgressDialog.show(this, "Please wait","Long operation starts...", true);
new Thread() {
#Override
public void run() {
//Do long operation stuff here search stuff
try {
// code runs in a thread
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.dismiss();
}
});
} catch (final Exception ex) {
}
}
}.start();
Use async task for heavy task. Put your progress dialog code in onPreExecute method progress dialog dismiss code in onPostExecute method and all your heavy task in doInBackground method.
try passing down the context on a new class with your progress bar (this goes on your main activity)
NAME_OF_YOUR_CLASS context = new NAME_OF_YOUR_CLASS(getApplicationContext());
and on your class call the method like this..(this goes on class)
public Networking(Context c) {
this.context= c;
}
dont forget to make context a field (private final Context context;)
hope this helps
also idk if this will work but try to extend AsyncTask and use methods to run your progress bar there.
I have been getting help to create a progress bar for my Android application. Lots of help here! I'm having an issue though that I am having a hard time fixing. I have a progress bar shown while the application attempts to download files from a networked computer. This works perfectly fine, however I need to update my UI incase an error occurs. I can't update the UI inside the thread and I want to update the UI from getRaceResultsHandler. Unfortunately it executes that code prior to the thread being completed. I have tried a few things with no luck. I have a code sample with my comments below if anyone can help.
public void getRaceResultsHandler (View view) {
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setMessage("Attempting to transfer race files. Please wait...");
// Set progress style to spinner
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// display the progressbar
dialog.show();
// create a thread for downloading the files
Thread background = new Thread (new Runnable() {
public void run() {
//The Code here to execute the file download from the networked computer....
//Dismiss the progress bar because the download is either completed or failed...
dialog.dismiss();
}
});
// start the background thread
background.start();
//All Other Code Goes here to update the UI. Shows either an error message or a success based on the results of the download.
//My problem is that this code executes before the background thread is completed. I need it to wait until the thread is completed.
}
Try to dismiss that dialog using Handler
Handler h = new Handler(); // Create this object in UI Thread
Thread background = new Thread (new Runnable() {
public void run() {
h.post(new Runnable()
{
public void run()
{
dialog.dismiss();
}
};
});
You should use AsyncTask instead of normal Thread
AsyncTask<Void,Void,Void> aTask = new AsyncTask<Void,Void,Void>()
{
#Override
public void onPreExecute()
{
// Setup some UI Objects
}
#Override
public void onPostExecute(Void result)
{
dialog.dismiss();
}
#Override
protected Void doInBackground(Void...params)
{
// your download stuff
publishProgress(object) // <-- if you want to update the progress of your download task
}
});
Note: Didn't try my own, have no IDE here in my friend's laptop
I make a dialog based on this website http://www.mkyong.com/android/android-progress-bar-example/
When progress bar goes to 100%, dialog closed but a toast still appears continuously. I noticed that after bar goes to 100%, progressHandler still runs looping.
How can I solved this problem?
Thing that I want : When progress bar goes to 100% then dialog closed and Toast shows and closed.
Thread background = new Thread(new Runnable() {
#SuppressWarnings("null")
public void run() {
try {
while (dialog.getProgress() <= dialog.getMax()) {
// wait 500ms between each update
Thread.sleep(100);
// active the update handler
progressHandler.sendMessage(progressHandler.obtainMessage());
}
} catch (java.lang.InterruptedException e) {
// if something fails do something smart
Toast.makeText(getApplicationContext(), "Error Occurs",Toast.LENGTH_LONG).show();
}
}
});
// start the background thread
background.start();
}
// handler for the background updating
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
dialog.incrementProgressBy(increment);
if(dialog.getProgress()==100){
editor.putInt("lastestSummaryNoSent",summary.getCurrentSummaryNo());
editor.commit();
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Update Finished", Toast.LENGTH_LONG).show();
}
}
};
This error
Can't create handler inside thread that has not called Looper.prepare()
is because of the Toast you have provided inside the background Thread. Remove the Toast inside the Catch phrase and you will be good to go.
I have a Button, and upon pressing it, the onClick() would process user's request. However, this takes a little time, so I would like to have a View showing "Please wait, processing..." immediately upon pressing this Button, while its OnClickListener does its thing.
My problem is, this "Please wait, processing..." which I placed at the very beginning of onClick(), only appears AFTER the whole onClick() is done. In other words, after the whole processing is done. So, I was wondering, how do I make a View saying "Please wait, processing..." before the actual processing has begun?
As #Blundell pointed you may process long-running operation on a separate thread to avoid freezing of UI thread. However in Android there's a better alternative for general-purpose Handler which is called AsyncTask. Please refer to this tutorial for details.
You can do this by just using AsyncTask without dealing anything else.
First create new AsyncTask class on "onPreExecute" change ui to show
that you are processing sth
Second do your all backend time consuming job on "doInBackground"
method (do not call any ui updating method from here)
Third change your ui to show that process is finished or whatever you
wanna do.
yourUiButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
new NewTask().execute();
}
});
class NewTask extends AsyncTask<String, Void, Task>{
#Override
protected void onPreExecute() {
super.onPreExecute();
//this part runs on ui thread
//show your "wait while processing" view
}
#Override
protected Task doInBackground(String... arg0) {
//do your processing job here
//this part is not running on ui thread
return task;
}
#Override
protected void onPostExecute(Task result) {
super.onPostExecute(result);
//this part runs on ui thread
//run after your long process finished
//do whatever you want here like updating ui components
}}
Do the processing on another thread so that the UI can show your dialog.
// Show dialog
// Start a new thread , either like this or with an ASyncTask
new Thread(){
public void run(){
// Do your thang
// inform the UI thread you've finished
handler.sendEmptyMessage();
}
}
When the processing is done you will need to callback to the UI thread to dismiss oyur dialog.
Handler handler = new Handler(){
public void handleMessage(int what){
// dismiss your dialog
}
};
AsyncTasks.
Place the displaying of the progress dialog in onPreExecute
Do your thing in doInBackground
Update whatever needs to be updated in the UI, and close the dialog in onPostExecute
You will need something like this
public void onClick(View v){
//show message "Please wait, processing..."
Thread temp = new Thread(){
#Override
public void run(){
//Do everything you need
}
};
temp.start();
}
or if you want it to run in the UIThread (since it is an intensive task, I don't recommend this)
public void onClick(View v){
//show message "Please wait, processing..."
Runnable action = new Runnable(){
#Override
public void run(){
//Do everything you need
}
};
v.post(action);
}
put ur code inside a thread and use a progress dialogue there...
void fn_longprocess() {
m_ProgressDialog = ProgressDialog.show(this, " Please wait", "..", true);
fn_thread = new Runnable() {
#Override
public void run() {
try {
// do your long process here
runOnUiThread(UI_Thread);//call your ui thread here
}catch (Exception e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(null, thread1
"thread1");
thread.start();
}
then close your dialogue in the UI thread...hope it helps..
I'm trying to create a ProgressDialog for an Android-App (just a simple one showing the user that stuff is happening, no buttons or anything) but I can't get it right. I've been through forums and tutorials as well as the Sample-Code that comes with the SDK, but to no avail.
This is what I got:
btnSubmit.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
(...)
ProgressDialog pd = new ProgressDialog(MyApp.this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("Working...");
pd.setIndeterminate(true);
pd.setCancelable(false);
// now fetch the results
(...long time calculations here...)
// remove progress dialog
pd.dismiss();
I've also tried adding pd.show(); and messed around with the parameter in new ProgressDialog resulting in nothing at all (except errors that the chosen parameter won't work), meaning: the ProgressDialog won't ever show up. The app just keeps running as if I never added the dialog.
I don't know if I'm creating the dialog at the right place, I moved it around a bit but that, too, didnt't help. Maybe I'm in the wrong context? The above code is inside private ViewGroup _createInputForm() in MyApp.
Any hint is appreciated,
you have to call pd.show before the long calculation starts and then the calculation has to run in a separate thread. A soon as this thread is finished, you have to call pd.dismiss() to close the prgoress dialog.
here you can see an example:
the progressdialog is created and displayed and a thread is called to run a heavy calculation:
#Override
public void onClick(View v) {
pd = ProgressDialog.show(lexs, "Search", "Searching...", true, false);
Search search = new Search( ... );
SearchThread searchThread = new SearchThread(search);
searchThread.start();
}
and here the thread:
private class SearchThread extends Thread {
private Search search;
public SearchThread(Search search) {
this.search = search;
}
#Override
public void run() {
search.search();
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
displaySearchResults(search);
pd.dismiss();
}
};
}
I am giving you a solution for it,
try this...
First define the Progress Dialog in the Activity before onCreate() method
private ProgressDialog progressDialog;
Now in the onCreate method you might have the Any button click on which you will change the Activity on any action. Just set the Progress Bar there.
progressDialog = ProgressDialog.show(FoodDriveModule.this, "", "Loading...");
Now use thread to handle the Progress Bar to Display and hide
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 progress dialog
progressDialog.dismiss();
}
}.start();
That is all!
Progress Dialog doesn't show because you have to use a separated thread. The best practices in Android is to use AsyncTask ( highly recommended ).
See also this answer.
This is also possible by using AsyncTask. This class creates a thread for you. You should subclass it and fill in the doInBackground(...) method.