How do I show and then remove an android progress dialog - android

I can get a progress bar to appear with the following code
pd = ProgressDialog.show(myActivity.this, "", "Loading. Please wait...", true);
straight forward, but once I have the code execute I want it to go away, but when I run the dismiss method after I never see the dialog box show at all.
Heres the code in context which is wrapped in oncreate
pd = ProgressDialog.show(myActivity.this, "", "Loading. Please wait...", true);
runCode();
setListAdapter(new CustomAdapter(myActivity.this));
pd.dismiss();
I thought you can show/dismiss progress dialog's anywhere in the activity but I must be wrong.

here is the code that I got to work
private class UpdateFeedTask extends AsyncTask<MyActivity, Void, Void> {
private ProgressDialog mDialog;
protected void onPreExecute() {
Log.d(TAG, " pre execute async");
mDialog = ProgressDialog.show(MyActivity.this,"Please wait...", "Retrieving data ...", true);
}
protected void onProgressUpdate(Void... progress) {
Log.d(TAG, " progress async");
}
#Override
protected Void doInBackground(MyActivity... params) {
// TODO Auto-generated method stub
return null;
}
protected void onPostExecute(Void result) {
Log.d(TAG, " post execute async");
mDialog.dismiss();
}
}

refer the sample code sinnpet of mine,hope this may help you
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.ProgressBar;
public class PlayActivity extends Activity {
/** Called when the activity is first created. */
private ProgressBar mProgress;
private int mProgressStatus = 0;
private int count=0;
private Handler mHandler=new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mProgress = (ProgressBar) findViewById(R.id.ProgressBar01);
new Thread(myThread).start();
}
private Runnable myThread = new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while (mProgressStatus<=100){
try{
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(1000);
}
catch(Throwable t){
}
}
}
Handler myHandle = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
mProgressStatus=mProgressStatus+10;
count=mProgressStatus;
Log.d("mProgressStatus",Integer.toString(count));
mProgress.setProgress(mProgressStatus);
if(count > 80)
{
Log.d("mProgressStatus",Integer.toString(mProgressStatus));
counter.start();
}
}
};
};
}

To remove a progressBar
ProgressBar progressbar = (ProgressBar)findViewById(R.id.progressbarID);
progressBar.setVisibility(View.INVISIBLE) ;
hide the progressbar in xml and show it like
ProgressBar progressbar = (ProgressBar)findViewById(R.id.progressbarID);
progressBar.setVisibility(View.VISIBLE) ;

Related

What is the process to include a progress Bar before an activity launches

Am trying to include a progessbar in my app before launching my activity.
If any one knows the perfect implementaion let me know.Am tried but not getting the desired solution.
Because of this issue m not able to work further.Plz i need help.
I know the Process how to include the progress Dialog but i want to include ProgessBar.What i really need to do.
M sharing my code that i hv tried:
package com.example.demo1;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
private static final int PROGRESS = 0x1;
private ProgressBar mProgress;
private int mProgressStatus = 0;
private Handler mHandler = new Handler();
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
mProgress = (ProgressBar) findViewById(R.id.progress_bar);
// Start lengthy operation in a background thread
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
mProgressStatus = doWork();
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
}
private int doWork() {
// TODO Auto-generated method stub
return 0;
}
}).start();
}
}
https://dzone.com/articles/android-example-progress-bar see if this helps... They have shown buffering progress bar example also...I dont know which one you need but this can help you chose any of them as per requirements...
You can include splash activity like this:->
public class SplashActivity extends AppCompatActivity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
context = this;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
finish();
}
}, 1000);
}
}

Cannot run the async example ..?

When i tried to run the code, only main toast is running. Progress Dialog and other toast message is not running.This program is simple async example for sleeping process.The main issue is that it is not showing the Progressdialog.
Did i need to add xml file(it contain only a textView and a Button).
Please help me to solve this.Thank You
package com.example.asyncexample;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
public class MainActivity extends Activity {
ProgressDialog progressBar;
int prorgessInc = 1; // incrementing the progress dialog
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.start_button);
button.setOnClickListener(startTaskListener);
}
private OnClickListener startTaskListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Context context = getApplicationContext();
progressBar = new ProgressDialog(v.getContext());
BackgroundTask test = new BackgroundTask();
test.execute(context);
CharSequence text = "Main Thread is Running";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
};
private class BackgroundTask extends AsyncTask<Context, Integer, String>{
protected void OnPreExecute() {
CharSequence msg = "BackgroundTask is Operating";
progressBar.setCancelable(true);
progressBar.setMessage(msg);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
}
#Override
protected String doInBackground(Context... params) {
//BackgroundTask Is Running
for(int i =0; i<=100; i+=prorgessInc){
try {Thread.sleep(100);}
catch (InterruptedException e) { e.printStackTrace();}
publishProgress(prorgessInc);
if(isCancelled()) break;
}
return getString(R.string.backgndcompld);
}
protected void OnProgressUpdate(Integer...values ) {
//Update Progress bar
progressBar.incrementProgressBy(prorgessInc);
}
protected void PostExecute(String result){
//Dissmiss progressbar
progressBar.dismiss();
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast2 = Toast.makeText(context, result, duration);
toast2.show();
}
}
}
Right, your problem is in your method naming for the AsyncTask.
You have defined:
protected void OnPreExecute()
protected void OnProgressUpdate()
protected void PostExecute()
However the real methods are:
protected void onPreExecute()
protected void onProgressUpdate()
protected void onPostExecute()
Note the difference in case. If you had used the #Override as below your IDE would likely have shown you that.
I have done some cleaning of that and other parts of your code. Take a look:
public class MainActivity
extends Activity
implements View.OnClickListener
{
private Button button;
private ProgressDialog progressBar;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_example);
button = (Button) findViewById(R.id.start_button);
button.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
Log.d("click", "start button clicked, starting task");
BackgroundTask test = new BackgroundTask();
test.execute();
}
private class BackgroundTask
extends AsyncTask<Void, Integer, String>
{
int PROGRESS_INCREMENT = 1;
int PROGRESS_MAX = 100;
String DIALOG_MSG = "AsyncTask is Operating";
#Override
protected void onPreExecute()
{
progressBar = new ProgressDialog(getApplicationContext());
progressBar.setCancelable(true);
progressBar.setMessage(DIALOG_MSG);
progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressBar.setProgress(0);
progressBar.setMax(PROGRESS_MAX);
progressBar.show();
}
#Override
protected String doInBackground(Void... params)
{
for (int i = 0; i <= 100; i += PROGRESS_INCREMENT)
{
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
publishProgress(PROGRESS_INCREMENT);
if (this.isCancelled())
{
break;
}
}
return "[some result text]";
}
#Override
protected void onProgressUpdate(Integer... values)
{
progressBar.incrementProgressBy(PROGRESS_INCREMENT);
}
#Override
protected void onPostExecute(String result)
{
progressBar.dismiss();
Toast.makeText(getApplicationContext(),
result,
Toast.LENGTH_LONG)
.show();
}
}
}
Notable changes:
Activity implements View.OnClickListener so you can move your onClick() method to your Activity eliminating the anonymous inner class.
Button moved to a class level scope. Defining it in your listener could be error prone.
prepare and display your PrgressDialog from the onPreExecute() method. That's what it's for.
Cleaned up your Toast. No need to use all those variables and waste space with useless objects.
Instead of Toast messages use the built in Log for debug messages. Toast messages can very quickly begin to spam your screen and because of the display lengths are very inaccurate for knowing when things happen.

Android Progress Bar not working for me

Progress bar is not working for me. I am try to show some details in Progress. But I can't, What I did wrongly? Please help me.
Activity Filename - MainActivity.java
package com.example.sqliteexample;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
public class MainActivity extends Activity {
private Handler handler = new Handler();
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//dialog = ProgressDialog.show(this,getString(R.string.loading) ,getString(R.string.alignMsg));
dialog = ProgressDialog.show(this,"Loading", "Loading the Image of the Day");
Thread th = new Thread()
{
public void run() {
handler.post(
new Runnable (){
#Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
dialog.dismiss();
}});
}};
th.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Try it using handler.postDelayed :
dialog = ProgressDialog.show(this,
"Loading", "Loading the Image of the Day");
handler.postDelayed(runnable,10000);
}
Runnable runnable = new Runnable() {
#Override
public void run() {
/* dismiss dialog here*/
dialog.dismiss();
handler.removeCallbacks(runnable);
}
};
or you will need to move Thread.sleep(10000); inside Thread run method instead of inside Runnable which you are passing to Handler.post method as:
Thread th = new Thread()
{
public void run() {
/** call Thread.Sleep here... **/
Thread.sleep(10000);
handler.post(
....your code here....
The handler is defined in main activity and thus it will run on UI thread. You ask to sleep for 10 seconds and this won't work on the UI thread.
If you want to show the progress bar and dismiss it after 10 seconds then use handler.postDelayed(Runnable r, long delayMillis).
This is the code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// dialog = ProgressDialog.show(this,getString(R.string.loading) ,getString(R.string.alignMsg));
dialog = ProgressDialog.show(this, "Loading", "Loading the Image of the Day");
handler.postDelayed(new Runnable()
{
#Override
public void run()
{
dialog.dismiss();
}
}, 10000);
}
Hope it was helpful.

displaying progressbar using threading

I am trying to display a progress bar using threading .. I accept that I do not have that much concept of threading.
Here is the code
public class Progress extends Activity {
static String[] display;
private static final int Progress = 0;
private ProgressBar mProgress;
private int mProgressStatus = 0;
private Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.progress);
mProgress = (ProgressBar) findViewById(R.id.progressBar);
// Start lengthy operation in a background thread
new Thread(new Runnable() {
public void run() {
while (mProgressStatus < 100) {
mProgressStatus = doWork();
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
}
private int doWork() {
display = new Logic().finaldata();
// TODO Auto-generated method stub
return 100;
}
}).start();
}
}
On running, the logcat message is
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
What is the mistake that I am doing here?
So your problem will be elsewhere. I tried your example with Handler and it works for me.
package com.sajmon.threadsDemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ThreadsDemoActivity extends Activity {
ProgressBar bar;
TextView label;
Handler handler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bar = (ProgressBar) findViewById(R.id.progBar);
new Thread(new Runnable() {
int i = 0;
int progressStatus = 0;
public void run() {
while (progressStatus < 100) {
progressStatus += doWork();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
handler.post(new Runnable() {
public void run() {
bar.setProgress(progressStatus);
i++;
}
});
}
}
private int doWork() {
return i * 3;
}
}).start();
}
}
And XML:
<ProgressBar
android:id="#+id/progBar" style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
So look at this and edit your code similar with this.
Find the below example code for progress bar update using threads
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ThreadDemo1ProgressBar extends Activity
{
ProgressBar bar;
TextView msgWorking;
boolean isRunning = false;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
bar.incrementProgressBy(5);
if (bar.getProgress() == bar.getMax()) {
msgWorking.setText("Done");
bar.setVisibility(View.INVISIBLE);
} else {
msgWorking.setText("Working..." +
bar.getProgress());
}
}// handleMessage
};
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
bar = (ProgressBar) findViewById(R.id.progress);
bar.setMax(100);
msgWorking = (TextView) findViewById(R.id.TextView01);
}
public void onStart() {
super.onStart();
bar.setProgress(0);
Thread background = new Thread(new Runnable() {
public void run() {
try
{
for (int i = 0; i < 20 && isRunning; i++) {
Thread.sleep(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch(Throwable t) {
// just end the background thread
}
}
});
isRunning = true;
background.start();
}// onStart
public void onStop() {
super.onStop();
isRunning = false;
}
}// ThreadDemo1ProgressBar
The about example updating the progress bar for every 5 seconds.
I actually just create a thread instance once and it works anyway. This code was written in the Startup Activity. All you need to do is call showSpinner1() method to show/hide the spinner.
Ensure to do this
getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS); in your onCreate() method and use this code for toggling the spinner ON and OFF.
// Spinner related code - The thread is created just once and is used multiple times (works!!)
boolean toShow = false;
Thread spinner1Thread = new Thread("Show/Hide Spinner Thread") {
#Override
public void run() {
setProgressBarIndeterminateVisibility(toShow);
}
};
/**
* Shows and hides the spinner
* #param pShow
*/
public void showSpinner1(boolean pShow) {
toShow = pShow;
runOnUiThread(spinner1Thread);
}

show progressbar on button click when going from 1 intent to other and data is coming from server

I have a button in one page and when I click on that button I
am able to go another activity through Intent(), but onbuttonclick()
in which activity I am going in that activity data in spinner
coming from server means on button click
I load that data on spinner from server.so it takes times for moving my button click activity
to other activity so I want to show progress bar when my button is clicked
and untill data is not coming from server...how to achieve this..and I want to show progress bar
on buttonclick page means on my first activity when I click the button.
My code of of on button click is given below.
cuurentloc.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Intent i = new Intent(MainMenu.this, currentlocmap.class);
startActivity(i);
}
});
Actually I know asynchronous task but using this I will be able to show progress bar on 2nd activity, I want to show it on my first activity until data is not loaded in second activity, so I want progree bar above the button on first activity, and when data is loaded on second activity it moves to second.
You need to use AsyncTask as the way I am guiding here.
Create Async Task in first activity. On button click event call that AsyncTask. In background do loading data from server. and onPostExecute start second activity
cuurentloc.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
new ProgressTask(MyClassName.class).execute(null);
}
});
Async Task
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
List<Message> titles;
private ListActivity activity;
//private List<Message> messages;
public ProgressTask(ListActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
Intent i = new Intent(MainMenu.this, currentlocmap.class);
startActivity(i);
}
protected Boolean doInBackground(final String... args) {
try{
//load data from server
} catch (Exception e){
Log.e("tag", "error", e);
return false;
}
}
}
}
Thanks
Deepak
have a look at this code
package com.exercise.AndroidBackgroundThread;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidBackgroundThread extends Activity {
Thread backgroundThread;
TextView myText;
boolean myTextOn = true;
boolean running = false;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
//super.handleMessage(msg);
if (myTextOn){
myTextOn = false;
myText.setVisibility(View.GONE);
}
else{
myTextOn = true;
myText.setVisibility(View.VISIBLE);
}
}
};
void setRunning(boolean b){
running = b;
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myText = (TextView)findViewById(R.id.mytext);
Toast.makeText(this, "onCreate()", Toast.LENGTH_LONG).show();
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(this, "onStart()", Toast.LENGTH_LONG).show();
backgroundThread = new Thread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
while(running){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendMessage(handler.obtainMessage());
}
}
});
setRunning(true);
backgroundThread.start();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
boolean retry = true;
setRunning(false);
while(retry){
try {
backgroundThread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Toast.makeText(this, "onStop()", Toast.LENGTH_LONG).show();
}
}
and for more detail look at this guide http://tech-aamir.blogspot.in/2012/06/how-to-make-progress-bar-when.html
Best of luck
aamirkhan i.
To build on the first answer, since you are familiar with AsyncTask. You can have the AsyncTask perform the work to retrieve whatever data you'll need in your first activity. And during that process, you display your progress bar. Once the AsyncTask completes, you remove the progress bar, put your data in a bundle (by calling putExtras), and send it off with your intent to start the 2nd Activity.
You can use the ProgressBar or ProgressDialog in the currentlocmap class.
Use AsyncTask class for that and when the data is fetched, set the layout using setContentView() and dismiss the ProgressDialog.
Refer to these links:
Fetch data from server and refresh UI when data is fetched?
How to start and finish progressBar dynamically in android

Categories

Resources