应用程序在查看详细信息时被强制停止
我已经尝试了不同的方法来连接到我的 firebase 用户 ID,但它给出了空指针异常并显示尝试调用接口方法Firebase 身份验证状态侦听器引发错误
查看详情.class
public class ViewDetails extends AppCompatActivity {
private DatabaseReference myref;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private String userId;
ListView listView;
private TextView name,email,phone,shopname,shopaddress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_details);
setContentView(R.layout.activity_login);getWindow().setBackgroundDrawableResource(R.drawable.inventorybackground);
listView=(ListView)findViewById(R.id.listview);
name=(TextView)findViewById(R.id.name);
email=(TextView)findViewById(R.id.email);
phone=(TextView)findViewById(R.id.phonenumber);
shopname=(TextView)findViewById(R.id.shopname);
shopaddress=(TextView)findViewById(R.id.shopaddress);
mAuth=FirebaseAuth.getInstance();
mFirebaseDatabase=FirebaseDatabase.getInstance();
myref=mFirebaseDatabase.getReference();
FirebaseUser user=mAuth.getCurrentUser();
userId=user.getUid();
myref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void showData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren())
{
getdetails get=new getdetails();
get.setName(ds.child(userId).getValue(getdetails.class).getName());
get.setEmail(ds.child(userId).getValue(getdetails.class).getEmail());
get.setPhone(ds.child(userId).getValue(getdetails.class).getPhone());
get.setShopname(ds.child(userId).getValue(getdetails.class).getShopname());
get.setShopadd(ds.child(userId).getValue(getdetails.class).getShopadd());
ArrayList<String> array = new ArrayList<>();
array.add(get.getName());
array.add(get.getEmail());
array.add(get.getPhone());
array.add(get.getShopname());
array.add(get.getShopadd());
ArrayAdapter adapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
listView.setAdapter(adapter);
}
}
@Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
protected void onStop() {
super.onStop();
if(mAuthListener!=null)
{
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void toastMessage(String message)
{
Toast.makeText(this,message,Toast.LENGTH_LONG).show();
}
}
怎么了?
你得到 null mAuthListener
因为永远不会实例化。
在你的onCreate()
中执行此操作
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// Your logic
}
}
};