gpt4 book ai didi

android - 在模型 Firebase 上保存 userId

转载 作者:太空狗 更新时间:2023-10-29 16:28:59 25 4
gpt4 key购买 nike

我有一个关于如何使用 firebase 保存用户信息的问题。我扩展了用户身份验证并在 json 树上与用户创建了一个新节点,每个用户都有自己的 id,由 firebase 生成,用户信息在该 key /id 中。问题是,每次我这样做时:

myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

User user = snapshot.getValue(User.class);

if (number.equals(String.valueOf(user.getPhone()))) {
Log.d("here", "i entered");
key = snapshot.getKey();
userFriend = user;
}


}

我将用户信息映射到我的代码中的用户模型中的那个 key 中,但在我的项目的后续步骤中,我也需要为特定用户提供 key 。在这里,我只是在没有 key 的情况下映射用户信息。有没有一种方法可以在我的模型中添加一个字符串 id 并自动将键添加到该 id 字段?

用户模型

package com.esmad.pdm.friendlymanager.model;

import java.util.ArrayList;


public class User {

private String id;
private String username;
private int age = -1;
private String phone;
private int gamesPlayed = 0;
private ArrayList<User> FriendList = new ArrayList<User>();

// CONSTRUCTOR
public User() {

}

public User(String username) {
this.username = username;
}

// GETTERS & SETTERS
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }

public User(String id, String username, int age, String phone, int gamesPlayed, ArrayList<User> users) {
this.username = username;
this.age = age;
this.phone = phone;
this.gamesPlayed = gamesPlayed;
this.FriendList = users;
}



public int getAge() { return age; }
public void setAge(int age) { this.age = age; }

public String getPhone() { return phone; }
public void setPhone(String phone) { this.phone = phone; }

public int getGamesPlayed() { return gamesPlayed; }
public void setGamesPlayed(int gamesPlayed) { this.gamesPlayed = gamesPlayed; }

public ArrayList<User> getUsers() { return FriendList; }
public void setUsers(ArrayList<User> users) { this.FriendList = users; }
}

最佳答案

当您调用snapshot.getValue(User.class)时,无法获取自动注入(inject)的快照的 key 。

但是您可以轻松地添加一个额外的调用,将 key 添加到 User 对象。您首先需要为 id 添加一个 getter 和 setter 到您的 User 类:

@Exclude
public String getId() { return id; }
@Exclude
public void setId(String id) { this.id = id; }

您可能已经注意到我用 @Exclude 注释了这些。这告诉数据库客户端在读取/写入数据库时​​忽略这些属性。如果没有注释,您还会在数据库中的每个用户节点中获得一个 id 属性。

现在您可以在读取属性值时简单地设置和获取 key :

public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
user.setId(snapshot.getKey());
System.out.println(user.getId());
}
}

在上面的代码 fragment 中,snapshot.getValue(User.class) 获取了一个具有所有常规属性的用户对象,然后是 user.setId(snapshot.getKey()) 将 key 添加到该对象。

当写回数据库时,您还可以使用 user.getId() 来确定写到哪里:

ref.child(user.getId()).setValue(user);

关于android - 在模型 Firebase 上保存 userId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43705871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com