Search code examples
androidfirebasefirebase-realtime-databasefirebaseui

How can i retrieve keys from Firebase and map it to its model instance


How can i retrieve the keys for my database entries and map them to my java objects, so that i can update the content of each individual object in the database? I want to retrieve the "TODO KEY" as represented in the JSON below.

Database

{
  "todos" : {
    "7Y3s5KPhyLU8mR7cbUGNbcnNQ7f1 (USER KEY)" : {
      "-LCddfFC048CowqkTfV1 (TODO KEY)" : {
        "description" : "vhh",
        "title" : "hh"
      },
      "-LCdiAkltHn3Zs47Fdyg" : {
        "description" : "hg5hh",
        "title" : "bcgyi"
      }
    }
  }
}

Android code

mUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
mQuery = FirebaseDatabase.getInstance().getReference().child("todos/" + mUserId);

//Initialize RecyclerView
mRecyclerView = findViewById(R.id.recyclerView);

//Set layout manager for RecyclerView
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

//Initialize options for adapter
FirebaseRecyclerOptions<Todo> options =
        new FirebaseRecyclerOptions.Builder<Todo>()
                .setQuery(mQuery, Todo.class)
                .build();


//Initialize adapter
mAdapter = new FirebaseRecyclerAdapter<Todo, TodoHolder>(options) {
    @Override
    public TodoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // Create a new instance of the ViewHolder, in this case we are using a custom
        // layout called R.layout.message for each item
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item, parent, false);

        return new TodoHolder(view);
    }

    @Override
    protected void onBindViewHolder(TodoHolder holder, int position, Todo todo) {
        // Bind the Chat object to the ChatHolder
        holder.bind(todo);
    }
};


//Connect adapter to recyclerview
mRecyclerView.setAdapter(mAdapter);

Solution

  • To get the key in your onBindViewHolder, you look it up from the adapter based on the position:

    DatabaseReference ref = mAdapter.getReference(position);
    String key = ref.getKey();