具有两种类型的用户时从数据库读取

时间:2019-04-17 08:41:59

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

我正在开发一些Android应用,其中两种类型的用户可以登录,数据库将显示其信息。可以说一种类型的用户是顾客(“用户”),另一种类型是餐馆(“餐馆”)。当我尝试从数据库中读取用户详细信息时,问题开始了。当我只有一种类型的用户(子级“ Users”)时,应用程序运行良好并显示用户信息,但是当我添加另一种类型的用户(子级“ Restaurants”)时,该应用程序似乎不知道从哪个子级用户登录在?希望这是有道理的:)

// JSON

{
  "Restaurants" : {
    "4kASMGuVlxgk8HiDsxEt7IcSo4y2" : {
      "restaurantEmail" : "res1@gmail.com",
      "restaurantName" : "res1",
      "restaurantPhone" : "123456"
    },
    "6FwZR8rYxyVKm8FC8v0jV4ZwgVs2" : {
      "restaurantEmail" : "1604@gmail.com",
      "restaurantName" : "restaurant1604",
      "restaurantPhone" : "123456"
    },
    "vERcsGqBA0VNDjXfNvrseA29UGc2" : {
      "restaurantEmail" : "restaurant3@gmail.com",
      "restaurantName" : "restaurant3",
      "restaurantPhone" : "123456"
    }
  },
  "Users" : {
    "3BCqSyocaScBiviSUf2QAXo5Fdu1" : {
      "phoneNumber" : "123456",
      "userEmail" : "test3@gmail.com",
      "userName" : "test3"
    },
    "wzz9NBQt2YfFikMHTaMIcdRyCRI2" : {
      "phoneNumber" : "123456",
      "userEmail" : "test5@gmail.com",
      "userName" : "test5"
    }
  }
}

// JAVA

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    WelcomeActivity = new Intent(this,com.example.danie.dine.Activities.WelcomeActivity.class);
    BookingManagementActivity = new Intent(this,com.example.danie.dine.Activities.BookingManagementActivity.class);
    setContentView(R.layout.activity_home);

    mAuth = FirebaseAuth.getInstance();
    FirebaseUser currentUser = mAuth.getCurrentUser();
    userID = currentUser.getUid();
    mDatabase = FirebaseDatabase.getInstance();
    mRef = mDatabase.getReference("Users");

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in

                showMessage("Successfully signed in with: " + user.getEmail());
            } else {
                // User is signed out
                showMessage("Successfully signed out.");
            }
            // ...
        }
    };

///添加缺少的代码部分

mRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            showInfo(dataSnapshot);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

// JAVA尝试从数据库读取-不起作用

private void showInfo(DataSnapshot dataSnapshot) {
    for(DataSnapshot ds : dataSnapshot.getChildren()){
        UserInformation uInfo = new UserInformation();
        uInfo.setUserName(ds.child(userID).getValue(UserInformation.class).getUserName()); //get username
        uInfo.setUserEmail(ds.child(userID).getValue(UserInformation.class).getUserEmail()); //get user email
        uInfo.setPhoneNumber(ds.child(userID).getValue(UserInformation.class).getPhoneNumber()); //get user phone number
        //display user details
        lblUserName.setText(uInfo.getUserName()); //error points here
        lblUserEmail.setText(uInfo.getUserEmail());
        lblUserPhone.setText(uInfo.getPhoneNumber());
    }
}

///缺少代码2的一部分

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

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

// JAVA userInfo对象

public class UserInformation {

private String userName;
private String phoneNumber;
private String userEmail;


public UserInformation(){
}


public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getPhoneNumber() {
    return phoneNumber;
}

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

public String getUserEmail() {
    return userEmail;
}

public void setUserEmail(String userEmail) {
    this.userEmail = userEmail;
}

public UserInformation(String userName, String phoneNumber, String userEmail) {
    this.userName = userName;
    this.phoneNumber = phoneNumber;
    this.userEmail = userEmail;
}

}

到目前为止,如果我只有一个孩子“用户”,则应用程序会从数据库中读取并显示数据库,而没有任何问题,一旦添加孩子“餐馆”,所有的事情都会变成香蕉...我认为我需要某种方式指出代码来读取子级“ Users”,仅当我尝试仅显示用户信息时,而不是“ Restaurants”?

//错误消息

2019-04-17 11:44:33.116 11557-11557/com.example.danie.dine E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.danie.dine, PID: 11557
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.danie.dine.Model.UserInformation.getUserName()' on a null object reference
    at com.example.danie.dine.Activities.HomeActivity.showInfo(HomeActivity.java:172)
    at com.example.danie.dine.Activities.HomeActivity.access$100(HomeActivity.java:30)
    at com.example.danie.dine.Activities.HomeActivity$2.onDataChange(HomeActivity.java:93)
    at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.5:75)
    at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.5:63)
    at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.5:55)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6669)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

//建议的解决方法

mRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            UserInformation userDetails = dataSnapshot.getValue(UserInformation.class);
            userDetails.getUserName();
            userDetails.getPhoneNumber();
            userDetails.getUserEmail();
            userDetails.setUserName(dataSnapshot.child(userID).getValue(UserInformation.class).getUserName()); //get username
            userDetails.setUserEmail(dataSnapshot.child(userID).getValue(UserInformation.class).getUserEmail()); //get user email
            userDetails.setPhoneNumber(dataSnapshot.child(userID).getValue(UserInformation.class).getPhoneNumber()); //get user phone number
            lblUserName.setText(userDetails.getUserName());
            lblUserEmail.setText(userDetails.getUserEmail());
            lblUserPhone.setText(userDetails.getPhoneNumber());

2 个答案:

答案 0 :(得分:0)

简而言之

您必须创建两个方法:一个getUser()和另一个getRestaurant(),因为您所展示的数据库具有两个根节点:Users和Restaurants。

如果另一方面,您将所有用户(即“用户”和“餐厅”)保留在一个列表中,并带有附加的类型属性(“ type:0用于用户,type:1用于餐厅,或type:usertype:restaurant)一个数据库引用就足够了。您所要做的就是创建UserModel和RestaurantModel应该扩展的BaseModel,并在阅读type之后创建User或Restaurant。

我希望能回答您的问题。

答案 1 :(得分:0)

非常感谢您的所有建议,我参考了Firebase文档,并从头开始重做所有从数据库功能读取的内容。看来我的userInfo()方法无法正常工作,我摆脱了它,并创建了新方法(在// proposal修复注释下添加了代码。我希望有人会发现它有用。经验教训:)