未调用onAuthStateChanged且用户保持为null

时间:2017-03-25 10:47:09

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

我想要读取数据的代码:

public class DonorDetails extends AppCompatActivity {

private DatabaseReference donorDatabase;
private String TAG = "DonorDetails";
private FirebaseUser user;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseAuth mAuth;

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

    //initializing Firebase Database Object
    FirebaseOptions options = new FirebaseOptions.Builder()
            .setApplicationId("1:281410145157:android:6a1794e09956e306") // Required for Analytics.
            .setApiKey("AIzaSyB5MaQmmwSqgeVS9htvbVSMPizmuARkzYU") // Required for Auth.
            .setDatabaseUrl("https://e-blood-f1d0c.firebaseio.com") // Required for RTDB.
            .build();
    FirebaseApp donorApp = FirebaseApp.initializeApp(this, options, "DonorDetails");
    donorDatabase = FirebaseDatabase.getInstance(donorApp).getReference();


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

    // Read from the database
    donorDatabase.child("Donors").child(user.getUid()).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.
            Donor value = dataSnapshot.getValue(Donor.class);
            Log.d(TAG, "Value is: " + value);
        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w(TAG, "Failed to read value.", error.toException());
        }
    });
}

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

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

创建新用户的代码:

public class UserRegistrationActivity extends AppCompatActivity {

private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private static final String TAG = "Registration";
private EditText emailEditText, passwordEditText, nameEditText, phoneEditText, ageEditText, addressEditText, occupationEditText;
private Spinner bloodgroupSpinner;
private DatabaseReference donorDatabase;
private String userBloodGroup;
FirebaseUser user;

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

    //initializing Firebase Authentication Object
    mAuth = FirebaseAuth.getInstance();

    //initializing Firebase Database Object
    FirebaseOptions options = new FirebaseOptions.Builder()
            .setApplicationId("1:281410145157:android:6a1794e09956e306") // Required for Analytics.
            .setApiKey("AIzaSyB5MaQmmwSqgeVS9htvbVSMPizmuARkzYU") // Required for Auth.
            .setDatabaseUrl("https://e-blood-f1d0c.firebaseio.com") // Required for RTDB.
            .build();
    FirebaseApp donorApp = FirebaseApp.initializeApp(this, options, "DonorRegistration");
    donorDatabase = FirebaseDatabase.getInstance(donorApp).getReference();

    //initializing Views
    emailEditText = (EditText) findViewById(R.id.email_edit_text);
    passwordEditText = (EditText) findViewById(R.id.password_edit_text);
    nameEditText = (EditText) findViewById(R.id.name_edit_text);
    phoneEditText = (EditText) findViewById(R.id.phone_edit_text);
    ageEditText = (EditText) findViewById(R.id.age_edit_text);
    addressEditText = (EditText) findViewById(R.id.address_edit_text);
    occupationEditText = (EditText) findViewById(R.id.occupation_edit_text);
    bloodgroupSpinner = (Spinner) findViewById(R.id.blood_group_spinner);
    View registerButton = (View) findViewById(R.id.register_button);

    //ArrayAdapter for the Blood Group Spinner
    final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.blood_group, R.layout.spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    bloodgroupSpinner.setAdapter(adapter);
    bloodgroupSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            userBloodGroup = bloodgroupSpinner.getItemAtPosition(position).toString();
            Toast.makeText(parent.getContext(), "Bloood group is: " + userBloodGroup, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

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

    //Register On-Click
    registerButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            registerUser();
        }
    });
}

//RegisterUser
private void registerUser() {
    String email = emailEditText.getText().toString().trim();
    String password = passwordEditText.getText().toString().trim();
    mAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
                    // If sign in fails, display a message to the user. If sign in succeeds
                    // the auth state listener will be notified and logic to handle the
                    // signed in user can be handled in the listener.
                    if (!task.isSuccessful()) {
                        Toast.makeText(UserRegistrationActivity.this, "You are not eligible. Sorry",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        writeNewDonor(task.getResult().getUser());
                        Intent userDetails = new Intent(UserRegistrationActivity.this, DonorDetails.class);
                        startActivity(userDetails);
                    }
                }
            });
}

//Add Details to Database
private void writeNewDonor(FirebaseUser user) {
    String name = nameEditText.getText().toString();
    long phone = Long.parseLong(phoneEditText.getText().toString());
    int age = Integer.parseInt(ageEditText.getText().toString());
    String address = addressEditText.getText().toString();
    String bloodGroup = userBloodGroup;
    String occupation = occupationEditText.getText().toString();

    Donor donor = new Donor(name, phone, age, address, bloodGroup, occupation);

    donorDatabase.child("Donors").child(user.getUid()).child("Name").setValue(donor.getName());
    donorDatabase.child("Donors").child(user.getUid()).child("Phone").setValue(donor.getPhone());
    donorDatabase.child("Donors").child(user.getUid()).child("Age").setValue(donor.getAge());
    donorDatabase.child("Donors").child(user.getUid()).child("Address").setValue(donor.getAddress());
    donorDatabase.child("Donors").child(user.getUid()).child("BloodGroup").setValue(donor.getBloodGroup());
    donorDatabase.child("Donors").child(user.getUid()).child("Occupation").setValue(donor.getOccupation());
}

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

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

在读取数据的代码中,未调用onAuthStateChanged且用户未初始化。 错误:

  

引起:java.lang.NullPointerException:尝试调用虚拟方法&java; .lang.Su。在空对象引用上

1 个答案:

答案 0 :(得分:0)

异常是由user对象在此代码运行时为null引起的:

donorDatabase.child("Donors").child(user.getUid()) ...

我并不是真正理解你的代码流,但你可以通过确保user对象在获取它之前先填充它来避免这个错误,如下所示:

user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
    donorDatabase.child("Donors").child(user.getUid())
}

希望这有帮助。