I am trying to create a simple journal app but it keeps crashing because of a java null.pointer exception problem. I have been trying to fix it for a while but still could not figure it out. I am using firestore with its authentication feature.
The error is showed at the NewNoteActivity
that has the getCurrentUser
line.
This is the register activity:
...
public class RegisterActivity extends AppCompatActivity {
private static final String TAG = "003";
private EditText emailfield, passfield;
private FirebaseAuth mAuth;
private String email, password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
emailfield = (EditText) findViewById(R.id.reg_email);
passfield = (EditText) findViewById(R.id.reg_password);
Button submitbtn = (Button) findViewById(R.id.submitRegBtn);
mAuth = FirebaseAuth.getInstance();
submitbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!hasValidationErrors(email, password)) {
register();
}
}
});
}
private void register() {
//create user
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseFirestore db = FirebaseFirestore.getInstance();
String userId = mAuth.getCurrentUser().getUid();
//save username
CollectionReference userRef = db.collection("main").document(userId).collection("userinfo");
UserInfo userinfo = new UserInfo(email);
userRef.add(userinfo).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("Failed at userinfo", e.getMessage());
}
});
Intent toMain = new Intent(RegisterActivity.this, NewNoteActivity.class);
toMain.putExtra("userinfo", userinfo);
startActivity(toMain);
Toast.makeText(RegisterActivity.this, "User Created", Toast.LENGTH_SHORT).show();
} else {
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(RegisterActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
protected void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
Intent toMain = new Intent(RegisterActivity.this, NewNoteActivity.class);
startActivity(toMain);
}
}
private boolean hasValidationErrors(String emailText, String passText) {
if (emailText.isEmpty()) {
emailfield.setError("Required");
emailfield.requestFocus();
return true;
} else if (passText.isEmpty()) {
passfield.setError("Required");
passfield.requestFocus();
return true;
}
return false;
}
}
This is the login activity.
...
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "002";
private EditText emailfield, passfield;
private FirebaseAuth mAuth;
private String email, password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
emailfield = (EditText) findViewById(R.id.reg_email);
passfield = (EditText) findViewById(R.id.reg_password);
Button submitbtn = (Button) findViewById(R.id.submitbtn);
mAuth = FirebaseAuth.getInstance();
//get data
email = emailfield.getText().toString().trim();
password = passfield.getText().toString().trim();
submitbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!hasValidationErrors(email, password)){
login();
}
}
});
}
private void login() {
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(LoginActivity.this, "You're logged in :)", Toast.LENGTH_SHORT).show();
startActivity(new Intent(LoginActivity.this, NewNoteActivity.class));
} else {
Log.w(TAG, "signInWithEmail:failure", task.getException());
Toast.makeText(LoginActivity.this, Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(LoginActivity.this, "failure listener " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void toRegisterpage(View view) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
@Override
protected void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser!=null){
Intent toMain = new Intent(LoginActivity.this, NewNoteActivity.class);
startActivity(toMain);
}
}
private boolean hasValidationErrors(String emailText, String passText) {
if (emailText.isEmpty()) {
emailfield.setError("Required");
emailfield.requestFocus();
return true;
} else if (passText.isEmpty()){
passfield.setError("Required");
passfield.requestFocus();
return true;
}
return false;
}
}
add new entry activity
...
public class NewNoteActivity extends AppCompatActivity {
private RelativeLayout wholeLayout;
private EditText titleInput, desInput, reflecInput;
private Toolbar toolbar;
private FirebaseFirestore db;
private FirebaseAuth mAuth;
private String userId;
private CollectionReference userIdRef;
private Journal journal;
private String date, titleText, descText, reflecText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newnote);
wholeLayout = (RelativeLayout) findViewById(R.id.wholeLayout);
titleInput = (EditText) findViewById(R.id.title);
desInput = (EditText) findViewById(R.id.description);
reflecInput = (EditText) findViewById(R.id.reflection);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);
db = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
date = new SimpleDateFormat("EEEE, dd MMM yyyy hh:mm", Locale.getDefault()).format(new Date());
titleText = titleInput.getText().toString().trim();
descText = desInput.getText().toString().trim();
reflecText = reflecInput.getText().toString().trim();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
saveNote();
Toast.makeText(this, "Saved!", Toast.LENGTH_SHORT).show();
break;
case R.id.action_list:
Toast.makeText(this, "Loading entries", Toast.LENGTH_SHORT).show();
break;
case R.id.action_mail:
Toast.makeText(this, "Have a suggestion?", Toast.LENGTH_SHORT).show();
break;
case R.id.action_settings:
Toast.makeText(this, "Loading settings", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return true;
}
private void saveNote() {
if (!hasValidationErrors(descText)) {
if (titleText.isEmpty()) {
titleText = date;
} else {
userId = mAuth.getCurrentUser().getUid();
userIdRef = db.collection("main").document(userId).collection("journal");
journal = new Journal(userId, titleText, descText, reflecText, date);
userIdRef.add(journal).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(NewNoteActivity.this, "Saved note", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("Failed at saving note", e.getMessage());
Toast.makeText(NewNoteActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
}
private boolean hasValidationErrors(String descText) {
if (descText.isEmpty()) {
desInput.setError("Required");
desInput.requestFocus();
return true;
}
return false;
}
}
error from logcat
08-20 19:11:10.341 6603-6751/com.amethyst.within I/OpenGLRenderer: Initialized EGL, version 1.4
08-20 19:11:10.441 6603-6751/com.amethyst.within D/OpenGLRenderer: Enabling debug mode 0
08-20 19:11:15.601 6603-6603/com.amethyst.within D/AndroidRuntime: Shutting down VM
08-20 19:11:15.601 6603-6603/com.amethyst.within E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.amethyst.within, PID: 6603
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.amethyst.within/com.amethyst.within.NewNoteActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2462)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2534)
at android.app.ActivityThread.access$900(ActivityThread.java:164)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1419)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:159)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.amethyst.within.NewNoteActivity.onCreate(NewNoteActivity.java:69)
at android.app.Activity.performCreate(Activity.java:6093)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2415)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2534)
at android.app.ActivityThread.access$900(ActivityThread.java:164)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1419)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:159)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)
08-20 19:11:15.691 6603-6603/com.amethyst.within I/Process: Sending signal. PID: 6603 SIG: 9
08-20 19:11:15.691 6603-6603/com.amethyst.within V/Process: killProcess [6603] Callers=com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException:99 java.lang.ThreadGroup.uncaughtException:693 java.lang.ThreadGroup.uncaughtException:690 <bottom of call stack>
Any help would be very much appreciated.