How to show Dialog in onCreate method? - android

How to show Dialog in onCreate method ? Is that possible at all, I tried but I got leaked window exception. Can anyone suggest me anything ?

you can use ProgressDialog Class with the Help of Handler Class. This way you can achieve what you want to do.
progDailog = ProgressDialog.show(loginAct,"Process ", "please wait....",true,true);
new Thread ( new Runnable()
{
public void run()
{
// your loading code goes here
}
}).start();
Handler progressHandler = new Handler()
{
public void handleMessage(Message msg1)
{
progDailog.dismiss();
}
}

I am sure that you might be using a bad context there. To show the Dialog on the UI(specific) Activity don't use getApplicationContext() or getBaseContext(). Just create the instance using Activity_Name.this and you will be able to show the Dialog.

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.

Show a ProgressDialog from a Thread inside a Service

I have a service that I have started from MainActivity with:
Intent intent = new Intent(getBaseContext(), MyService.class);
getBaseContext().startService(intent);
Inside MyService, I create and start a thread, giving it a reference to the Service's Context:
mThread = new MyThread(this);
mThread.start();
Then inside the thread, I want to display a ProgressDialog. I tried this:
mProgressDialog = ProgressDialog.show(mContext,
"", "Receiving file...", true);
mProgressDialog.show();
but I get "RuntimeException: Can't create handler inside thread that has not called Looper.prepare()". This makes sense, so I tried this instead:
HandlerThread progressHandlerThread = new HandlerThread(
"ProgressHandlerThread");
progressHandlerThread.start();
Handler progressHandler = new Handler(
progressHandlerThread.getLooper());
progressHandler.post(new Runnable()
{
#Override
public void run()
{
mProgressDialog = ProgressDialog.show(mContext, "",
"Receiving file...", true);
mProgressDialog.show();
}
});
but I get "BadTokenException: Unable to add window token is not for an application" but I don't understand what that error means.
I have seen this: Show ProgressDialog from thread inside the Service
and the conclusion seems to be that I need to runOnUIThread, but I don't have a reference to an Activity to do that since I am in a Service. Can anyone explain this BadTokenException and suggest a good way to do this?
I think the fact that you're trying to directly manipulate UI from a Service means that You're Doing It Wrong™
Services don't have a UI, and therefore should never directly influence UI. Instead, you should pipe an event from your Service to a listening Activity or Fragment, for instance.
Take a look a https://github.com/square/otto for some extremely flexible and saucy event bussing.
edit) Take a look at the comments below for what the dirty solution was to David's problem.
Not much idea about badTokenException , but I can suggest you to use AsyncTask to solve this kind of problem. You can start the progressdialog in preExecute() method and dismiss it in postExecute() method because these both are running on UI thread.
I just implemented this from a thread here. Please read Rachit Mishra's answer further down the page talking about a ProgressBar:
Communication between Activity and Service
I have this in my service:
public void sendMessage(int state) {
Message message = Message.obtain();
switch (state) {
case 1://SHOW:
message.arg1 = 1;
break;
case 0:
message.arg1 = 0;
break;
}
try {
messageHandler.send(message);
} catch (RemoteException e) {
e.printStackTrace();
}
}
Call sendMessage() with 1 or 0 to show or dismiss the ProgressDialog within your service.
And this is in my Main Activity:
private ProgressDialog progress;
public class MessageHandler extends Handler {
#Override
public void handleMessage(Message message) {
int state = message.arg1;
switch (state) {
case 0://HIDE
progress.dismiss();
break;
case 1://SHOW
progress = ProgressDialog.show(MainActivity.this, (getResources().getString(R.string.CONNECTING) + "..."), (getResources().getString(R.string.PLEASE_WAIT) + "!")); //show a progress dialog
break;
}
}
}
The ProgressDialog cannot be shown from the service, it must be called from the activity or fragment. I hope I added all the code you need and that it works well for your needs. To be honest I'm not sure how the message handler works but it works for me! The naming is probably not the best either lol. Sorry.

android - progress bar is not dismissed properly

In OnResume(), I make web service call in thread here i used progress bar for indicating the process it works fine but suppose i uses the app after sometime i put the device idle after that open the app once again this time progress bar is not dismissed.It's not regularly happens sometimes it happens. Why?
How can i make it to away from this? If you need more info plz let me know.
Code :
Edit:
public void onResume()
{
super.onResume();
pdMessages = ProgressDialog.show(getParent(), "", "Please wait...", true);
Thread thImportbtn = new Thread()
{
public void run()
{
try
{
//Get internal messages
strInternalInboxWSR = GetInternalInboxMessages();
} catch (SoapFault e) {
e.printStackTrace();
}
dh_Messages_Handler.post(checked_internalinbox_response);
handler.sendMessage(handler.obtainMessage());
}
};
thImportbtn.start();
}
private Handler handler = new Handler()
{
#Override
public void handleMessage ( Message message )
{
pdMessages.dismiss();
}
};
You can use Handler Class to dismiss your ProgressDialog, like below
private Handler handler = new Handler()
{
#Override
public void handleMessage ( Message message )
{
progressDialog.dismiss();
}
};
you can use following statement to call Handler class,
handler.sendMessage(handler.obtainMessage());
You are Trying To Dismiss ProgressDialog in Non-UI Thread, So can't Dismiss proper.
you should put your dismiss code( pdMessages.dismiss();) in Handler Using Overriding handleMessage method
Use AsyncTask is better.

Cannot get ProgressDialog to display in Thread

Well I've seen a wide variety of failures while trying to get this to work. I have a thread that is started via an Activity. The thread needs to create/display progress dialogs and dismiss them.
When I tried to directly display the ProgressDialog I got an error that my Looper wasn't prepared. I looked up with a Looper was an implemented it. However, I had to call Looper.loop for the progress dialog to show up. After it showed up the application froze on that point never to continue past the Looper.loop call.
I couldn't get it to work so looked for a whole new way using a HandlerThread and a Handler. I create a HandlerThread and start it. I get the looper from the thread and create a Handler with it. My ProgressDialog or Toasts won't show up at all.
Is there an easier way to go about doing this?
U can have an
private Handler stopProgressHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
setProgressBarIndeterminateVisibility(false);
}
};
private Handler startProgressHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
setProgressBarIndeterminateVisibility(true);
}
};
so that when u start the thread start the progressbar and after thread is completed u can stop the progressbar.
public void closeProgressbar(){
//bluetoothconnector.onDestroy();
stopProgressHandler.sendEmptyMessage(0);
}
public void openProgressbar(){
//bluetoothconnector.onDestroy();
startProgressHandler.sendEmptyMessage(0);
}
This will help to call the progressbar to start and stop.. This will be one of the solution..
Not sure about ProgressDialog, but all UI related stuff in Android, as far as I know, required to be updated in UI Thread. There's actually an easy helper class for implementing async task: http://developer.android.com/reference/android/os/AsyncTask.html
Alternatively, you can create a Handler (which would be on UI Thread) and create the dialog using that:
Handler uiHandler;
//Activity onCreate
onCreate(...){
uiHandler = new Handler();
}
// Somewhere in your other thread,
uiHandler.postRunnable(new Runnable(){
#Override
public void run(){
// Create or update dialog
...
}
});
The last answer is wrong....
it should be:
setProgressBarIndeterminateVisibility(Boolean.TRUE | Boolean.FALSE);

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