Android : How to show custom dialog from thread - android

I stack with this, I'm trying to create application using TabLayout. I have 3 tabs (3 different activities). I also got service which reads my gps position - that works fine. I got thread which post to the web server user position - that works to.
Now I'm trying to create thread which ask web server if there are any messages for user. If there are - thread try to show custom dialog (2 text views and gallery - it works if i start action from activity by clicking button), and there problem starts I know i can't update UI form threads different from main thread but i don't know how to work around this. I tried to use AsyncTask - failed - i don't want to assign AsyncTask to specific Activity as inner private class.
I wish I could show my custom dialog regardless of the tab on which user is currently using.
Thread works fine, but how to show that dialog.
I read about runOnUIThread but don't know how to use it.
Any ideas, any similar examples ??

Using runOnUiThread is easy.
YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
YourActivity.this.showDialog(CUSTOM_DIALOG_ID);
}
}

You need to use a Handler. http://developer.android.com/reference/android/os/Handler.html

Related

About AsyncTask updating UI thread with dialog

I'm developing an Android app that has a basic structure: activity that requests some action from AsyncTask implementer. The implementer has 3 custom methods that should be able to update UI thread with a Dialog and a postExecute() that should update UI thread with a failuer Dialog if an exception is thrown. Here are some questions:
Where should I create the Dialog object? In the activity class or the AsyncTask implementer? What general guidelines should I follow?
Can I update UI thread with a Dialog without waiting for postExecute()?
How can I update UI thread with a picture? Should I create a custom Dialog or is there an easier way?
If the updates - as dialogs with pictures - come one after another, in a sequence how should I deal with it? Should I create some kind of queue? How would you do it?
Thank you in advance :)
1)There's a couple of different ways you can do this. But personally I usually create the dialog in onPreExecute of the AsyncTask, so that the UI for the task is completely self contained.
2)Yes. You can do it in onProgressUpdate. doInBackground should call publishProgress() which will cause onProgressUpdate to be called on the UI thread.
3)Too few details- where do you want the picture? In an existing image view? On top of the current layout? If you just want to display it in a dialog box, an AlertDialog with custom layout would probably work.
4)Depends on the app. Do you want the user to see all the images, or is it ok to miss images in the middle if a new one is sent?

My app's UI hanged

I am writing an android app, in which I have 1 button and 1 progress bar as UI elements.
The main aim of this app is when user presses this button, it has to create a database which contains all phone book contacts in customized format, means I am reading Contacts database and manipulating for my requirement.
So I am using SQLiteOpenHelper for database operations. I written a method downloadPhonebook() to perform all required operations. I written app such that when user presses button I am making progress bar visible and calling this method.
In this case, UI was hanged after clicking button and showing a dialog with Force Close and Wait buttons, after 15 seconds.
To avoid this I tried following mechanisms.
-> Broadcast Button click message and call method downloadPhonebook(). Here no use, same problem occurred.
-> Used a Thread and AsyncTask to call this method, here I got Runtime exceptions like Couldn't create Handler inside a Thread, Looper.prepare not called. I tried calling Looper.prepare() and Looper.loop() even exceptions occurred.
-> I tried with Android Service and Broadcast intent, again same problem UI hanged.
If anybody faced this problem or knows the solution or knows how to use Looper.prepare and Looper.loop please reply me. Thanks.
the workflow should be something like this: create a handler in your main class, add a handler in your sql helper class, pass the handler from the main class to the sql helper class when you create it. Run the download on separate thread from your main class, when download is ready, call yourHandler.sendEmptyMessage(0). You should override the Handler.handleMessage (I'm not sure about the exact name of the method) in your main class. You can also send messages to update the progress, read about Andoid Handler for more information

Is using runOnUiThread inside AsyncTask inefficient and bad?

I know it sounds crazy that someone is using runOnUiThread inside AsyncTask. Somehow, it is working for me but I wanna know if it is an acceptable and robust approach or not. Here is the scenario:
I have an app in which after successful login, user is rendered to next screen. In this new screen, 3 different methods are loading different types of data from a web server. These methods are:
getMembersForList() : It loads the list of community members and shows it in a listview.
getProfileData() : It loads the profile of logged in user and shows his name , image etc on the screen.
getNotificationCounts : It loads the count of new notifications for the user.
I applied 3 different approaches for it :
(1) Calling all 3 methods simply in onCreate i.e. no exclusive thread is being used for any of the methods . In this case , the transition from login screen to this screen becomes very slow and black screen shows up for some time before this activity shows up.
(2) Calling getMembersForList() on UI thread and the other 2 methods on exclusive threads. In this case transition becomes fast and list shows up quickly but Notification counts and username etc. don't show up because WrongThreadException occurs saying that this thread can't touch other thread's views (TextViews for username, notification count etc. which are declared globally) . The same thing happens when I start these threads from an AsyncTask as well.
(3) Calling getMembersForList() on UI thread and then starting an AsyncTask in which the other 2 methods are being called in "runOnUiThread" inside doInBackground() method. This solves both the above issues. Now the screen transition is faster and the WrongThread exception is also not occuring.
So far the approach-(3) is working good for me but I am not sure if this is the right way to do it because runOnUiThread and AsyncTask are 2 completely opposite things. Can anyone please clear my doubts about this scenario. Thanx in advance.
Yes, use-cases like this are a big reason why the runOnUiThread() method exists in the first place. The idea is you allow your background thread(s)/AsyncTask instance(s) to run your lengthy operations in the background, and then provide a simple hook that they can use to update the interface when they have the result (or at arbitrary intervals, as different pieces of the result become available).
As long as that's what you're doing, then your usage is fine. What you want to avoid doing is performing a lengthy operation on the main thread, either directly or indirectly by passing in some lengthy operation from a background thread.
Of course you don't have to do it that way if you don't want to. You could use postExecute() instead. Or you could store the result somewhere and then use any sort of message-passing API to notify the main thread that the result is ready, and so on.
I would advice to run all the 3 calls in the asyncTask, and update the UI in the postExecute() of the AsyncTask after the background taks is complete, postExecute runs on UIthread so you need not call anything explicit to run them on UIthread.

Display loading screen using AsyncTask with ListActivity

I've got an app that uses ListActivity to give users a list of actions. When they click one I use an Intent to launch a separate activity.
My problem is that the actions that the app performs take about 20 seconds to finish, and since I don't want the user to receive that nasty ANR dialog, I tried to use AsyncTask to present them with a loading screen in the mean time. I tried using setContentView(R.layout.loading); on onPreExecute(), but it throws a NullPointerException which as far as I have figured out is due to the fact that loading.xml is not "a ListView whose ID is android.R.id.list".
So what can I do now? How can I show that loading screen? Is there a way around this pretty annoying situation? Any help would be greatly appreciated. Thanks!
I am not sure exactly what your use case is; you have a list of items that are populated immediately, and upon selecting one an action is taken? The action that is taken is to launch another Activity which performs background processing?
Or does it take that long to populate the list of actions?
If the former, you can use an AsyncTask for the long-running activity instead of an Intent to launch another Activity: in the callback you get for the click on the item in question, you would create the AsyncTask, and in doInBackground you would perform the long-running activity, with onPostExecute refreshing or manipulating your list as necessary.
Another thing to consider is using a dialog box to show a loading screen, if the loading is required to happen before you launch a new Activity.
If you can further describe your use case, I can help you more.
It's not the loading screen you need to have on the AsyncTask, it's that 20-second Activity initialization. I would look for a way to do all the setup in a background thread in a Service while the user is free to merrily bop around in other Activities. I'd try hard to find a way not to just stall the user for 20 seconds. Maybe take them to the target Activity and show them data cached from their last visit until the new set is ready.
Fire up and display your loading dialogs in your onCreate() of the Activity being called, then call Dialog.dismiss() in your AsyncTask's onPostExecute().

Opening WebView in background

This is the first time I ask something, so if there is something wrong just tell me and I´ll try to fix it ASAP.
We have a customer that wants us to login in their servers with a native Android app, but without giving us a custom way to do this. They want us to use the current website they have to log and, after authentication takes place, retrieve within the browser a XML which contains the data we need. After that, use the data in the native app. All of this with the user not knowing/seeing that a browser is being used. A total mess IMHO.
Of course, I have never tried this approach in the past and my first tests make me feel like this is impossible (or extremely difficult) to achieve. Whenever I try to load the URL in a hidden WebView the default browser pops up showing the website.
My main question is, is it possible to load a webview and work with it (invoke javascript, etc...) in the background?
Thank you.
You could set the WebView to hidden by default with the attribute android:visibility="gone", interact with it at runtime then when you need to show it to the user after you've loaded data, just call setVisibility(View.VISIBLE)
Hope this helps!
Ofc, you must to use a Thread :
protected void getPage(){
Thread th = new Thread(){
public void run(){
//Download and make things
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
//print int the activity
}
});
}
};
th.start();
Remember, and thats is VERY important, you CANT draw from thread to the main activity. The only who can draw in the screen is the main activity. You can draw with 2 methods:
One , with the method _mActivity.runOnUiThread(new Runnable() {_ like the example i put.
Two, use a Handler to send messages from thread to main activity with the information that you want to draw.
*Main activity is the activity that its in the screen in that moment, not the first activity of the app

Categories

Resources