Basically I have 2 tabs.
In which first tab contains the data, and the second one contains some summary kind of data based on first tab's data.
In the first tab there is list of events. Whenever the there is an add/update/delete operation on events the summary needs to recalculated. The recalculated summary creates the list of rows in the database. And from those rows the summary tab is displayed.
So the problem is summary calculation takes long amount of time. So it is blocking the UI thread. So I moved the calculations in the thread for smooth UI operations.
Now as summary calculation is running in thread, I don't know when the calculation is complete and now I need to update the summary tab data and showing something while calculation is going on.
The current setup which I have is something like this:
My DatabaseHelper Class:
add() {
...
// Do Add operation
...
reCalculateSummary();
}
remove() {
...
// Do remove operation
...
reCalculateSummary();
}
reCalculateSummary() {
new Thread(new Runnable() {
#Override
public void run() {
...
// calculate summary (may call another method)
...
// Add calculated summary to DB
}
}).start();
}
While the reCalculateSummary() is running, the summary to tab should show loading message.
So How can I achieve this whole situation working?
How can I know if thread has completed its execution? So that I can update summary tab data by retrieving new db values of summary data.
So here is some confusing situation. Please feel free to ask if you have any doubts in understanding the situation.
Thanks in advance!
Use an event bus, so you can update the UI, and avoid the limitation on AsyncTasks.
You can create the event "recalculateSummary", and just before job start (think of it as onPreExecute), update the UI with something that shows the user that the information on screen is not up-to-date, and update results when job is done.
Examples on event buses are Otto, EventBus, AutoBus ...
You can use an AsyncTask.
Do the processing in the doInBackground(..) method, and update the UI inside onPostExcecute(..) method
Related
when I'm querying lot of elements the UI get freeze.
realm.where(TVRealm.class).equalTo("favorite", true).findAllAsync()
.addChangeListener(new RealmChangeListener<RealmResults<TVRealm>>() {
#Override
public void onChange(RealmResults<TVRealm> element) {
List<TV> tvList = new ArrayList<>();
for (TVRealm tvRealm : element) {
tvList.add(prepareTV(TVRealm.toTV(tvRealm), true));
}
listener.onDataChange(tvList);
}
});
I thought that findAllAsync() will run on other thread and avoid the issue but not.
Does anyone knows how to avoid this issue? Maybe there is another way without using findAllAsync() method.
Thanks.
According to official Realm document, findAllAsync works in a background thread.
https://realm.io/docs/java/latest/#asynchronous-queries
I think your data changes too often and so you're trying to notify ui too often. So you're blocking ui. I guess you are notifying a RecyclerView adapter in your onDataChange method.
Also if your result list has too many items, every time when your data changed exploring the results and adding items to a new list may block ui.
If I don't make mistake, while RealmResults is updating, for each change you create new collection with new models and update UI. Try to call findAll() in another thread, map results to TVs and post completed list of TVs to UI thread.
why dont you try this
RealmResult<item> res=realm.where(item.class).where("name","sanjay").findAll();
it will get all the data at a time.
I have a method playSoE() that performs an operation on each view and updates the ArrayAdapter and thus GridView after each operation. I want to do is have the code wait for 1 second after the update is done, and then perform the operation on the next view. For example:
public class MainActivity extends Activity{
public void playSoE(){
for(int i = 0; i < primesLE; i++) //iterates to each view
mAdapter.setPositionColor(index, 0xffff0000 + 0x100 * index); //operation performed on view
mAdapter.notifyDataSetChanged(); //updates adapter/GridView
//Code that waits for one second here
}
}
I have tried many threading APIs but none of them seem to work, they've either froze up the application for primesLE seconds and shown all the operations at the end, skip the second wait and just performed all the operations at once, or gotten an Exception related to concurrency.
Assuming the update itself is quick, you should not be creating additional threads at all. Create a Handler and use postDelayed(...) to time your updates in the UI thread.
You may have to take a look at AsyncTask.
Put the wait code at the doInBackground() and then the following that affects the visual on the onPostExecute()
All you do on doInBackground() will not freeze your application.
I have a bit of a problem I cannot solve, since it might a bug or something like that. I would like to make a chart with androidplot, and it works really good, but of course it needs some time to draw it (using hundreds of data), so I use a progress dialog to indicate the loading. But what happens is really weird.
I can define the appearance of the activity when it's loading and when it's loaded. When its loading I define a textview in the background setting its text to "loading" and if it is loaded, that textview contains lots of datas, text etc.
onCreate
{
Thread thread = new Thread(new Runnable() {
public void run() {
-------what needs to be appeared after its loaded ----
Textview -> 12,3245,456,78,789
}
----what is on the screen while the progressbar is on---
TextView -> loading..
}
But most of the time after the progress dialog disappears, nothing happens, the textview still says "loading" and rarely it loads the datas and makes the data appear and changes the textview. What I noticed that the more data I would like to appear the rarelier it stays at the loading phase. Of course everytime the loading progessbar appeers then disappears.
Any Suggestion? It is really weird because I use it in a tablayout and other tabs never do this, always make the data appear.
Thanks in advance!
UP: Okay, its always the first tab, whatever it contains, so the first tab is somehow wrong...
The Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI
from a worker thread—you must do all manipulation to your user interface from
the UI thread. Thus, there are simply two rules to Android's single thread model:
1. Do not block the UI thread
2. Do not access the Android UI toolkit from outside the UI thread
read this for more information on how to access UI elements from outside.
edit::
use AsyncTask ::
onCreate
{
new myLoading().execute();
}
class myLoading extends AsyncTask<Void, Void, Void>
{
protected Void doInBackground(Void ... ) {
.......... do all the loading here .........
}
protected void onPostExecute(Void ) {
Textview -> 12,3245,456,78,789
}
}
I figured out some workaround. I dont have any clue about the solution, my only guess is the loading screen somehow overtake the arrival of all the data and so the chart cannot be drawn. or whatever...
I put a thread.sleep(1000) and now it works.
I will attempt to summarize my code as follows:
I have a TileAdapter which extends from BaseAdapter to populate a GridView
My TileAdapter contains an array of Tiles that is used to maintain state
My TileUpdate class performs the following operations:
Changes Tile A's colour to green
Calls TileAdapter.notifyDataSetChanged()
Changes Tile B's colour to yellow
Calls TileAdapter.notifyDataSetChanged()
Changes Tile B's colour to red
Calls TileAdapter.notifyDataSetChanged()
I would have expected to see my GridView refresh 3 times, once for each call to notifyDataSetChanged().
However, I only see it refresh after step 6, when and never see Tile B turn yellow.
What is happening here? I presume there is some part of the API I'm not aware of.
Thanks
Update
I still have not been successful in implementing this, even after studying the Handler approaches described below.
So in my UI thread I've created a new GridOperationQueue class which extends from Thread:
public class GridOperationQueue extends Thread {
private Handler handler;
#Override
public void run() {
Looper.prepare();
handler = new Handler();
Looper.loop();
}
public void addTaskToQueue(final GridUpdateTask task)
{
Log.d(this.getClass().toString(), "Current thread is ID " + Thread.currentThread().getId());
handler.post(new Runnable()
{
#Override
public void run() {
Log.d(this.getClass().toString(), " Handler task's current thread is ID " + Thread.currentThread().getId());
task.run();
}
});
}
public void clearQueue(){
handler.removeCallbacksAndMessages(null);
}
}
So my UI thread invokes addTaskToQueue providing a new Task object. The idea is that the task's processing will be performed on a separate thread and after it completes invokes a notifyDataSetChanged() on the UI thread.
However, I've added some logging and it seems that when my tasks run they are still running on the main thread....how would this be? See the following logging:
GridOperationQueue(4393): Current thread is ID 1
GridOperationQueue(4393): Current thread is ID 1
GridOperationQueue(4393): Current thread is ID 1
GridOperationQueue$1(4393): Handler task's current thread is ID 9
TileOperationService$1(4393): Current thread is ID 9
MyActivity(4393): Current thread is ID 9
GridOperationQueue$1(4393): Handler task's current thread is ID 9
TileOperationService$2(4393): Current thread is ID 9
MyActivity(4393): Current thread is ID 9
GridOperationQueue$1(4393): Handler task's current thread is ID 9
TileOperationService$3(4393): Current thread is ID 9
MyActivity(4393): Current thread is ID 9
How come the tasks are still running on the main thread?
I assume you're making all of those changes in your onClick method. The onClick method runs in the UI thread... so, while the code in onClick is running, the UI thread cannot change and tile colors since it's busy. in fact, notifyDataSetChanged simply sets a flag that tells Android to update the changes to the view whenever it can; notifyDataSetChanged does not force an update, but simple tells android one is needed. Thus, you are simply telling android it needs to update the view three times... but, by the time android can actually make the update, which is after your onClick method is done, it can only see the most recent change to the tile color.
How do you get around this? Well, it depends on what you really want to do. for instance, if you want tile color A to change to tile color B when you click the view, and then change to tile color C 500 ms later, do something like this
Handler handler; // instance var
public onCreate(Bundle savedInstanceState) {
...
handler = new Handler();
}
// in your onClick method, wherever it may be (pseudocode)
public void onClick(View v) {
1) set tile color to color B
2) call notifyDataSetChanged
3) schedule a color change in 500 ms:
handler.postDelayed(new Runnable() {
public void run() {
1) set tile color to color C
2) call notifyDataSetChanged
}
}), 500);
You should take a look at Updating the UI from a Timer. The trouble is that when you call notifyDataSetChanged() you only trigger a flag to the GUI. When the adapter gets a repaint it checks if the flag is set and takes action. It does not take any action directly when you call notify.
If you want to update the GUI directly you should learn about the class Handler (see the previous link) so you can post updates to the interface.
Maybe I misunderstood your question, but it seems that you are updating twice the color of Tile B (identical steps 3 and 5 on your question). If that's the case, you will only see the last color (red) and yellow will never be displayed, of course.
Or, you meant "Tile C" on step 5. If this is the case, then the following comments might help:
Even if the UI is changing 3 times, you are probably overriding each color on each call.
1) So your three tiles are 'default' color
2) You update Tile A to green
3) notifyDataSetChanged() is called
(your grid view is updated correctly)
4) You update Tile B to yellow
5) notifyDataSetChanged() is called
(your grid view updates Title B to yellow, but overrides Title A to 'default' color.
6) You update Tile C to red
7) notifyDataSetChanged() is called
(your grid view updates Title C to red, but overrides Title A and B to 'default' color.
That could be the issue.
Also, remember as other guys have mentioned, notifyDataSetChanged() does nothing directly. It only signals the UI to be refreshed when the ideal conditions are met.
I am writing an application that searches a database in "realtime".
i.e. as the user presses letters it updates a search results list.
Since the search can take a while, I need to do the search in background and allow new key presses to re-start a search. So that is a user presses 'a' (and the code starts searching for "a"), then presses 'b' - the code will NOT wait for "a" search to end, then start searching for "ab", but rather STOP the "a" search, and start a new "ab" search.
To do that I decided to do the search in an AsyncTask. Is this a wise decision ?
Now - whenever a keypress is detected, I test to see if I have an AsyncTask running. If I do - I signal it (using a boolean within the AsyncTask) it should stop. Then set a timer to re-test the AsyncTask within 10 mSec, to see if it terminated, and start the new search.
Is this a smart method ? Or is there another approach you would take ?
TIA
First yes, AsyncTask is a good way to do this. The problem I see with your approach is the timer waiting to watch something die. When you invoke the asyncTask hold onto a reference of it. Let it keep state for you so you know if it's out searching or it's has returned. When the user clicks another letter you can tell that asyncTask to cancel. Something like this:
public void onClick() {
if( searchTask != null ) {
searchTask.cancel();
}
searchTask = new SearchTask( MyActivity.this ).execute( textInput.getText() );
}
public class SearchTask extends AsyncTask<String,Integer,List<SearchResult>> {
private boolean canceled = false;
protected onPostExecute( List<SearchResult> results ) {
if( !canceled ) {
activity.handleResults( results );
}
}
public void cancel() {
canceled = true;
}
}
This is safe because onPostExecute() is on the UI thread. And cancel() is only called from the UI thread so there is no thread safety issues, and no need to synchronize. You don't have to watch a thread die. Just let the GC handle cleaning up. Once you drop the reference to the AsyncTask it will just get cleaned up. If your AsyncTask blocks that's ok because it only hangs up the background thread, and when the timeout hits it will resume by calling onPostExecute(). This also keeps your resources to a minimum without using a Timer.
Things to consider about this approach. Sending a new request everytime a new letter is typed can overload your servers because the first few letters are going to produce the largest search results. Either limit the number of results you'll return from the server (say 10-50 results max), or wait until they've entered enough characters to keep results down (say 3). The cons of making the user type more characters is the feedback doesn't kick in until 3 chars. However, the pro is it will dramatically reduce the hits on your server.