Android: Loading Dialog for Activity - android

I'm trying to implement the code from showing dialog while loading layout by setContentView in background and http://developer.android.com/guide/appendix/faq/commontasks.html#threading to show a loading dialog while my activity is loading, but having difficulty.
I have class variables defined for the UI elements in my view, and also strings for the data which is loaded on another thread from the database:
private TextView mLblName, mLblDescription, etc...
private String mData_RecipeName, mData_Description...
I also have the handlers defined:
private ProgressDialog dialog;
final Handler mHandler = new Handler();
final Runnable mShowRecipe = new Runnable() {
public void run() {
//setContentView(R.layout.recipe_view);
setTitle(mData_RecipeName);
mLblName.setText(mData_RecipeName);
mLblDescription.setText(mData_Description);
...
}
};
In onCreate, I'm trying too show the dialog, then spawn the loading thread:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dialog = ProgressDialog.show(this, "", "Loading. Please wait...", true);
setContentView(R.layout.recipe_view);
showData();
}
protected void showData() {
// Fire off a thread to do some work that we shouldn't do directly in the UI thread
Thread t = new Thread() {
public void run() {
mDatabaseAdapter = new ChickenPingDatabase(ShowRecipe.this);
mDatabaseAdapter.open();
mTabHost = getTabHost();
mLblName = (TextView)findViewById(R.id.lblName);
mLblDescription = (TextView)findViewById(R.id.lblDescription);
...
Cursor c = mDatabaseAdapter.getRecipeById(mRecipeId);
if(c != null){
mData_RecipeName= c.getString(c.getColumnIndex(Recipes.NAME));
mData_Description= c.getString(c.getColumnIndex(Recipes.DESCRIPTION));
...
c.close();
}
String[] categories = mDatabaseAdapter.getRecipeCategories(mRecipeId);
mData_CategoriesDesc = Utils.implode(categories, ",");
mHandler.post(mShowRecipe);
}
};
t.start();
}
This loads the data, but the progress dialog isn't shown. I've tried shuffling the call to spawn the separate thread and show the dialog around, but can't get the dialog to show. It seems this is a fairly common request, and this post seemed to be the only answered example of it.
EDIT: For reference, a blog post demonstrating the way I eventually got this working.

Since what you want is pretty much straight-forward, I would recommend that you use an AsyncTask. You can control the showing/hiding of the dialog in onPreExecute() and onPostExecute(). Check out the link, there's a good example in there.

Related

How to display a loading screen while doing heavy computing in Android?

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.

Waiting until user actually sees something on the screen

I've got a main Activity, an extra class for my fragment, and inside this fragment is an AsyncTask, which gathers data from various android library (Wifi SSID, BSSID, etc). When I start my app the app shows a blank screen, without any UI. Then after about 2 seconds, the whole data is being shown. I actually want to display my TextViews as "Not connected to a wifi network" in the background, while showing a ProgressDialog until the data is being displayed. I've got the ProgressDialog in my MainActivity, and calling it in my AsyncTask onProgressUpdate
MainActivity.progressDialog = ProgressDialog.show(MainActivity.c,
"ProgressDialog Title",
"ProgressDialog Body");
I'm updating my TextViews in the doInBackground methode (via another methode outside the Fragment)
((Activity) getActivity()).runOnUiThread(new Runnable() {
Would be too big a comment so i'll just put it here.
Sounds like you are using both fragment and AsyncTask in an incorrect way. You should never do anything UI relevant in doInBackground.
Here is an example of what you could do.
I assume the following scenario:
You have a main activity
You have a fragment containing TextViews
You wish to populate the TextViews after loading some data using AsyncTask with a progressDialog
The approach would be to:
Add the fragment in onCreate of your activity (if the fragment is not defined in the layout, then it will automatically be added).
Create the AsyncTask in your fragment like this:
private class LoadData extends AsyncTask<Void, Void, List<String>> {
ProgressDialog progressDialog;
//declare other objects as per your need
#Override
protected void onPreExecute()
{
// getActivity() is available in fragments and returns the activity to which it is attached
progressDialog= new ProgressDialog(getActivity());
progressDialog.setTitle("ProgressDialog Title");
progressDialog.setMessage("ProgressDialog Body");
progressDialog.setIndeterminate(true)
progressDialog.setCancelable(false)
progressDialog.show();
//do initialization of required objects objects here
};
#Override
protected Void doInBackground(Void... params)
{
List<String> results = new ArrayList<String>();
//do loading operation here
//add each of the texts you want to show in results
return results;
}
// onPostExecute runs on UI thread
#Override
protected void onPostExecute(List<String> results )
{
progressDialog.dismiss();
// iterate results and add the text to your TextViews
super.onPostExecute(result);
};
}
Start the AsyncTask in onCreate of your fragment:
#Override
public void onCreate(Bundle savedInstanceState) {
new LoadData().execute();
super.onCreate(savedInstanceState);
}
This way you avoid calling directly back to your activity, which really should not be necessary in your scenario (unless I have misunderstood).
Otherwise please post all the relevant code and layouts.
This line:
I'm updating my TextViews in the doInBackground methode
points to your problem. You need to use the AsyncTask method onProgressUpdate() to publish to the UI thread. You do not call onProgressUpdate() directly, instead you call publishProgress().
Interestingly, I answered a similar question yesterday here: android AsyncTask in foreach
and it includes an example.
Here's what you need to do.
(1) From the place you run the code that gathers data, you should first display the progress dialog. Something like this:
busy = new ProgressDialog (this);
busy.setMessage (getString (R.string.busy));
busy.setIndeterminate (true);
busy.setCancelable (false);
busy.show();
(2) Then you start your data gathering. This must be done in a separate thread (or Runnable). Do something like this:
Thread thread = new Thread ()
{
#Override
public void run()
{
try
{
... gather data ...
Message msg = handler.obtainMessage();
msg.what = LOADING_COMPLETE;
msg.obj = null;
handler.sendMessage (msg);
}
catch (Exception e)
{
Message msg = handler.obtainMessage();
msg.what = LOADING_FAILED;
msg.obj = e.getMessage(); // maybe pass this along to show to the user
handler.sendMessage (msg);
}
// get rid of the progress dialog
busy.dismiss();
busy = null;
}
}
(3) Add a handler to the activity to receive notification when data gathering is complete:
Handler handler = new Handler()
{
#Override
public void handleMessage (Message msg)
{
if (msg.what == LOADING_COMPLETE)
loadingComplete ();
else if (msg.what == LOADING_FAILED)
loadingFailed ((String)msg.obj);
}
};
(4) Implement the handlers:
private void loadingComplete ()
{
...
}
private void loadingFailed (String errorMessage)
{
...
}
That's the essentials.

Show Loading Dialog When Making A HTTP Request in Android

In an effort to learn Android I am writing a small app. The first thing I am trying to do is login via a remote API.
I would like to show a "loading" dialog when the call is being made (in case he user in using mobile internet). Researching this has shown two possible methods.
One is to use a ProgressDialog and a private class that extends Thread, the other is using a private class that extends AsyncTask.
Which is best/more appropriate for this task?
I have tried using the ProgressDialog version but am struggling. I have put the function making the http request in the extended Thread run() method, but am unsure on how to pass the response data (JSON) back into my activity.
Any and all help gratefully received.
The best way possible is to use an AsyncTask with a ProgressDialog. You should extend AsyncTask and implement all the methods you need:
onPreExecute() - here you initialize your ProgressDialog and show() it
doInBackground() - here you do your work
onPostExecute() - here you call dismiss() on ProgressDialog to hide it
(optional) onProgressUpdate() - here you can change the progress of your ProgressDialog if it's determinate
There is a get() method in AsyncTask class that lets you retrieve the result of the work. Also you can implement an interface between the AsyncTask and calling Activity to return the result. Hope this helps.
Efforts come with rewards :) Egor is right, AsyncTask is the best way to do it. But
You have to know that Activity is working on the UI thread and threads not. So the only way to share things is via handler. Here an example:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = (ProgressBar) findViewById(R.id.progressBar1);
handler= new Handler();
}
public void startProgress(View view) {
// Do something long
Runnable runnable = new Runnable() {
#Override
public void run() {
for (int i = 0; i <= 10; i++) {
final int value = i;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
progress.setProgress(value);
}
});
}
}
};
new Thread(runnable).start();
}

Progress Dialog

-->I am new to Android And i want to show two progress dialog one after another??
-->First i want to show when my image is load from internet, when this process is done i have set A button on that Remote image.
-->When i click that button i want Dialog for second time..(on clicking button i have set video streaming code.. before video is start i want to close that Dialog..)
Any Help????
Thanks...
You can create 2 threads. First for image when it is loaded then call another thread of video.
Make two runnable actions and two handlers to handle that
public void onCreate(Bundle savedInstanceState) {
ProgressDialog pd = ProgressDialog.show(this, "","Please Wait", true, false);
Thread th = new Thread(setImage);
th.start();
}
public Runnable setImage = new Runnable() {
public void run() {
//your code
handler.sendEmptyMessage(0);
}
};
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (pd != null)
pd.dismiss();
}
};
On Android it's best to use AsyncTask to execute tasks in the background while still updating UI:
Extend the AsyncTask
Start the progress dialog in onPreExecute()
Define the background task in doInBackground(Params...)
Define updating of the progress dialog in onProgressUpdate(Progress...)
Update dialog by calling publishProgress() from doInBackground()
Start a new Dialog #2 in onPostExecute().

Android: ProgressDialog doesn't show

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.

Categories

Resources