How to avoid NullPointerException when deleting a document in Firestore?

I want to give the user in my app the possibility to delete his account so when he clicks on the delete button a document gets deleted which contains all his informations. The name of the document is his displayName so I get this as a string but when I run the code you are seeing below, I get a NullpointerException in this line: String currentUsername = user.getDisplayName();even though the displayName is not null. How can I avoid this exception?

Here is my method:


btn_delete_account.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

                user.delete()
                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if (task.isSuccessful()) {
                                    deleteDocument();

                                }
                            }
                        });
            }
        });

...

public void deleteDocument (){

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        String currentUsername = user.getDisplayName();

        db.collection("User").document(currentUsername)
                .delete()
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.d(TAG, "DocumentSnapshot successfully deleted!");
                        Toast.makeText(PersonalSettings.this, "Dein Account wurde erfolgreich gelöscht.", Toast.LENGTH_SHORT).show();
                        Intent i = new Intent(PersonalSettings.this, SignInActivity.class);
                        startActivity(i);
                        finish();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.w(TAG, "Error deleting document", e);
                    }
                });
    }

3 answers

  • answered 2019-10-15 16:11 Doug Stevenson

    I think you're misunderstanding the error. It's saying that user is null, not the display name. This means there is currently no user signed into the app. You will have to write some code to check for this case.

    I also strongly suggest not using a display name as the ID for a document in Cloud Firestore. Since you're using Firebase Authentication, the user already has a unique ID assigned to their account. This is the preferred way to store per-user data.

  • answered 2019-10-15 16:32 Kaiser

    I found the error:

    I called my delete method after I used the user.delete() method which deletes the signed in user, so logically the displayName was also deleted.

  • answered 2019-10-16 02:41 Rishav Singla

    First thing you have to check that current user is not null

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if(user==null)
    {
     return;
    }
    

    if current user is not null then get its name and further check that it's name is not null.

    String currentUsername = user.getDisplayName();
    if(TextUtils.isEmpty(currentUsername))
     {
      return;
     }
    

    if name is not null then go for delete document as follows :

    public void deleteDocument (){
    
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
         if(user==null)
         {
          return;
         }
    
        String currentUsername = user.getDisplayName();
         if(TextUtils.isEmpty(currentUsername))
         {
            return;
         }
    
        db.collection("User").document(currentUsername)
                .delete()
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Log.d(TAG, "DocumentSnapshot successfully deleted!");
                        Toast.makeText(PersonalSettings.this, "Dein Account wurde erfolgreich gelöscht.", Toast.LENGTH_SHORT).show();
                        Intent i = new Intent(PersonalSettings.this, SignInActivity.class);
                        startActivity(i);
                        finish();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.w(TAG, "Error deleting document", e);
                    }
                });
    }