Android - Create Progress Dialog - java

I am new to android development. I want to develop a dialog with a progressbar in my application. When i click the search button the dialog should appear with the progressbar, showing that the progress is going on before switching to another activity. Please suggest me with sample code.

Use a ProgressDialog. You should do the work on a new thread, though, and use a handler to call back to the activity when finished. Here's how I do it:
private ProgressDialog pd;
private View.OnClickListener searchClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
pd = ProgressDialog.show(MyActivity.this, "Searching...", "Searching for matches", true, false);
new Thread(new Runnable() {
public void run() {
//do work
//.....
finishedHandler.sendEmptyMessage();
}
}).start();
}
}
private Handler finishedHandler = new Handler() {
#Override public void handleMessage(Message msg) {
pd.dismiss();
//start new activity
}
}

Related

Android dialog dismiss after certain computation

I'm encountering the following problem:
I created a waiting spinner using Dialog like this
final Dialog progDialog = new Dialog(context);
progDialog.setContentView(R.layout.progress_dialog);
progDialog.setTitle("Calculating...");
progDialog.setCancelable(false);
progDialog.setCanceledOnTouchOutside(false);
WindowManager.LayoutParams lp = progDialog.getWindow().getAttributes();
lp.dimAmount = 0.7f;
progDialog.show();
Afterwards, I'm calculating something in the background
for()...
for()...
After the calculation is finished, I want to dismiss my dialog with
progDialog.dismiss();
However, this results in my dialog never being shown at all. When I remove the last line, the dialog is shown but is never dismissed. Is there a fix to it?
You better try with AsyncTask
private class YourAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progDialog;
public YourAsyncTask(MyMainActivity activity) {
progDialog = new ProgressDialog(activity);
}
#Override
protected void onPreExecute() {
progDialog.setContentView(R.layout.progress_dialog);
progDialog.setTitle("Calculating...");
progDialog.setCancelable(false);
progDialog.setCanceledOnTouchOutside(false);
progDialog.show();
}
#Override
protected Void doInBackground(Void... args) {
// do background work here
return null;
}
#Override
protected void onPostExecute(Void result) {
// do UI work here
if (progDialog.isShowing()) {
progDialog.dismiss();
}
}
}
Use the above code in your Main Activity. And, do your calculation part in doInBackground.
To set timer for your computation try below code:
Runnable progressRunnable = new Runnable() {
#Override
public void run() {
progDialog.cancel();
}
};
Handler pdCanceller = new Handler();
pdCanceller.postDelayed(progressRunnable, 3000);
Adding show/hide:
progDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
theLayout.setVisibility(View.GONE);
}
});
Update:
ProgressDialog class was deprecated as of API 26

New activity after 100% in ProgressDialog

I've got this code:
#Override
public void onClick(View v) {
progressDoalog = new ProgressDialog(Hack.this);
progressDoalog.setMax(100);
progressDoalog.setMessage("Its loading....");
progressDoalog.setTitle("ProgressDialog bar example");
progressDoalog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDoalog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
while (progressDoalog.getProgress() <= progressDoalog
.getMax()) {
Thread.sleep(200);
handle.sendMessage(handle.obtainMessage());
if (progressDoalog.getProgress() == progressDoalog
.getMax()) {
progressDoalog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
Handler handle = new Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
progressDoalog.incrementProgressBy(1);
}
};
});
}
}
Where can I add a code to open new activity when the ProgressDialog will be at 100%? Which and where exactly? Thanks for your help!
You can't start an Activity from a Dialog, but what you can do is start the Activity from the old one using a OnDismissListener.
Take a look at the documemtation :
https://developer.android.com/reference/android/content/DialogInterface.OnDismissListener.html
I haven't noticed but you can check the progress in your Handler, check if it's 100%, dismiss the dialog and start the new Activity, remember that you gotta do this on the UI thread

Issues In Splash Screen with progressDialog

My Issue is progress Dialog not display with the splash Screen?Can Any one solve this, Any help could be appreciated thanks in advance !
public class Splash extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_layout);
Thread thread = new Thread(){
#Override
public void run() {
try
{
sleep(3*1000);
ProgressDialog progressDialog = new ProgressDialog(Splash.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("wait");
progressDialog.setCancelable(false);
progressDialog.show();
}catch (Exception e)
{
e.printStackTrace();
}finally {
Intent i = new Intent(Splash.this,MainActivity.class);
startActivity(i);
finish();
}
}
};thread.start();
}
}
public class Splash extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_layout);
ProgressDialog progressDialog = new ProgressDialog(Splash.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("wait");
progressDialog.setCancelable(false);
progressDialog.show();
Thread thread = new Thread(){
#Override
public void run() {
try
{
sleep(3*1000);
}catch (Exception e)
{
e.printStackTrace();
}finally {
progressDialog.dismiss();
Intent i = new Intent(Splash.this,MainActivity.class);
startActivity(i);
finish();
}
}
};thread.start();
}
}
Cuz you are updating the UI in background thread..
try to use the
runOnUiThread(new Runnable.......)
or try to put the UI work on UI thread.
Everthing you write inside a thread will be executed in background. you can't manipulate any UI elements from a background Thread. you should be getting an error from this code, check your stacktrace. I suggest you remove the code for the ProgressDialog from the Thread and put it before the Thread.
You should show the progress dialog from UI thread. Or you can use runOnUiThread(...) method. If you have to show it from a different thread write thin inside run method of thread:
Handler mainHandler = new Handler(Looper.getMainLooper());
mainHandler.post(new Runnable() {
#Override
public void run() {
//add try catch
sleep(3*1000);
ProgressDialog progressDialog = new ProgressDialog(Splash.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("wait");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
I would suggest using handlers instead of sleep in your activity. You can also try this without the thread in your code:
Handler h = new Handler(Looper.getMainLooper())
h.postDelayed( new Runnable() {
#Override
public void run() {
ProgressDialog progressDialog = new ProgressDialog(Splash.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("wait");
progressDialog.setCancelable(false);
progressDialog.show();
}
},
(3*1000));

Android Splash Screen AsyncTask

Basically I have a loading splash screen which will be executed when button was clicked:
public void onClick(View v) {
// Load the loading splash screen
Intent loadingIntent = new Intent(context, LoadingScreen.class);
context.startActivity(loadingIntent);
}
});
And in the LoadingScreen class:
public class LoadingScreen extends Activity{
//A ProgressDialog object
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Initialize a LoadViewTask object and call the execute() method
new LoadViewTask().execute();
}
//To use the AsyncTask, it must be subclassed
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
//Before running code in separate thread
#Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(LoadingScreen.this,"Getting routes...",
"Loading data, please wait...", false, false);
}
//The code to be executed in a background thread.
#Override
protected Void doInBackground(Void... params)
{
try
{
//Get the current thread's token
synchronized (this)
{
//Initialize an integer (that will act as a counter) to zero
int counter = 0;
//While the counter is smaller than four
while(counter <= 4)
{
//Wait 850 milliseconds
this.wait(750);
//Increment the counter
counter++;
//Set the current progress.
//This value is going to be passed to the onProgressUpdate() method.
publishProgress(counter*25);
}
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return null;
}
//Update the progress
#Override
protected void onProgressUpdate(Integer... values)
{
//set the current progress of the progress dialog
progressDialog.setProgress(values[0]);
}
//after executing the code in the thread
#Override
protected void onPostExecute(Void result)
{
finish();
//close the progress dialog
progressDialog.dismiss();
}
}
}
With these codes, the loading splash screen did came out. But I wonder is there any other way to show only the pop out dialogue for loading progress bar which on top on my previous screen?
Let's say my previous screen was event details. Then when user selected the button, only the dialogue box with loading progress bar will be shown instead of a new intent with a dialogue box.
Any ideas? Thanks in advance.
EDIT
public void onClick(View v) {
// Load the loading splash screen
new LoadViewTask().execute();
ENeighbourhoodActivity.tvDirection.setText("");
eventModel.setEventX(String.valueOf(eventModel.getEventX()));
eventModel.setEventY(String.valueOf(eventModel.getEventY()));
new GetEventDirectionAsyncTask(new GetEventDirectionAsyncTask.OnRoutineFinished() {
public void onFinish() {
//Hide the callout and plot user location marker
ENeighbourhoodActivity.callout.hide();
EventController.getUserLocation(context);
getActivity().finish();
}
}).execute(eventModel);
}
});
public class GetRegisteredEventAsyncTask extends
AsyncTask<String, Integer, Double> {
static EventController eventCtrl = new EventController();
public static ArrayList<Event> upcomingModel = new ArrayList<Event>();
public static ArrayList<Event> pastModel = new ArrayList<Event>();
public interface OnRoutineFinished { // interface
void onFinish();
}
private OnRoutineFinished mCallbacks;
public GetRegisteredEventAsyncTask(OnRoutineFinished callback) {
mCallbacks = callback;
}
public GetRegisteredEventAsyncTask() {
} // empty constructor to maintain compatibility
#Override
protected Double doInBackground(String... params) {
try {
upcomingModel = eventCtrl.getRegisteredUpcomingEvent(params[0]);
pastModel = eventCtrl.getRegisteredPastEvent(params[0]);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Double result) {
if (mCallbacks != null)
mCallbacks.onFinish(); // call interface on finish
}
protected void onProgressUpdate(Integer... progress) {
}
}
In your onClick() method you could write something like:
new LoadViewTask().execute();
and the progress dialog will be shown in that page itself.
what are you doing man, just call your AsyncTask not the intent
public void onClick(View v)
{
new LoadViewTask().execute();
}
});
do your intent in postExecute
#Override
protected void onPostExecute(Void result)
{
finish();
//close the progress dialog
progressDialog.dismiss();
//START YOUR ACTIVITY HERE
Intent loadingIntent = new Intent(context, LoadingScreen.class);
context.startActivity(loadingIntent);
}
Must read the documentation of AsynTask

I want Android progress dialog to stay on screen until function on new activity is complete but doesn't work

In my Android app, one form has a button which upon click opens up another; the new form performs activities which can take a while. I want the first form to remain open and for the progress dialog to keep spinning while these activities finish.
I've attempted this below, but it just won't work. The progress dialog just finishes and opens up the next window (before described activities on new form have finished)
In the below code SecondForm -
The subroutine "Calculations", is what takes a while to complete
Code:
MainActivity:
final ProgressDialog ringProgressDialog = new ProgressDialog(
MainActivity.this);
ringProgressDialog.setTitle("Loading");
ringProgressDialog.show();
ringProgressDialog.setCancelable(false);
new Thread(new Runnable() {
#Override
public void run() {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(
getApplicationContext(),
SecondForm.class);
startActivity(intent);
}
});
} catch (Exception e) {
}
ringProgressDialog.dismiss();
}
}).start();
SecondForm:
public class CategoryTabs extends Fragment {
static Context mContext;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
gotstatdata = false;
rootView = inflater.inflate(R.layout.fragment_abc, container, false);
mContext = rootView.getContext();
new Thread(new Runnable() {
#Override
public void run() {
try {
((Activity) mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
gotstatdata = false;
Calculations(128);
gotstatdata = true;
}
});
} catch (Exception e) {
}
}
}).start();
You are dismissing your dialog as soon as it runs with ringProgressDialog.dismiss();.
That line should be removed and you should do something like send out a broadcast when you are finished to close the progress dialog.
It looks like you might also just want a background thread rather than a second Activity because no user interaction is required.
Looking at AsyncTask would be the easiest way for you to start with background threads and it's 'onPostExecute` method will allow you to dismiss your dialog.
Edit
The basic structure you want is to add the following
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
//TODO: show your dialog from here
}
#Override
protected Void doInBackground(Void... params) {
//TODO: call Calculations(128); from here
//Calculations(128); should live within this async task instead of a new activity
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//TODO: call dismiss on your dialog from here
}
}.execute();
instead of the new Thread(new Runnable() { block you currently have

Categories

Resources