显示分支键/名称RecyclerView + Firebase

时间:2017-05-09 10:39:36

标签: android firebase firebase-realtime-database android-recyclerview firebaseui

我一直在尝试使用Android上的RecyclerView显示我的所有分支(Firebase)。 这是我的JSON:

"notice" : {
    "notice1" : {
      "subnotice1" : "test1",
      "subnotice2" : "test2",
      "subnotice3" : {
        "test" : "test"
      }
    },
    "notice2" : {
      "subnotice1" : "test3",
      "subnotice2" : "test4"
    },
    "notice3" : {
      "subnotice1" : "test5",
      "subnotice2" : "test6"
    }
  }
}

我想用RecyclerView notice1,notice2,notice3展示,但似乎无法实现。

我该怎么办?

提前致谢

编辑:

private List<String> lista = new ArrayList<>();
private FirebaseRecyclerAdapter adaptador;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    RecyclerView rv = (RecyclerView) findViewById(recyclerView);
    rv.setHasFixedSize(false);
    rv.setLayoutManager(new LinearLayoutManager(this));
    DatabaseReference dbr = FirebaseDatabase.getInstance().getReference().child("compuestos");
    dbr.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            lista.removeAll(lista);
            for (DataSnapshot a : dataSnapshot.getChildren()) {
                Log.d("DIEGO", a.getKey());
                lista.add(a.getKey());
            }
           for(String s: lista){
                Log.d("KOKO", s);
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e("DIEGO", "ERROR", databaseError.toException());
        }
    });

    adaptador = new FirebaseRecyclerAdapter<Datos, Holder>(Datos.class, R.layout.lista_elementos, Holder.class, dbr) {
        @Override
        protected void populateViewHolder(Holder h, Datos d, int position) {               for(String s : lista){
                d.setCampo(s);
                h.setCampo(d.getCampo());
            }

        }
    };
    rv.setAdapter(adaptador);
}

1 个答案:

答案 0 :(得分:0)

<强>解: 我意识到我必须将键保存在ArrayList上,稍后只需要显示它:

private ArrayList<String> keys = new ArrayList<String>();
//...

 ChildEventListener childEventListener = new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            keys.add(dataSnapshot.getKey());
        }

在适配器中:

mAdapter =
            new FirebaseRecyclerAdapter<Trabajo, TrabajoHolder>(Trabajo.class,R.layout.lista_trabajos ,TrabajoHolder.class, dbAvisos) {
                @Override
                protected void populateViewHolder(TrabajoHolder viewHolder, Trabajo model, int position) {
                        viewHolder.setKey(keys.get(position));
                }
            };

通过这种方式&#34; populateViewHolder&#34;将通过RecyclerView显示我们在Array上的所有键。

我希望有用。