I wanted to show a ProgressDialog when data need to be uploaded to the server.
I have checked this question Best way to show a loading/progress indicator?
the best answer was
ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.show();
// To dismiss the dialog
progress.dismiss();
when i tried to implement this in my code, nothing showed at all !!
what is that i am doing wrong here?!
this is my code
private void UpdateData()
{
ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.show();
try
{
UpdateWSTask updateWSTask = new UpdateWSTask();
String Resp = updateWSTask.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
progress.dismiss();
}
The proper way of showing a ProgressDialog with a AsyncTask would be by displaying the dialog on the onPreExecute() method of the AsyncTask and hide it at onPostExecute() method of it:
private class SampleTask extends AsyncTask<Void, Integer, String> {
ProgressDialog progress = new ProgressDialog(YourActivity.this);
protected Long doInBackground(Void... urls) {
// execute the background task
}
protected void onPreExecute(){
// show the dialog
progress.setTitle("Loading");
progress.setMessage("Wait while loading...");
progress.setIndeterminate(true);
progress.show();
}
protected void onPostExecute(String result) {
progress.hide();
}
}
Both: onPreExecute() and onPostExecute() run on the main thread, while doInBackground() as the name suggests is executed on the background thread.
Edit:
Within your activity, where you want to call the AsyncTask you just need to execute it:
UpdateWSTask updateWSTask = new UpdateWSTask();
updateWSTask.execute();
A better idea would be to do this with AsyncTask class. You can take care of UI work in preExecute and postExecute methods and do your main work in doInBackground method. Nice and clean!
It seems that you already doing this. Move the dialog code to the asynctask class. You just need a reference to the context and you can provide it with a constructor for your custom asynctask class
Related
I have made a image downloading thread to download image from desire web address. On that thread I have used a progress dialog , but the progress dialog is not turning after 3 or 4 second, it seems that, it is hanged. But the background work is ok. My problem is , what the progress dialog is not turning ? what it is looking like hang?
I am using this code at the start position.
imageUploadhandler.postDelayed(runImageUpload, 500);
dialog = ProgressDialog.show(AllProductActivityPictGrid.this, "",
"Message...", true);
dialog.setCancelable(true);
Your dialog hangs, because if you instantiated your Handler in an Activity, then everything you post to the Handler will run on the UI thread, not on a background Thread.
Do your downloading and create the ProgressDialog in an AsyncTask.
Maybe you should take a look at AsyncTask ?
protected void onPreExecute() {
progressDialog=ProgressDialog.show(context,"Please Wait..","Retrieving data from device",false);
}
#Override
protected String doInBackground(String... params) {
//background stuff here
return "";
}
protected void onPostExecute(String result) {
progressDialog.dismiss();
Toast.makeText(context, "Finished", Toast.LENGTH_LONG).show();
}
Try to use dialog.dismiss() after you your download is completed.
Please use following code to call Progress Dialog.
ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Please Wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
After completion of your task call progressDialog.dismiss();
Now I am doing an Android application.In my application I have to get the data from json page.This operation is taking time delay.So I have to show a progressbar until the fetching process is completed.I used the following code to show progressbar.
public void onCreate(Bundle savedInstanceState) {
//somecode
ProgressDialog progressBar = new ProgressDialog(this);
progressBar.setCancelable(true);
progressBar.setMessage("Loading");
progressBar.show();
Thread thread = new Thread(this);
thread.start();
}
public void run() {
flag=GetFixtureDetailsJsonFunction();
handler.sendEmptyMessage(0);
}
protected boolean GetFixtureDetailsJsonFunction() {
//json parsing code
return true
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (flag==true) {
progressBar.dismiss();
}
}
};
Using this code I am getting exception.android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
AsyncTask is best way for getting response from xml or database. try like this,
private class DownloadQuestion extends AsyncTask<String, Void, String>
{
#Override
protected void onPreExecute()
{
pd = ProgressDialog.show(Activity_SplashScreen.this, "","Please wait...", true,false);
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls)
{
//Write background code here Code
return "";
}
#Override
protected void onPostExecute(String response1)
{
//Some Code.....
if (pd != null && pd.isShowing())
pd.dismiss();
}
}
Instead i would suggest you to implement AsyncTask, which is known as Painless Threading in android.
Using this AsyncTask, you don't need to bother about managing Threads. And its easy!!
FYI, do as follows:
Display ProgressBar in onPreExecute() method.
Do long running tasks inside the doInBackground() method.
Dismiss the ProgressBar inside the onPostExecute() method. You can also do display kinds of operation in this method.
This is a bit strange way to implement this functionality. Instead of fixing that code I suggest you using AsyncTask, which was implemented right for that purpose. See here.
You are trying to access the UI View from another thread which is not eligible.In this case this is your handler.
Instead of trying to access UI thread like this you should use an AsyncTask and do your progressDialog logic in it.
Start showing the progress bar onPreExecute
doInBackground() jobs while progressBar showing
And finallly dismiss your progressBar after your doInBackground() is complete onPostExecute()
I want to show ProgressDialog while uithread sleeps so that until the data from the server is retrived my activity will not be shown. How can I do this?
You can use Thread, AsyncTask, or Service to load your data in the background, and with a Handler implementation control your ProgressDialog.
The example in this post shows how to use a thread for a login request, and in the meantime show the progress dialog.
Using AsyncTask is a lot easier and clearer:
private static final int WAIT = 11;
private final class MyTask extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
// Show up the dialog with id=WAIT [11]
showDialog(WAIT);
// other actions that must be performed in the UI thread
// before the background works starts
}
#Override
protected Void doInBackground(Void... params)
{
// perform the background work
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Remove the dialog with id=WAIT [11]
removeDialog(WAIT);
// other actions that must be performed in the UI thread
// after the background works finished
}
}
[...]
final MyTask task = new MyTask();
task.execute(null);
Since AsyncTask is a generic type, you can specify the parameter types for your preference, so it is very handy for transferring data from the ui thread to a background thread and back.
Your dialog part is just a few lines inside your activity:
private ProgressDialog dialog;
#Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case WAIT:
{
dialog = new ProgressDialog(this);
dialog.setMessage("Loading...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
return dialog;
}
}
return null;
}
This task is commonly solved with AsyncTask bounded with progress dialog. See this article.
Move your Network Process code into a Thread and get a ProgressDialog. Start your network process by calling .start(); and then ProgressDialog.show(); when you have done in network process, stop the ProgressDialog through a Handler from Thread.run().
you can try this code for progress dialoge in ur thread
ProgressDialoge pd = ProgressDialog.show(this, "Please wait...", "Retrieving data.", true,false);
I am using a simple progressDialog that running ok but the the wheel dose not progress:
//Progress Dialog
final ProgressDialog dialog = ProgressDialog.show(TravelPharm.this, "Searching","Please wait ...", true);
((ProgressDialog) dialog)
.setProgressStyle(ProgressDialog.BUTTON_NEUTRAL);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
dialog.dismiss();
}
};
Thread checkUpdate = new Thread() {
public void run() {
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
what i am missing??
Create your progress dialog like so:
final ProgressDialog progress = new ProgressDialog(context);
add some text/icon to it:
progress.setTitle("Loading");
progress.setMessage("Loading, please wait");
progress.setIcon(R.drawable.icon);
Show it:
progress.show();
I think you should pass ProgressDialog.STYLE_SPINNER to ProgressDialog.setProgressStyle() method.
final ProgressDialog dialog = ProgressDialog.show(TravelPharm.this, "Searching","Please wait ...", true);
The way you are creating the ProgressDialog is correct - if the spinner isn't spinning then something is blocking your UI thread.
Out of interest, why are you using TravelPharm.this for the context instead of this? I'm not sure it's the cause of your problem, I'm just wondering why.
I am guessing that you are launching a time intensive task from a dialog and then trapping the thread exit in your handler where you are trying to dismiss the dialog. If possible, consider simply sending an empty message when the dialog is done. Then in the handler create a new AsyncTask as:
private class MyAsynch extends AsyncTask<String, Void, String>{
protected void onPreExecute() {
resetProgress();
progress.show();
}
#Override
protected String doInBackground(String...strings) { // <== DO NOT TOUCH THE UI VIEW HERE
// TODO Auto-generated method stub
doNonUIStuff();
return someString; // <== return value String result is sent to onPostExecute
}
protected void onPostExecute(String result){
progress.dismiss();
doSomethingWithString(result); // you could launch results dialog here
}
};
protected void onPause() {
super.onPause();
if (asynch != null) {asynch.cancel(true);}
if (progress != null){progress.cancel();}
}
private void resetProgress() { // avoid frozen progress dialog on soft kill
if (progress != null && progress.isShowing()){
progress.cancel();
}
progress= new ProgressDialog(this);
progress.setIndeterminate(true);
progress.setMessage("I am thinking.");
}
You could return any type in onPostExecute, in this example I am returning a string. Another approach would be to launch a second Activity as a "dialog" using startActivityForResult create the AsycnTask in onActivityResult.
In other words, gather the data in a dialog or second Activity, then in the first activity show a progress dialog in onPreExecute, do the time intensive task in the background, and cancel the progress dialog in onPostExecute.
I have seen the frozen spinning ball, thus the call to resetProgress().
I want to show the progress bar during web service call. I called progress bar before calling the service, but it is being called after the service call is finished and i have received the response.
ProgressDialog dialog = ProgressDialog.show(LogIn.this,"","Loading. Please wait...", true);
status=Loginvalid(method,username,psword); //calling the method for making service call
But, progress dialog is starting after the response is received from the service.
Please how can i fix this problem..
public class Progress extends AsyncTask<String, Void, Void> {
protected void onPreExecute() {
ProgressDialog dialog = new MyProgressDialog(MyActivity.this, "Loading.. Wait..");
dialog.show();
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
// do your network connection
return null;
}
protected void onPostExecute(Void unused) {
dialog.dismiss();
}
}
Use AsyncTask. It is the most effective and painless way of showing a progress dialog during a web service call.
show the progressbar on preexecute, call your webservice in doInBackground method, and dismiss the progressbar onPostexecute.
http://developer.android.com/reference/android/os/AsyncTask.html
In order to properly show the progress dialog it must be executed on UIThread, while all the other work(service call) - in another. See the example here.