如何从userID子Firebase(Android)中的子项中获取推送数据?

时间:2018-09-29 20:23:23

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

我的Firebase数据库有问题。我想从userID的(child)的child中获取推送的用户数据。请帮助我,并说明如何从唯一用户的孩子参考中获取孩子。我已经可以从userID子级中提取数据,但是我不能再进一步了。我几乎到处都在寻找,找不到答案。

预先感谢:)

Here is the Database

规则

{
/* Visit https://firebase.google.com/docs/database/security to learn more 
about security rules. */
 "rules": {
 ".read": "auth != null",
 ".write": "auth != null"
 }
 }

ViewDatabase

package com.mcarrow.mapsservicerunning;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;

public class ViewDatabase 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.view_database_layout);
    mListView =(ListView)findViewById(R.id.listview);
    mAuth=FirebaseAuth.getInstance();
    mFirebaseDatabase= FirebaseDatabase.getInstance();
    myRef=mFirebaseDatabase.getReference();
    FirebaseUser user=mAuth.getInstance().getCurrentUser();
    userID=user.getUid();
    mAuthListener=new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user =firebaseAuth.getInstance().getCurrentUser();
            if(user!=null){
                Log.d(TAG,"Signed in"+user.getUid());
                toastMessage("Signed In"+user.getEmail());
            }else {
                Log.d(TAG,"Signed Out");
                toastMessage("Signed Out");
            }

        }
    };
    myRef.addValueEventListener(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()) {

            UserInformation uInfo = new UserInformation();
            ds= (DataSnapshot) ds.child(userID).getChildren();

uInfo.setName(ds.getValue(UserInformation.class).getName());
uInfo.setEmail(ds.getValue(UserInformation.class).getEmail());
uInfo.setPhone_num(ds.getValue(UserInformation.class).getPhone_num());
            Log.d(TAG, "showData: name: " + uInfo.getName());
            Log.d(TAG, "showzData: phone_num: " + uInfo.getPhone_num());
            Log.d(TAG, "showData: email: " + uInfo.getEmail());
            ArrayList<String> array = new ArrayList<>();
            array.add(uInfo.getName());
            array.add(uInfo.getEmail());
            array.add(uInfo.getPhone_num());
            ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array);
            mListView.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_SHORT).show();
}

}

用户信息

package com.mcarrow.mapsservicerunning;

public class UserInformation {
private String Name;
private String Email;
private String Phone_num;
public UserInformation(){

}

public String getName() {
    return Name;
}

public void setName(String name) {
    Name = name;
}

public String getEmail() {
    return Email;
}

public void setEmail(String email) {
    Email = email;
}

public String getPhone_num() {
    return Phone_num;
}

public void setPhone_num(String phone_num) {
    Phone_num = phone_num;
}
}

LOGCAT

java.lang.ClassCastException: com.google.firebase.database.zza cannot be cast to com.google.firebase.database.DataSnapshot
    at com.mcarrow.mapsservicerunning.ViewDatabase.showData(ViewDatabase.java:73)
    at com.mcarrow.mapsservicerunning.ViewDatabase.access$100(ViewDatabase.java:23)
    at com.mcarrow.mapsservicerunning.ViewDatabase$2.onDataChange(ViewDatabase.java:58)
    at com.google.android.gms.internal.firebase_database.zzfc.zza(Unknown Source:13)
    at com.google.android.gms.internal.firebase_database.zzgx.zzdr(Unknown Source:2)
    at com.google.android.gms.internal.firebase_database.zzhd.run(Unknown Source:71)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6938)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

1 个答案:

答案 0 :(得分:0)

正如我在您的数据库中看到的那样,您正在使用一个我个人认为不需要的额外孩子。为简单起见,建议您使用以下数据库结构:

Firebase-root
   |
   --- users
         |
         --- uid
              |
              --- Email: "egor@gmail.com"
              |
              --- Name: "Egor"
              |
              --- Phone_num: "24365675"

看,现在缺少额外的级别。要获取单个用户的数据,请使用以下代码:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        UserInformation uInfo = dataSnapshot.getValue(UserInformation.class);
        Log.d(TAG, uInfo.getName());
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage());
    }
};
uidRef.addListenerForSingleValueEvent(valueEventListener);

如果要从所有用户那里获取数据,请使用以下代码:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            UserInformation uInfo = ds.getValue(UserInformation.class);
            Log.d(TAG, uInfo.getName());
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage());
    }
};
usersRef.addListenerForSingleValueEvent(valueEventListener);

代码中的另一个问题是您正在模型类字段中使用以大写字母开头而不是小写字母的字段。当您使用名为getName()的吸气剂时,Firebase会查找名为 name 而不是Name的字段。看到小写的n和大写的N?因此,这可能会给您带来麻烦。您的模型类应该是这样的正确方式:

public class UserInformation {
    private String name, email, phoneNum;

    public UserInformation() {}

    public UserInformation(String name, String email, String phoneNum) {
        this.name = name;
        this.email = email;
        this.phoneNum = phoneNum;
    }

    public String getName() { return name; }
    public String getEmail() { return email; }
    public String getPhoneNum() { return phoneNum; }
}

删除旧数据,添加新数据,一切正常。