Unable to get particular record from database getting this output.
My output is :
java.lang.RuntimeException: Unable to start activity ComponentInfo{appwork.com.example/appwork.com.example.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.arch.lifecycle.LiveData.observe(android.arch.lifecycle.LifecycleOwner, android.arch.lifecycle.Observer)' on a null object reference
I am using room database, Modelview, Repository and Dao file to get Live data but unable to get particular record from database via following things
<pre><code>
public class MainActivity extends AppCompatActivity {
private NoteViewModel noteViewModel;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
noteViewModel =
ViewModelProviders.of(this).get(NoteViewModel.class);
noteViewModel.getNote("test7").observe(this, new Observer<Note>()
{
@Override
public void onChanged(@Nullable Note note)
{
Toast.makeText(MainActivity.this,
"found title is : " +note.getTitle(),
Toast.LENGTH_LONG).show();
}
});
}
}
public class NoteViewModel extends AndroidViewModel
{
private LiveData<Note> note;
public NoteViewModel(@NonNull Application application)
{
super(application);
// note = repository.getNote("");
}
public LiveData<Note> getNote(String search)
{
repository.getNote(search);
if(note != null)
{
return note;
}
return null;
}
}
public class NoteRepository {
private NoteDao noteDao;
private LiveData<Note> note;
public NoteRepository(Application application)
{
NoteDatabase noteDatabase =
NoteDatabase.getInstance(application);
noteDao = noteDatabase.noteDao();
}
public LiveData<Note> getNote(String search)
{
new SearchNoteAsyncTask(noteDao).execute(search);
if(note != null)
{
return note;
}
return null;
}
public static void asyncFinished(LiveData<Note> results)
{
note = results;
}
public static class SearchNoteAsyncTask extends AsyncTask<String, Void, LiveData<Note>>
{
private NoteDao noteDao;
private LiveData<Note> note;
private SearchNoteAsyncTask(NoteDao noteDao)
{
this.noteDao = noteDao;
}
public LiveData<Note> doInBackground(String... search)
{
return noteDao.getNote(search[0]);
}
public void onPostExecute(LiveData<Note> result)
{
asyncFinished(result);
}
}
}
@Dao
public interface NoteDao{
@Query("Select * from note_table where title =:search Order By priority DESC")
LiveData<Note> getNote(String search);
}
I am getting response in Repository call but unable to get value from public
static class SearchNoteAsyncTask extends AsyncTask<String, Void, LiveData<Note>>
Any working example will be great!
thanks