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);
Related
I use asynctask quite often however this time it doesn't work!
I have a UI contains a viewpager and fragments. To populate the view, it takes about 3 secs. Now I want to show the ProgressDialog until it finishes by using AsyncTask. But the ProgressDialog is not showing!!!!
Anybody can tell me the solution? Thanks
onCreate(...){
setContentView(...)
new LoadUI(MyActivity.this).execute();
}
public class LoadUI extends AsyncTask<Void, Void, Void>{
ProgressDialog pd;
Context context;
public LoadUI(Context mContext) {
this.context = mContext;
pd = new ProgressDialog(mContext);
aViewPager = (ViewPager) findViewById(R.id.aPagerDay);
}
#Override
protected void onPreExecute() {
pd.show();
}
#Override
protected Void doInBackground(Void... params) {
//Create ViewPager
//Create pagerAdapter
return null;
}
#Override
protected void onPostExecute(Void result) {
if (pd.isShowing()) {
pd.dismiss();
}
super.onPostExecute(result);
}
}
You can try out two options:
Either use the AsyncTask's method get(long timeout, TimeUnit unit) like that:
task.get(1000, TimeUnit.MILLISECONDS);
This will make your main thread wait for the result of the AsyncTask at most 1000 milliseconds.
Alternatively you can show a progress dialog in the async task until it finishes. See this thread. Basically a progress dialog is shown while the async task runs and is hidden when it finishes.
You have even third option:" if Thread is sufficient for your needs you can just use its join method. However, if the task is taking a long while you will still need to show a progress dialog, otherwise you will get an exception because of the main thread being inactive for too long.
The problem is the GUI is not ready in onCreate(). And nothing will be shown if I try to show Dialog in this state. A solution is move the dialog to activity onStart():
#override
onStart(){
new LoadUI(MyActivity.this).execute();
}
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 have developed an android application .In that application getting information from web and displayed in the screen.At the time of getting information i want to load a progress dialog to the screen after getting the information i want dismiss the dialog
Please any one help me how to do this with some sample code
Thanks in advance
You need to implement an AsyncTask.
Example:
class YourAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
//show your dialog here
progressDialog = ProgressDialog.show(this, "title", "message", true, false)
}
#Override
protected Void doInBackground(Void... params) {
//make your request here - it will run in a different thread
return null;
}
#Override
protected void onPostExecute(Void result) {
//hide your dialog here
progressDialog.dismiss();
}
}
Then you just have to call
new YourAsyncTask().execute();
You can read more about AsyncTask here: http://developer.android.com/reference/android/os/AsyncTask.html
The point is, you should use two different thread 1st is UI thread, 2nd is "loading data thread"
from the 2nd thread you are to post the process state to the 1st thread, for example: still working or 50% is done
use this to post data
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.