I have a little problem I spend a lot of time now. I hope you can help me.
Well, I have an activity witch loads content out of data base in background. It returns asynchrony and modifies my data model. Now I'm looking for a good way to inform the controller to update view. I use the notifyDataChanged method but I got an exception.
Android do not allow to modify a view from another thread. In my opinion this is a basic functionality. So there has to be a way to implement such a functionality.
Can you give me an hint.
I also watch the content observer class. But I don't think that the right one.
Thanks
Please provide some code snippets from your Activity. If you are using AsynkTask which is the best way to do background processing on data, you should use the onPostExecute() method to update your UI, because doInBackground() runs on a background thread, not on the UIThread.
A workaround would be to declare a Handler in your Activity and post a new Runnable in that Handler when you want to acccess the UI, something like this:
mHandler.post(new Runnable() {
#Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
But this is somehow a "hack" and I wouldn't recommend using this. The best way would be to use the AsyncTask.
Related
How do I use a thread to run some code continuously whilst an Apps running, using the information it gives to periodically update the UI of the App.
Specifically the thread would run some code that searches through a text file in order to find co-ordinates which would then be plotted over a PNG on the UI. This would update automatically say every second maybe every half second, and would clear the image then redraw the points.
How do i first of all set up the thread then second of all send information from the thread back to the UI and have it update?
Any example code would be great or any information you've come across that gives example code. I'm not trying to do it the best way at the moment, just trying to hack it together, so if you know easy and quick (but awful) ways of doing this don't feel afraid to share.
This may help u...
//on create
Thread currentThread = new Thread(this);
currentThread.start();
after on create
public void run() {
try {
Thread.sleep(4000);
threadHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
//don't forget to deal with the Exception !!!!!
}
}
private Handler threadHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
Intent in = new Intent(getApplicationContext(),****.class);
startActivity(in);
}
};
This is a very common scenario and its far boyend the scope of a simple answer to your question.
Here are two usefull links:
http://developer.android.com/guide/components/processes-and-threads.html
http://www.vogella.com/articles/AndroidBackgroundProcessing/article.html
And there are a lot more.
Here are two different approaches for you as starting point:
Update gui from your thread, only needs syncronzation with the UI thread. Pass your Activity into your thread, it provides the method: runOnUiThread
Define an interface to provide callbacks, let the calling ui class (activity) implement your interface and register it as listener to your thread. Then you can call the callback, when ever you want. Don't for to syncronize
Try to use service(or IntentService - http://developer.android.com/guide/components/services.html) for background work and BroadcastReceiver to update the UI thread from the service.
Use the AsyncTask class (instead of Runnable). It has a method called onProgressUpdate which can affect the UI (it's invoked in the UI thread).
Its for the first time I'm making a fairly large app and there are lots of sections in it.
I want to keep UI and background processes in different classes to avoid confusion. However, how do i communicate among them in best possible way. I've come across few approaches till now:
Declaring background thread in different class and defined its onPostExecute() method in UI thread.
new SetupDefaultFeeds(context) {
#Override
protected void onPostExecute(List<Feed> result) {
default_feeds = result;
for (Feed t : result) {
String log = t.toString();
Log.d("DEFAULT feed", log);
}
menu_btn[0].performClick();
}
}.execute();
Signalling using a flag variable between background and UI thread.
Thread and handler.
Are there any other ways and what is the best possible way. Thanks !
Passing messages through a Handler is usually the most "Android-ish" way to do this. Trying to do all communication through flag variables is most likely going to be quite a headache.
Edit: Android itself doesn't provide a way for you to link the two classes together, you need to do that by hand. One way which works quite well is to create an interface for your communication and have either the UI class or background thread implement it. Then, when creating the class, you can pass a reference to the other object and communicate through the interface.
However, if you want to completely decouple the two classes, you might want to use a BroadcastReceiver instead and use it to send messages between the UI and background thread.
Word up, I need to update a context menu for a widget (listview in this case).
The items for the menu need to come from a call to a web service. If the web service call is made synchronously on the main UI thread then this works.
However due to fact that I'm calling a web service it needs to been done asynchronously via an AsyncTask or similar to avoid ANRs etc. This asynchronous update of the menu via menu.add() within the onCreateContextMenu doesn't work, i.e. asynchronous calls to menu.add() don't result in the context menu being displayed. Also note the async menu updates are done on the UI thread via the onPostExecute of an AsyncTask.
All Ui updates have to be done on UI thread. So you will have to post a runnable onto Ui thread.
Something like
runOnUiThread(new Runnable() {
public void run() {
//DO UI update here
}
});
Or you will have to call publishprogress() in doinBackground function of Asynctask and then do Ui work on onProgressUpdate().
If the Ui update can wait you should do it in OnPostExecute
Thanks to those that have provided answers, I may have to leave this for now with a somewhat half baked solution. For those reading this that are experiencing the same problem, my current solution uses the openContextMenu(View view) method in the activity to call back to the onCreateContextMenu. A simple boolean state flag determines whether to do the async call or populate the menu with the data from a previous async call. This design feels a bit awkward and fragile to me but works.
Save the information, you get from the web-service in the activity. Then in onPrepareContextMenu() use this information to update the menu. onPrepareContextMenu() is called before the context menu is displayed. OnCreateContentMenu() is only called once for every activity instance.
i have an application in which i have a UI activity which is supposed to display data which is retrieved after xml parsing done in another class.
during the xml parsing what i am doing is showing a progressdialog. i pass the handler of my ui activity to the thread doing xml parsing and when parsing is done , the xmlparser therad, using the handler that i have passed dispatches a message which is received by the UI activity after which it starts displaying the data.
the above is how i am doing multithreading.
is there a better way to do the same?
thank you in advance.
Edit: i have heard of the following async task, executionarservice, intent service.
which is the best for my purpose?
AsyncTask is your best friend if you are doing mutlithreading in android.
Instead of passing runnables to the UI THread, you need to implement a AsyncTask class, and them inside have it parse the xml in doInBackground().
For the progress dialog, initiate the dialog and the show it when onPreExecute() and dismiss it with onPostExecute(). If you want a precentage bar you can implement that in onProgressUpdate()
Surely there are several techniques for this task.
You can achieve multithreading by using Services, AsyncTasks, Handlers, ...
For taking the right decision based on your problem, i suggest you to take a look at Romain Guy's Painless Threading post on Android Developers. This is a very handy article, and very precise as well, never gets old.
I have got to know that the Handlers are basically used to Run the Small Section of Code and etc...
But I didn't got the exact scenerio about when particularly It is Ideal to use the Handlers!
Any Help???
Thanks,
david
Handlers are used for updating the UI from other (non-UI) threads.
For example, you can declare a Handler on your Activity class:
Handler h = new Handler();
Then you have some other tasks on different thread that wants to update some UI (progress bar, status message, etc). This will crash:
progressBar.setProgress(50);
Instead, call this:
h.post(new Runnable() {
public void run() {
progressBar.setProgress(50);
}
});
I'm a newbie myself but I'll give a newbie example since I recently learned this, I'm sure there are many more.
You have to use a Handler when you want to update the main UI when you are doing something in another thread. For example in my case I used it in image slideshow code that runs in a TimerTask. You cannot update the main UI ImageView with the next image from within the TimerTask because it's in a different thread. So you have to use a Handler or you get an error.
This is just one example. I hope this helps.