Room running very slow

Multi tool use
Multi tool use


Room running very slow



I'm trying to get/store data using the Room Persistence Library. The calls to get all data from a table is really slow, and I timed it using nanoTime to be about 1800ms, which I think is too slow. What could be going wrong?


nanoTime



Here's some more info:


nanoTime


AsyncTask



The query is defined in DbDao as


@Query("SELECT * FROM events")
List<Event> getAllEvents();




1 Answer
1



Async task is not good for handling Room database. I would suggest you to use executor and make a singleton class using this. Code is as follows.


import android.os.Looper;
import android.support.annotation.NonNull;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;




public class AppExecutor {
private static final Object LOCK = new Object();
private static AppExecutor sInstance;
private final Executor diskIO;
private final Executor mainThread;
private final Executor networkIO;

public AppExecutor(Executor diskIO, Executor mainThread, Executor networkIO) {
this.diskIO = diskIO;
this.mainThread = mainThread;
this.networkIO = networkIO;
}
public static AppExecutor getInstance(){
if (sInstance==null){
synchronized (LOCK){
sInstance = new AppExecutor(Executors.newSingleThreadExecutor(),Executors.newFixedThreadPool(3),new MainThreadExecutor());
}
}
return sInstance;
}
public Executor diskIO() {
return diskIO;
}
public Executor mainThread() {
return mainThread;
}

public Executor networkIO() {
return networkIO;
}

private static class MainThreadExecutor implements Executor{

private android.os.Handler mainThreadHandler = new android.os.Handler(Looper.getMainLooper());

@Override
public void execute(@NonNull Runnable runnable) {

}
}

}



Now after making this new class do all database access functions in the appexecutor threads. This is better than using async task and built in java thread libraries. Also make sure that any data access functions does not run on UI thread.
If you have posted more code I would be able to pinpoint the exact problem.
One last thing use this in your code as follows-


AppExecutor.getInstance().diskIO().execute(new Runnable() {
@Override
public void run() {
 ///Your data access task////
}
});
}






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

lD kOqrDHQcK XCZ9fVgtG3Ina fm,B,aZ
kmyL4qHW 2HXWc,jUHUjeE,pTWXZsNe8,16zjr2 95g1OXWIyyq8,9WX7,1gkFc3oWE SMk1Mlk4y VOwcxQ rHgJx

Popular posts from this blog

PySpark - SparkContext: Error initializing SparkContext File does not exist

django NoReverseMatch Exception

List of Kim Possible characters