Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return data outside the main thread in Android Room

I am making an Android App using the Room Data Persistence Library, however I have difficulty to figure out how I can query the database in a new thread and return the value to the main thread...

For instance I have a method in my ProductDAO to retrieve one product by his barCode:

@Query("SELECT * FROM Product WHERE barCode = :barCode")
Product getProductById (String barCode);

And in another class I tried this :

public Product getProduct(final String barcode){
    final Product[] product = new Product[1];
    new Thread(new Runnable() {
        @Override
        public void run() {
            product[0] = db.inventory().getProductById(barcode);
        }
    });
    return product[0];
}

However the result is always null and I don't know how to return the value from getProductById in the main thread. I'm sure however that the database configuration is correct because all my queries works in the main thread when I build the database with allowMainThreadQueries()

I also have the same problem when inserting a product from a new thread :

public void AddProduct(final Product product){
    new Thread(new Runnable() {
        @Override
        public void run() {
            db.inventory().insertOneProduct(product);
        }
    });
}

because it doesn't seem to insert anything.

Thanks a lot !!

like image 384
obrassard Avatar asked Sep 15 '25 00:09

obrassard


1 Answers

The problem appears to be with this code:

 public void AddProduct(final Product product){
new Thread(new Runnable() {
    @Override
    public void run() {
        db.inventory().insertOneProduct(product);
    }
});
 }

Although you have created a thread, you did not call the start method. So change it to this:

 public void AddProduct(final Product product){
new Thread(new Runnable() {
    @Override
    public void run() {
        db.inventory().insertOneProduct(product);
    }
}).start();
}

And then it should work.

As a side note, you should be using Async Task instead of the thread as AsyncTask was designed to work with the android threading model and allows you to track progress easily while doing work on a separate thread among other benefits.

like image 147
SteelToe Avatar answered Sep 16 '25 13:09

SteelToe