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 !!