When I run replication on Couchbase Lite in Android from UI Thread, it happens that the replication executes in another thread and notifications (Via addChangeListener() method) are received in a third Thread. My code for Pull Replication is as follow:
Replication pullRep = getDatabase().createPullReplication(syncUrl);
pullRep.setContinuous(true);
pullRep.addChangeListener(this);
pullRep.start();
My question is: How can I run synchronous replication or at least get notifications on the same Thread from which replication was started ?
My opinion is that replication must occur in the current thread. The developer must handle thread issues.
I´m very new with Couchbase Lite and maybe I´m wrong.
I apologize if I'm misunderstanding your situation, but I believe what you're trying to say is you can't update the UI with changes discovered in the Couchbase listener because the listener operates on a background thread and not the UI thread. Am I correct?
You definitely don't want to run potentially long tasks on the UI thread because it will create a poor UX. Asynchronous is the way to go.
You might try something like this instead:
Handler threadHandler = new Handler();
couchbaseDatabase.addChangeListener(new Database.ChangeListener() {
public void changed(Database.ChangeEvent event) {
// Alter variables related to the UI (maybe an array for a list view)
threadHandler.post(updateUI);
}
});
final Runnable updateUI = new Runnable() {
public void run() {
// Refresh the UI
adapter.notifyDataSetChanged();
}
};
Of course what I pasted is just bits and pieces and not a true working example. My point here is that I used a Handler. There are a ton of other ways that will work as well.
Would this work for you?
Best,
Related
I am making an android game which is made up of a game loop that is constantly running as well as use of the android UI stuff. So they need to be in separate threads to work concurrently.
I am planning to put the game loop inside an AsyncTask however it says in the developer.android documentation that
AsyncTasks should ideally be used for short operations (a few seconds at the most.)
My game loop will in theory be operating indefinitely and almost always for more than a few seconds. Is the asynctask the right place to put this then or is there another preferred method to split up a game loop and the UI operations
AsyncTasks are for short operations only, as the documentation has stated. Also, they usually do some work that shouldn't interfere with the UI. Hence, "Async" and "Task".
What you should use instead is a new Thread. This is called Multi-Threading. There are a lot of Game Frameworks out there which will have problems with android's UI. Though you have not stated what UI Operations you are talking about, but if you plan to use the android's widgets(UI), you could call Activity.runOnUiThread() to run a code on the UI Thread, for example, changing a TextView's text.
Here is a snippet on how you would create a never ending loop in a new thread(or something like this, i dont remember if the function is private):
new Thread(new Runnable() {
#Override
private void run() {
while(true) {
//your code goes here
}
}
});
Although AsyncTask allows you to perform background operations and publish results on the UI thread without having to manipulate threads, it should ideally be used for short operations (a few seconds at the most).
To keep things simple, you could use a Handler, or even better, research about the various APIs provided by the java.util.concurrent package.
import android.os.Handler;
// Create the Handler
private Handler handler = new Handler();
// Define the code block to be executed
private Runnable runnable = new Runnable() {
#Override
public void run() {
// Insert simulation processing code here
// Repeat 60 times per second
handler.postDelayed(this, 1000 / 60);
}
};
// Start the Runnable immediately
handler.post(runnable);
Remember that multi-threading is the easy part. Correct synchronization is hard.
I am using priority job queue , there are number of jobs running in parallel, so that their result populates on UI at same time which takes application to ANR, is there any way , so that i can run asynchronous calls and populate ui synchronously?
UI is always populated synchronously, if it is done in correct way. The correct way is to call activity.runOnUiThread(Runnable), directly or indirectly. Seems that your problem is that your jobs post to UI thread in a too high rate.
First, check if the Runnables to update UI does only UI work. Any calculations should be done outside the UI thread. If it is so, create an intermediate object which makes pauses between UI updates from the parallel jobs and so lets the UI thread to respond to updates from user. It can look as follows:
public class PauseMaker {
Semaphore sem = new Semaphore(1);
public void runOnUiThread(Runnable r) {
sem.aquire();
Thread.sleep(1);
activity.runOnUiThread(new Runnable(){
try {
r();
} finally {
sem.release();
}
});
}
}
You can use the zip operator of rxjava2 to merge the responses together and when the combined response comes you can populate the UI synchronously .. for reference you can check..
http://www.codexpedia.com/android/rxjava-2-zip-operator-example-in-android/
Note The zipper will the return merged response after all the responses are received
I am using greendao as ORM library in my Android project and have problems understanding the behaviour of transactions.
greendao offers an API runInTx(Runnable r) .
My question is, how will two calls of this method from different Threads will be handled?
Thread 1
public void thread1() {
DaoManager.INSTANCE.getDaoSession().runInTx(new Runnable()
{
doQueries();
doInsertsAndUpdates();
}
}
Thread 2
public void thread2() {
DaoManager.INSTANCE.getDaoSession().runInTx(new Runnable()
{
doQueries();
doInsertsAndUpdates();
}
}
I have seen, that runInTx is calling SQLiteDatabase.beginTransaction in exclusive mode, so no other thread can read/write to database while this transaction is open.
But what i cannot figure out is, when thread1 is doing his job (i.e. doQueries) will the other thread (i.e thread2) blocked, so doQueries and doInsertsAndUpdates of thread2 will not be performed until thread1 has finished the transaction?
Thanks for any help.
SQLiteDatabase.beginTransaction is a blocking call.
I love the convenience of the Handler class; I can easily queue messages and even delay messages. However, all the code runs on the UI thread which is causing stuttering of the animation.
Is there a class, like Handler, that doesn't run on the UI thread ?
You could always use a HandlerThread. I do not have a simple example of this handy, unfortunately.
Personally, I tend to use java.util.concurrent classes directly for things that do not involve the main application thread (e.g., LinkedBlockingQueue, ExecutorService).
I'm a little confused by the currently accepted answer which seems to imply that using Handler on a non-UI thread isn't possible, because it's something I've done quite routinely and I thought it was pretty well known.
Within a non-UI Thread:
#Override
public void run() {
Looper.prepare();
...
mThreadHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
...
break;
default:
break;
}
}
};
Looper.loop();
}
Using the mThreadHandler, messages can be sent to be processed by the Handler in the above non-UI Thread.
If there are any good reasons for not using the Handler / Message classes to post work to be done on a non-UI Thread in this way then I'd like to know. It has been working fine for me so far though. The only reason I've read for not using a Handler in this way is that "a Handler is meant for posting stuff to the UI thread" which is not in itself a good technical basis.
I've been reading up on how to use Thread in java, and I'm hoping someone can help me verify I'm using it correctly. I'm concerned that I should be calling .interrupt() or destroying the thread in some way.
I have a simple script that just hits my server to verify some data. My code:
Thread checkregister = new Thread(){
#Override
public void run(){
checkSystem();
}
};
checkregister.start();
Where checkSystem() posts the device id to a php script and waits for the response via HttpClient & HttpResponse. There isn't any looping so I don't think blocking is called for, but please let me know if I'm wrong.
No need to destroy the Thread. The Thread is effectively taken out of the thread scheduler as soon as run() returns.
If for some reason you need a way to prematurely "end" the Thread, this is a bit more complicated and there's been a lot of discussion about the proper way to do it. Simple way though is to just call stop() on the Thread.