Firebase Android - 将数据对象保存到用户ID

时间:2018-01-22 18:55:49

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

我尝试在用户ID下保存用户数据。

现在,我可以根据"锻炼"保存信息。另外一个关于"锻炼细节"。细节保存在"锻炼" id所以它的连接。

我要做的是将数据保存在使用Google登录信息创建的唯一用户ID下。

因此,当用户保存详细信息时,他/她现在只能看到自己的详细信息。我确实有正常的Firebase数据库规则设置。



private  void addWorkout(){
        String name = editTextName.getText().toString().trim();
        String category = spinnerCategory.getSelectedItem().toString();

        //if name not empty we save it to firebase db
        if(!TextUtils.isEmpty(name)){

            //make it so it saves under the user ID
            FirebaseUser user = firebaseAuth.getCurrentUser();

            //create a unique id for workout to save in firebase

            String id =databaseWorkouts.push().getKey();

            Workout workout = new Workout(id, name, category );

            //set value method to save in firebase db
            databaseWorkouts.child(id).setValue(workout);

            Toast.makeText(this, "Workout added", Toast.LENGTH_LONG).show();
            editTextName.setText("");




2 个答案:

答案 0 :(得分:0)

首先需要拥有数据库中的用户ID和StorageReference

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

if (user == null) {
    // No session user
    return;
}

// In this example is QMvzmlCksCPgFSpuVNxwBuVBvaA2

String userId = user.getUid();

//Example you need save a Store in 
FirebaseDatabase database = FirebaseDatabase.getInstance();

DatabaseReference stores = database.getReference("stores");

stores.child(userId).push().setValue(store);

其中store是您需要保存的类。

Store store= new Store();

public class Store {

public String url;
public String username;
public String password;
public String image;
public String name;

public Store() {
}

public Store(String url, String username, String password, String image, String name) {
    this.url = url;
    this.username = username;
    this.password = password;
    this.image = image;
    this.name = name;
}

}

最后,您将拥有Firebase数据库 Example saved store data in Firebase Database

注意:如果您不想要列表数据,可以省略.push()

答案 1 :(得分:0)

要解决此问题,请使用push()方法提供的uid来代替使用FirebaseUser方法提供的随机生成密钥:

String id = user.getUid();
Workout workout = new Workout(id, name, category);
databaseWorkouts.child(id).setValue(workout);
Toast.makeText(this, "Workout added", Toast.LENGTH_LONG).show();
editTextName.setText("");