I am using a Roomdatabase and I wish to search get a single object from the database when I give it's name. For that I wrote this Query in the DAO :
@Query("SELECT * FROM kuh_table WHERE name = :kuhName ")
Kuh findKuh(String kuhName);
I call it in the repository this way :
public Kuh findKuh(String kuhName){
final Kuh[] kuh = new Kuh[1];
new Thread(new Runnable() {
volatile boolean running = true;
@Override
public void run() {
if(running!= true) {
return;
}
kuh[0] =kuhDAO.findKuh(kuhName);
running = false;
}
}).start();
return kuh[0];
}
then in my ViewModel this way :
public Kuh findKuh(String kuhName){ return repository.findKuh(kuhName);}
I then initialize my ViewModel in a fragment and try using the method by giving a String like this:
MarkerApiKt.setMarkerTapListener(mapView, (MarkerTapListener) (new MarkerTapListener() {
public void onMarkerTap(@NotNull View view, int x, int y) {
Intrinsics.checkNotNullParameter(view, "view");
if (view instanceof MapMarker) {
MarkerCallout callout = new MarkerCallout(context);
callout.setTitle(((MapMarker) view).getName());
callout.setSubTitle("position: " + ((MapMarker) view).getX() + " , " + ((MapMarker) view).getY());
Kuh kuh = kuhViewModel.findKuh(((MapMarker) view).getName());
Toast.makeText(context, "this is "+ kuh.getName(), Toast.LENGTH_SHORT).show();
but somehow the istance of my object is always null since I end up with a nullpointer exception. Any idea what I may be doing wrong?
So, as @Olli said, the problem was that my thread in my Repository didn't finish its execution, which is why it returned a null object.
I just changed my code this way and now it works fine
public Kuh findKuh(String kuhName) throws InterruptedException {
final Kuh[] kuh = new Kuh[1];
Thread t1 = new Thread(new Runnable() {
volatile boolean running = true;
@Override
public void run() {
if(running!= true) {
return;
}
kuh[0] =kuhDAO.findKuh(kuhName);
running = false;
}
});
t1.start();
t1.join();
return kuh[0];
}