2016-11-15 91 views
0
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; 
    public class PlayId { 
private DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference(); 
public String id; 
public String name; 
public String getId() { 
    return id; 
} 
public void setId(String id) { 
    this.id = id; 
} 
public String getName() { 
    return name; 
} 
public void setName(String name) { 
    this.name = name; 
} 
public PlayId() { 
} 
public PlayId(String id, String name) { 
    this.id = id; 
    this.name = name; 
} 
public void writeNewPlayList(String userId,PlayId user) {  mDatabase.child("playlist").child("krikor").child(userId).setValue(user); 
} 
public void read() 
{ 
    ValueEventListener postListener = new ValueEventListener() { 
     @Override 
     public void onDataChange(DataSnapshot dataSnapshot) { 
      // Get Post object and use the values to update the UI 
      PlayId post = dataSnapshot.getValue(PlayId.class); 
      System.out.println(post.getId()+" tatatat "+post.name); 
      } 
      @Override 
     public void onCancelled(DatabaseError databaseError) { 
     } 
    }; 
    mDatabase.addValueEventListener(postListener); 
}} 

簡單地說,當我第一次這樣做時。它首先工作,它存儲播放列表 - > Krikor-> playlistid-> playlistId/playlistName。但是,當我再次調用它時,它會更新數據。我只是想要它存儲新的數據播放列表 - > Krikor->新數據 - >新數據/新數據。什麼是解決方案?Firebase不能正常工作

 PlayId xs = new PlayId(""+playlistId,playlistName); 
     xs.writeNewPlayList(xs.getId(),xs); 

我有第二個問題,我該如何讀取所有存儲的值playlist-> krikor。因爲我可能有播放列表 - >詹姆斯。

回答

3

使用此代碼讀取數值

DatabaseReference databaseReference1 = firebaseDatabase.getReference().child(KEY_METAINGREDIENT) 
      .child(KEY_META_BURGER); 
    final List<Ingredient> burger = new ArrayList<>(); 

    databaseReference1.addValueEventListener(new ValueEventListener() { 
     @Override 
     public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) { 
      burger.clear(); 
      for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) { 
       Ingredient ingredient = dataSnapshot1.getValue(Ingredient.class); 
       burger.add(ingredient); 
      } 
     } 

     @Override 
     public void onCancelled(DatabaseError databaseError) { 

     } 
    });