Can I use progress bar in android, without the thread?
HERE IS CODE OF MY CURRENT WAY OF IMPLEMENTING PROGRESS DIALOG
// Adding Progress bar
String[][] data; //Global variable
//called on onCreate() or onItemSelected
final ProgressDialog myProgressDialog;
myProgressDialog = ProgressDialog.show(ListingPage.this,"Please Wait", "Loading Date", true);
new Thread() {
public void run() {
try{
setSelected();
sleep(5000);
} catch (Exception e) { }
myProgressDialog.dismiss();
}
}.start();
populateList(Split.splitToTwoDimArray(data)); // populates the list view
HOPE ABOVE HELPS, IF USING THREAD THE LIST IS NOT BEING POPULATED.
Sure, you can always set the progress manually via
progressBar.setProgress(int progress);
Above question/added code is a bit confusing cause you asked how to use the progress bar without a thread but now in your code you're using a thread. I thought that you initially wanted to avoid.
Anyway, maybe you should use an AsyncTask instead of the Thread, which allows you to modify anything in the main UI thread.
https://sites.google.com/site/androidhowto/how-to-1/create-a-custom-progress-bar-using-asynctask
http://developer.android.com/reference/android/os/AsyncTask.html
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've found that a lot of people are having a similar problem but I am simply trying to show a dialog while I am grabbing some data off a URL and then dismiss properly after the data is retrieved. Here is what I'm trying to do (This is in my onClick() method for a refresh button):
dialog.show();
// do some work
dialog.dismiss();
Doing it this way you never really see the dialog at all. I've tried doing it using an extra thread such as:
Thread t = new Thread() {
public void run() {
dialog.show();
}
};
But this way I get an error and a force close down...
What is the best method to do this?
For the task you are trying to implement:
dialog.show();
// do some work
dialog.dismiss();
Now, to implement above, there is concept of AsyncTask, the best way to implement Threading task, as its also known as Painless Threading in Android.
AsyncTask has 4 main methods:
onPreExecute() - Here you can show ProgressDialog or ProgressBar.
doInBackground() - Here you can do/implement background task
onProgressUpdate() - Here you can update UI based on the intermediate result you receive from webservice call or from background task
onPostExecute() - Here you can dismiss dialog or make progress bar invisible. Also you can do the task which want to do after receiving result from background task or webservice call.
For this kind of task mostly I recommend you to use the AsyncTask. Here is one good example of it which will help you.
And for this question as You are making UI related task and for that please use the UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
//Show or Hide your ProgressDialog
}
});
Try to use runOnUiThread of the Activity instead of using Thread.
Check the following code snippet.
runOnUiThread(new Runnable() {
public void run() {
dialog = new ProgressDialog(ctContext);
dialog.show();
}
}
});
I think this will help you.
Sorry, the title is a bit hard to understand but I'm not 100% sure as to what to ask. its easier to show you the code and see if you understand from that. I found the way to use the progress dialog from another post on here, so this is basically adding onto that post. ( ProgressDialog not showing until after function finishes )
btw, this is using eclipse environment with the android plugin.
final MyClass mc = new MyClass(text,info, this);
final ProgressDialog dialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
Thread t = new Thread(new Runnable()
{
public void run()
{
// keep sure that this operations
// are thread-safe!
Looper.prepare(); //I had to include this to prevent force close error
mc.doStuff();//does ALOT of stuff and takes about 30 seconds to complete... which is why i want it in a seperate thread
runOnUiThread(new Runnable()
{
#Override
public void run() {
if(dialog.isShowing())
dialog.dismiss();
}
});
}
});
t.start();
tmp = mc.getStuff();
now the issue is that tmp is always null because mc isnt finished doing stuff. So, if i do this it finishes doing stuff, but doesnt show the progress dialog..
t.start();
while(t.isAlive());//noop
tmp = mc.getStuff();
Any thoughts or ideas would be greatly appreciated!
In your second attempt, you are making the main thread wait for the new thread to complete.
The runnable in the runOnUiThread call is where you want to do tmp = mc.getStuff();
That will then be executed on the main thread after mc has finished doStuff().
But otherwise, check out the link blindstuff commented, it simplifies threading.
I'm using a thread so that I can show a progress dialog while my app loads some data. If there is an error it will stop the progress dialog and show the popup saying "error". However I found out that alert dialogs cannot run inside a UI thread and that I need to use a Handler. Can someone with help with this issue? Here is my code. Thanks
verifyCode.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final ProgressDialog progressDialog = ProgressDialog.show(
Activate.this, "", "Loading...");
new Thread(new Runnable() {
public void run() {
try {
new AlertDialog.Builder(Activate.this)
.setTitle(getResources().getString(R.string.InvalidKey))
.setMessage(getResources().getString(
R.string.PleaseEntervalidRegistration)).setNeutralButton(
"OK", null).show();
progressDialog.dismiss();
//more code
}).start();
}
You can't make changes to UI element on non-UI threads. onClick will run on the UI thread, but since you spawn a Thread inside onClick then non-UI elements cannot be manipulated from inside that Thread. Move your AlertDialog and ProgressDialog calls to just prior to spawning the new Thread.
Also, as #lightblade suggested, If you need to do some sort of action which requires heavy background processing and UI manipulation based on that processing, then you should use AsyncTasks. It provides methods you can override for pre-processing, actual processing, post-processing, and updating progress.
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.