1

I have the current onBindViewHolder function:

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    myHolder = holder;    
    //Here I need to set text ("Hello" and "World") to myHolder.itemTextView.setText(text);
}

Assuming my dataset is a HashMap called myDataset: If I have the position, how do I get the key and value?

This is how I first set the data in the activity:

mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
myDataset = new HashMap<>();

myDataset.put("key1", "Hello");
myDataset.put("key2", "World");


mAdapter = new HashMapAdapter(myDataset);
mRecyclerView.setAdapter(mAdapter);

Or, if I'm using HashMap, there should be a different way that's not based on position?

pileup
  • 1
  • 2
  • 18
  • 45

2 Answers2

2

It will be difficult if you use the map as the data source. I recommend to convert from map to arraylist first and then install it on the adapter. Why? because its POSITION is not guaranteed to be accurate at all. , but if you keep want to use map probably it will be like this:

@Override
        public void onBindViewHolder(MyViewHolder holder, int position) {

            int i = 0;
            for (Map.Entry<String, String> entry : myDataset.entrySet()) {
                if(position == i){
                    String key = entry.getKey();
                    String value = entry.getValue();

                    // print your hello word here
                    break;
                }
                i++;
            }
        }

I say again do not use maps, use the List so that the data obtained is in correct order

Nanda Z
  • 1,604
  • 4
  • 15
  • 37
  • How to convert HashMap to ArrayList? – pileup Dec 29 '18 at 16:58
  • Determine your Model first then use Gson or something like that. Its simple, you can figure out google. [Sample1](https://stackoverflow.com/questions/20677492/gson-parsing-from-list-of-maps-how) or [Sample2](https://stackoverflow.com/questions/1026723/how-to-convert-a-map-to-list-in-java) – Nanda Z Dec 30 '18 at 02:04
0

you can convert your HashMap to an Iterator object like this :

Iterator it = myDataset.entrySet().iterator();

and then iterate throw your iterator value to get your position like this:

    int p = 0;
    while (it.hasNext()) {
        if (p == position) {
            Map.Entry pair = (Map.Entry) it.next();
            System.out.println(pair.getKey() + " = " + pair.getValue());
            break;
        }

        p++;
    }
Ali Samawi
  • 1,079
  • 1
  • 9
  • 18