2017-11-05 12 views
-1

私はsimple_list_item_multiple_choiceを使用しているリストビューとarrayadapterで作業していますので、リストビューで複数の項目を選択できます。Android - HashMapでupdateChildren()を使用

私がしたいこと:選択したすべてのアイテムをFirebaseデータベースに挿入します。そのために、私はハッシュマップを使用しています。私はを行っている何

addUsersButton.setOnClickListener(new View.OnClickListener() { 
     HashMap<String, Object> drivers = new HashMap<>(); 
     @Override 
     public void onClick(View v) { 
      int cntChoice = userList.getCount(); 
      SparseBooleanArray sparseBooleanArray = userList.getCheckedItemPositions(); 

      for (int i = 0; i < cntChoice; i++) { 
       if (sparseBooleanArray.get(i)) { 
        drivers.put("drivers", userList.getItemAtPosition(i).toString()); 
       } 

      } 
      userRef.child(sharedPreferences.getString("school", null)).child("routes").child(key).updateChildren(drivers); 


     } 
    }); 

問題:これは、データベースへの選択した項目の一つ追加されます。どうしてか分かりません。選択した項目の各反復で

+0

別のものを選択すると、データベースの項目が上書きされますか? –

+0

はい、アイテムが上書きされています。したがって、どれだけ選択しても、データを上書きするため、データベースに1つしか表示されません。 – JDoe

+0

updateChildren()のためのオーバーライド –

答えて

1

、あなたが呼んでいる:

指定された位置にある項目と HashMap"drivers"値を上書きします
drivers.put("drivers", userList.getItemAtPosition(i).toString()); 

を、そのため、あなたのHashMapは今までで1つの項目が含まれています"drivers"のキー。これは、HashMap keys are unique and calling put() replaces the previous value associated with the given key if it already existsです。

したがって、あなたはユニークなIDでHashMapに各項目を追加して、代わりにdrivers子ノードにupdateChildren()を呼び出す必要があります:

addUsersButton.setOnClickListener(new View.OnClickListener() { 
    HashMap<String, Object> drivers = new HashMap<>(); 
    @Override 
    public void onClick(View v) { 
     int cntChoice = userList.getCount(); 
     SparseBooleanArray sparseBooleanArray = userList.getCheckedItemPositions(); 

     for (int i = 0; i < cntChoice; i++) { 
      if (sparseBooleanArray.get(i)) { 
       String uniqueId = usersRef.push().getKey(); // this doesn't actually push any data to the database 
       drivers.put(uniqueId, userList.getItemAtPosition(i).toString()); // use the unique ID to add to the HashMap 
      } 
     } 
     userRef.child(sharedPreferences.getString("school", null)) 
      .child("routes") 
      .child(key) 
      .child("drivers") // specify "drivers" child node here 
      .updateChildren(drivers); 
    } 
}); 

この方法で、各項目はHashMapに追加されます一意のIDでこのHashMapが子ノードdriversにプッシュされます。

+0

パーフェクト、これは動作します:)ありがとう – JDoe

関連する問題