简体   繁体   中英

Why am I getting a Null Pointer Exception when reading user data from Firebase?

I'm currently creating an android application that allows people to register and login to an account, add details to their profile and then display those details on another page.

I've successfully managed to log users into my application and store their profile data, however, I get a null pointer exception on line 90 in the class ViewProfileActivity. Which is: uInfo.setAddress(ds.child(userID).getValue(UserDetails.class).getAddress());

I've made sure that the database is read and write enabled. Any help would be greatly appreciated.

Below is all possible relevant code and an image of the firebase database structure

ViewProfileActivity

public class ViewProfileActivity extends AppCompatActivity {
    private static final String TAG = "ViewDatabase";

    private FirebaseDatabase mFirebaseDatabase;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private DatabaseReference myRef;
    private String userID;

    private ListView mListView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_profile);

        mListView = (ListView) findViewById(R.id.listview);

        //declare the database reference object. This is what we use to access the database.
        //NOTE: Unless you are signed in, this will not be useable.
        mAuth = FirebaseAuth.getInstance();
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        myRef = mFirebaseDatabase.getReference();
        FirebaseUser user = mAuth.getCurrentUser();
        userID = user.getUid();

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                    toastMessage("Successfully signed in with: " + user.getEmail());
                } else {
                    // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");
                    toastMessage("Successfully signed out.");
                }
                // ...
            }
        };

        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                showData(dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }

    private void showData(DataSnapshot dataSnapshot) {
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            UserDetails uInfo = new UserDetails();
            uInfo.setAddress(ds.child(userID).getValue(UserDetails.class).getAddress()); //set the email
            uInfo.setDateOfBirth(ds.child(userID).getValue(UserDetails.class).getDateOfBirth());
            uInfo.setName(ds.child(userID).getValue(UserDetails.class).getName()); //set the name
            uInfo.setPhoneNumber(ds.child(userID).getValue(UserDetails.class).getPhoneNumber());


            //display all the information
            Log.d(TAG, "showData: name: " + uInfo.getName());
            Log.d(TAG, "showData: email: " + uInfo.getAddress());
            Log.d(TAG, "showData: phone_num: " + uInfo.getPhoneNumber());
            Log.d(TAG, "showData: phone_num: " + uInfo.getDateOfBirth());

            ArrayList<String> array = new ArrayList<>();
            array.add(uInfo.getName());
            array.add(uInfo.getAddress());
            array.add(uInfo.getPhoneNumber());
            array.add(uInfo.getDateOfBirth());
            ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array);
            mListView.setAdapter(adapter);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }
}

CreateProfileActivity

public class CreateProfileActivity extends AppCompatActivity {

    private FirebaseAuth auth;
    private TextView textViewUserEmail;

    private EditText editTextName;
    private EditText editTextPhoneNumber;
    private EditText editTextPostalAddress;
    private EditText editTextDateOfBirth;


    private Button buttonSaveProfile;
    private Button buttonLogout;


    private DatabaseReference databaseReference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_profile);

        auth = FirebaseAuth.getInstance();

        if(auth.getCurrentUser() == null)
        {
            finish();
            startActivity(new Intent(this,LoginActivity.class));
        }


        databaseReference = FirebaseDatabase.getInstance().getReference();

        FirebaseUser user = auth.getCurrentUser();

        textViewUserEmail = (TextView) findViewById(R.id.textViewUserEmail);
        textViewUserEmail.setText("Welcome " + user.getEmail());

        buttonLogout = (Button) findViewById(R.id.buttonLogout);
        buttonSaveProfile = (Button) findViewById(R.id.buttonSaveProfile);

        editTextName = (EditText) findViewById(R.id.editTextName);
        editTextPhoneNumber = (EditText) findViewById(R.id.editTextPhoneNumber);
        editTextPostalAddress = (EditText) findViewById(R.id.editTextPostalAddress);
        editTextDateOfBirth = (EditText) findViewById(R.id.editTextDateOfBirth);


        buttonLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                auth.signOut();
                finish();
                startActivity(new Intent(CreateProfileActivity.this, LoginActivity.class));
            }
        });

        buttonSaveProfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveUserInformation();
            }
        });
    }

    private void saveUserInformation()
    {
        String address = editTextPostalAddress.getText().toString().trim();
        String dateOfBirth = editTextDateOfBirth.getText().toString().trim();
        String name = editTextName.getText().toString().trim();
        String phoneNumber = editTextPhoneNumber.getText().toString().trim();

        UserInformation userInformation = new UserInformation(name, address, dateOfBirth, phoneNumber);

        FirebaseUser user = auth.getCurrentUser();
        databaseReference.child("users").child(user.getUid()).setValue(userInformation);

        Toast.makeText(this, "Information Saved...", Toast.LENGTH_SHORT).show();

        startActivity(new Intent(CreateProfileActivity.this, ViewProfileActivity.class));
    }
}

UserDetails Class

public class UserDetails
{
    public String name;
    public String address;
    public String dateOfBirth;
    public String phoneNumber;

    public UserDetails()
    {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getDateOfBirth() {
        return dateOfBirth;
    }

    public void setDateOfBirth(String dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
}

Firebase数据库结构图

I guess that you are not referring to the data that you want

instead of this

  myRef = mFirebaseDatabase.getReference();

use this to point to your data

 myRef = mFirebaseDatabase.getReference().child("users");

change this line

myRef.addValueEventListener(new ValueEventListener()...

with this

myRef.child("users").addValueEventListener(new ValueEventListener()...

also in your UserDetails.class press in one of the variables Fn + alt + insert , select Constructor and select all your variables and make a constructor for them , and do not delete the empty one keep it there too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM