@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mood);
databaseAtrtists = FirebaseDatabase.getInstance().getReference("Artists");
editTextName = (EditText) findViewById(R.id.editTextName);
buttonAdd = (Button) findViewById(R.id.buttonAddArtist);
spinnerGenres = (Spinner) findViewById(R.id.spinnerGenres);
spinnerEmo = (Spinner) findViewById(R.id.spinnerEmo);
buttonTips = (Button) findViewById(R.id.buttonTips);
listViewArtists = (ListView) findViewById(R.id.listViewArtist);
listMood = new ArrayList<>();
mRemoveButton = (Button) findViewById(R.id.removeButton);
buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addAtrist();
}
});
mRemoveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
databaseAtrtists.removeValue();
}
});
}
private void configureTipsButton() {
final Button buttonTips = (Button) findViewById(R.id.buttonTips);
buttonTips.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(Mood.this, MoodsTips.class));
}
});
}
@Override
protected void onStart() {
super.onStart();
databaseAtrtists.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
listMood.clear();
for (DataSnapshot artistSnapshot : dataSnapshot.getChildren()) {
MindYourMood level = artistSnapshot.getValue(MindYourMood.class);
listMood.add(level);
}
MoodLists adaptor = new MoodLists(Mood.this, listMood);
listViewArtists.setAdapter(adaptor);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void addAtrist() {
String name = editTextName.getText().toString().trim();
String emotion = spinnerEmo.getSelectedItem().toString();
String genre = spinnerGenres.getSelectedItem().toString();
if (!TextUtils.isEmpty(name)) {
String id = databaseAtrtists.push().getKey();
MindYourMood level = new MindYourMood(id, name, emotion, genre);
databaseAtrtists.child(id).setValue(level);
Toast.makeText(this, "Emotion Added", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Enter a date", Toast.LENGTH_SHORT).show();
}
}
上面是我的代码,允许用户将数据输入到Firebase数据库中。它保存数据,以便当前登录的用户可以查看它。但是,我的问题是,它不会仅为登录用户保存数据。每当我与其他用户登录时,它都会显示相同的输入数据。
我对如何解决此问题感到困惑。
任何帮助都会有所帮助。
*注意-我是否需要在主活动文件上进行设置,还是为每个单独的类文件使用一些代码,以确保其特定于当前登录的用户?
答案 0 :(得分:0)
您需要使用此数据库:
Artists
userId
artistName: "userX"
artistEmail: "userx@gmail.com"
userId
artistName: "userY"
artistEmail: "usery@gmail.com"
用户登录后,您可以检索其唯一的用户ID,并仅在该ID下保存数据:
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String userId=user.getUid();
DatabaseReference ref=FirebaseDatabase.getInstance().getReference("Artists").child(userId);
ref.child("artistName").setValue("userZ");
ref.child("artistEmail").setValue("userZ@gmail.com");
这里有一个新用户登录,他的数据仅在其ID下保存在数据库中。