Skip to content Skip to sidebar Skip to footer

Android Livedata Null Error When Trying To Update Object

I am looking for help to better understand LiveData in Android. I have created an application that allows a user to view, edit or create entries in a db. I have used a viewmodel on

Solution 1:

You are trying to call setName() on a NULL. Because patternViewModel.getPattern().getValue() returns the value that is held in the LiveData, which might be NULL in your case. You can add a null check:

if (patternViewModel.getPattern().getValue() == null) {
    FlyPatternflyPattern=newFlyPattern();
    flyPattern.setName("foo");
    patternViewModel.getPattern().setValue(flyPattern);
 } else {
    patternViewModel.getPattern().getValue().setName("foo");
 }

Or you can create a function in the ViewModel called e.g. setFlyPatternName() and use it to update your DB. In your PatternViewModel.java

publicvoidsetFlyPatternName(String name) {
    if (mObservablePattern.getValue == null) {
        FlyPattern flyPattern = newFlyPattern();
        flyPattern.setName(name);
        mObservablePattern.setValue(flyPattern);
        repo.insertFlyPattern();
    } else {
        mObservablePattern.getValue().setName(name);
        repo.updateFlyPattern();
    }
}

Edit: The proper way of doing this is actually a bit different. Normally your repository functions need to work on the background thread, since you are dealing with i/o, but if you want them to work on the mainThread you need to at least create a callback and pass that callback object to your repository function, which will be called when the data is inserted/updated/deleted. And when the callback function is called you need to call the setValue() on the LiveData and set the data to your livedata object.

Create a callback interface:

publicinterfaceInsertCallback {
    voidonDataInserted(FlyPattern flyPattern);

    voidonDataInsertFailed();
}

Change your repositories insert function's body to accept the Callback object as parameter

publicvoidinsertFlyPattern(FlyPattern flyPattern, InsertCallback insertCallback) {
    // Do your insertion and if it is successful call insertCallback.onDataInserted(flyPattern), otherwise call insertCallback.onDataInsertFailed(); 
}

In your ViewModel implement InsertCallback and it's method

publicclassPatternViewModelextendsAndroidViewModelimplementsInsertCallback {
//....publicvoidonDataInserted(FlyPattern flyPattern) {
    mObservablePattern.setValue(flyPattern);         
}

publicvoidonDataInsertFailed() { 
    //Show error message
} 

}

Post a Comment for "Android Livedata Null Error When Trying To Update Object"