2017-03-19 2 views
1

코멘트를 저장할 오브젝트 배열이 있습니다. 올바른 postid을 찾고 사용자가 주석을 남길 때마다 해당 배열에 새 객체를 삽입하고 싶습니다.Firebase에서 객체 배열을 업데이트하는 방법은 무엇입니까?

스키마

"comments" : { 
    "-KfXyMUIqsiPGElax098" : { 
    "comments" : [ { 
     "author" : "s123456", 
     "comment" : "This is the first comment." 
     } ], 
    "postid" : "-KfSToVpsWUecTL_tmlh" 
    } 
} 

모델

public class CommentNew { 

String author; 
String comment; 

public CommentNew() {} 

public CommentNew(String author, String comment) { 
    this.author = author; 
    this.comment = comment;} 

public String getAuthor() { 
    return author;} 

public void setAuthor(String author) { 
    this.author = author;} 

public String getComment() { 
    return comment;} 

public void setComment(String comment) { 
    this.comment = comment;} 
} 

코드 내가 올바른 postid 발견,하지만 어떻게 내가 배열에 새 개체를 추가 할 수 있습니다

?

public void saveComment(String postIdKey, final CommentNew commentNew) { 
    Query queryRef = mFirebase.child("comments").orderByChild("postid").equalTo(postIdKey); 
    queryRef.addListenerForSingleValueEvent(new ValueEventListener() { 
     @Override 
     public void onDataChange(DataSnapshot dataSnapshot) { 
      for (DataSnapshot snapshot: dataSnapshot.getChildren()) { 
       String key = snapshot.getKey(); 
       String path = "comments/" + key + "/comments"; 
       List comment = new ArrayList<CommentNew>(Arrays.asList(commentNew)); 
       Map<String, Object> result = new HashMap<String, Object>(); 
       result.put("comments", commentNew); 
       mFirebase.child(path).updateChildren(result); 
      } 
     } 
     @Override 
     public void onCancelled(FirebaseError firebaseError) { 

     } 
    }); 
} 
+0

'CommentNew' 클래스를 정의하십시오. – RamithDR

+0

@RamithDR'CommentNew' 클래스를 게시합니다. – David

+0

수업을 게시 해 주셔서 감사합니다. 내 대답 아래에 포함 된 솔루션을보십시오. – RamithDR

답변

0

경로는 데이터를 업데이트하는 데 적합하지만 몇 단계가 누락되었습니다.

1 단계 :

귀하의 CommentNew 클래스는 HashMap에 CommentNew 개체를 변환하는 방법을 포함해야합니다.

public class CommentNew { 

String author; 
String comment; 

public CommentNew() {} 

public CommentNew(String author, String comment) { 
    this.author = author; 
    this.comment = comment;} 

public String getAuthor() { 
    return author;} 

public void setAuthor(String author) { 
    this.author = author;} 

public String getComment() { 
    return comment;} 

public void setComment(String comment) { 
    this.comment = comment;} 

//converts an object of CommentNew to a HashMap 
@Exclude 
public Map<String, Object> toMap() { 

    HashMap<String, Object> result = new HashMap<>(); 
    result.put("author", getAuthor()); 
    result.put("comment", getComment()); 

    return result; 
} 

} 

2 단계 :

변경 다음 onDataChange의 코드 : 같은

@Override 
public void onDataChange(DataSnapshot dataSnapshot) { 
    for (DataSnapshot snapshot: dataSnapshot.getChildren()) { 

     String key = snapshot.getKey();  
     String path = "comments/" + key + "/comments"; 

     Map<String, Object> updatedComment = commentNew.toMap(); 
     Map<String, Object> childUpdate = new HashMap<>(); 
     childUpdate.put(path, updatedComment); 

     mFirebase.updateChildren(childUpdate); 
    } 
} 

두 HashMaps을 사용 하였다 볼 수 있듯이, 최초의 HashMap는 데 사용됩니다 CommentNew 개체의 업데이트 된 특성 목록을 저장하고 두 번째 HashMap에는 자식이 업데이트해야하는 경로 + 업데이트 된 데이터가 포함됩니다.

임의로 updateChildren 메서드에 OnCompleteListener을 추가하고 주석이 성공적으로 업데이트되었거나 원하는 것으로 사용자에게 토스트를 제공 할 수 있습니다.

추가 읽기 : 당신이 더 해명을해야하는 경우 Update specific fields

HTH는, 아래에 의견을;

+0

이것은 작동하지 않습니다. 'CommentNew' 모델은 배열로 저장되기 때문에. http://i.imgur.com/mQyv91j.png를보십시오. 이전 데이터는 새로운 데이터로 대체됩니다. – David

+0

배열을 저장하는 것은 좋은 생각이 아닙니다. 아마도, 구조를 변경해야합니다. – David

+0

@David 사실, 중첩 된 데이터를 유지하는 것이 더 어렵습니다. 프로젝트 시나리오로 질문을 업데이트 할 수 있다면 데이터베이스 구조를 도울 수 있습니다. – RamithDR

관련 문제