Why do I get the error Attempt to invoke direct method 'void asyncFinished(com.ats.atsver2.ui.db.classes.User)' on a null object reference
. On the onPostExecute, I get a result but when I try to send it through the delegate, I get the error.
Here is my code:
public class UserRepository {
private UserDao userDao;
private User user;
private LiveData<List<User>> allUsers;
public UserRepository(Application application) {
AtsDatabase database = AtsDatabase.getInstance(application);
userDao = database.userDao();
allUsers = userDao.getUsers();
}
private MutableLiveData<User> userSearched = new MutableLiveData<>();
private void asyncFinished(User userResult) {
if(userResult == null) return;
Log.i("TAG", "asyncFinished: " + userResult.getLastName());
userSearched.setValue(userResult);
}
public LiveData<User> getUserByUserName(String userName) {
new GetUserByUserNameAsyncTask(userDao).execute(userName);
}
public LiveData<List<User>> getAllUsers() { return allUsers; }
private static class InsertUserAsyncTask extends AsyncTask<User, Void, Void> {
private UserDao userDao;
private InsertUserAsyncTask(UserDao userDao) { this.userDao = userDao; }
@Override
protected Void doInBackground(User... users) {
userDao.insert(users[0]);
return null;
}
}
private static class GetUserByUserNameAsyncTask extends AsyncTask<String, Void, User> {
private LiveData<User> user;
private UserDao userDao;
private UserRepository delegate = null;
private GetUserByUserNameAsyncTask(UserDao userDao) { this.userDao = userDao; }
@Override
protected User doInBackground(String... strings) {
user = userDao.getUserByUserName(strings[0]); ======> I GET RESULT HERE
return null;
}
@Override
protected void onPostExecute(User user) {
super.onPostExecute(user);
Log.i("TAG", "onPostExecute: "+user.getLastName());
delegate.asyncFinished(user);
}
}
}
This delegate is within the same class except anonymously so why is it a null object? How can I make this right?
You are never assigning delegate
to the outer class instance when you create a new GetUserByUserNameAsyncTask
. Since it's null when you invoke asyncFinished()
it will throw a NPE.
private static class GetUserByUserNameAsyncTask extends AsyncTask<String, Void, User> {
private LiveData<User> user;
private UserDao userDao;
private UserRepository delegate;
private GetUserByUserNameAsyncTask(UserDao userDao, UserRepository delegate) {
this.userDao = userDao;
this.delegate = delegate;
}
@Override
protected User doInBackground(String... strings) {
user = userDao.getUserByUserName(strings[0]); ======> I GET RESULT HERE
return null;
}
@Override
protected void onPostExecute(User user) {
super.onPostExecute(user);
Log.i("TAG", "onPostExecute: "+user.getLastName());
delegate.asyncFinished(user);
}
}
You can now create it with your UserRepository
instance (this
):
public LiveData<User> getUserByUserName(String userName) {
new GetUserByUserNameAsyncTask(userDao, this).execute(userName);
}