从Firebase读取用户数据时,为什么会出现Null指针异常?

时间:2018-02-15 17:57:33

标签: java android firebase firebase-realtime-database nullpointerexception

我目前正在创建一个Android应用程序,允许用户注册并登录帐户,向其个人资料添加详细信息,然后在另一个页面上显示这些详细信息。

我已成功设法将用户登录到我的应用程序并存储他们的个人资料数据,但是,我在ViewProfileActivity类的第90行获得了空指针异常。这是:uInfo.setAddress(ds.child(userID).getValue(UserDetails.class).getAddress());

我已确保数据库已启用读写。任何帮助将不胜感激。

以下是所有可能的相关代码和firebase数据库结构的图像

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类

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 Database Structure Image

2 个答案:

答案 0 :(得分:2)

我猜你不是指你想要的数据

而不是

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

用它来指向你的数据

$configFiles = Get-ChildItem "C:\RDP LINKS\" *.rdp -rec
foreach ($file in $configFiles)
{
    (Get-Content $file.PSPath) |
    Foreach-Object { $_ -replace "administrator@testdomain.local", "administrator@test2domain.local" } |
    Set-Content $file.PSPath
}

答案 1 :(得分:1)

更改此行

private func handleTabSelection(selectedIndex: Int) {
    //Do something on tab selection at selectedIndex
}

用这个

myRef.addValueEventListener(new ValueEventListener()...

同样在myRef.child("users").addValueEventListener(new ValueEventListener()... 按下其中一个变量UserDetails.class,选择Fn + alt + insert并选择所有变量并为其构建一个构造函数,并且不要删除空变量保留它那里也是。