【问题标题】:Retreive data from a certain position in firebase using Android Studio使用 Android Studio 从 Firebase 中的某个位置检索数据
【发布时间】:2019-02-14 04:54:49
【问题描述】:

大家好 :) 我是编程新手,刚开始在 Android Studio 中使用 RecyclerView。

现在我想从 firebase 中的位置 x 检索数据:

例如,我的数据库包括:

用户: Max(包含字段:大学、年龄、城市) Lena(字段:大学、年龄、城市)

我不知道有多少用户以及他们的名字,我想获取一个用户在位置 x 的所有数据。

有没有人知道如何解决这个问题? 提前致谢!

编辑: 我现在保存了用户的 UID 并将其传递给其他活动。然后我试图从firebase接收所属数据,但我仍然无法在TextView中显示来自“大学”字段的数据。

public class nextActivity extends AppCompatActivity{

String UID;
private DocumentReference myReference;

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

//get data from intent (I checked the value of UID - getIntent worked.)
UID = getIntent().getStringExtra("uid");

// I am not sure with the following line. Is it possible to just add "UID"?
myReference = FirebaseFirestore.getInstance().document("Users/"+UID);
myReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
    @Override
    public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
        if (documentSnapshot.exists()) {

            long universityID = documentSnapshot.getLong("university");
            cUniversityText.setText("University"+Long.toString(universityID));

        } else if (e != null) {
            Log.w("InspiringQuote", "Exception!", e);
        }
    }
});
cUniversityText = findViewById(R.id.cuniversitytext);

}

【问题讨论】:

  • 您构建数据库的方式不合适。如需指导,请参阅 - stackoverflow.com/questions/16421179/…
  • at position x 是什么意思?请回复@。
  • @dunkiero 也许您应该保存用户的uid 并将其传递给其他活动,以便能够获取特定用户的数据。
  • @dunkiero 这行代码在Log.d("TAG", String.valueOf(universityID)); 放在这行cUniversityText.setText("University"+Long.toString(universityID)); 之后会打印什么?
  • @dunkiero 好的,请随时通知我。

标签: android firebase firebase-realtime-database


【解决方案1】:

我认为这可能会对您有所帮助:

reference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        DataSnapshot users = dataSnapshot.child("users");
        int count=0;
        for (DataSnapshot usrchild : users.getChildren()){
           count++;
           if(count == 'Position x variable'){
              DataSnapshot university = usrchild.child("University");
              DataSnapshot age = usrchild.child("Age");
              DataSnapshot City = usrchild.child("City");
              if(!String.valueof(university.getValue()).matches("")){
              //Value is not null
              }
           }
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
    }
});

【讨论】:

  • 好的!谢谢,我明白了。现在我需要将大学设置为文本。如何避免它变为空?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2019-07-24
  • 1970-01-01
  • 2018-02-25
  • 2020-03-28
相关资源
最近更新 更多