Search code examples
androidhashmap

On the Adapter class How to get key and value from HashMap


On my RecyclerViewAdapter class i'm passing HashMap<String,ArrayList<Custom>> as data, now i want to get key & value for every position but i don't know how i should do this! thanks in advance

public class Main_Recycler_Single_Row extends RecyclerView.Adapter<Main_Recycler_Single_Row.ViewHolder> {



private Context mContext;
private HashMap<String,ArrayList<Products>> dataSet;

public Main_Recycler_Single_Row(Context mContext, HashMap<String,ArrayList<Products>> mDataSet) {
    this.mContext = mContext;
    this.dataSet = mDataSet;

} @Override
public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {

    Map.Entry<String,ArrayList<Products>> entry=(Map.Entry<String,ArrayList<Products>>) dataSet.entrySet();//this line is my problem!


    holder.header.setText(entry.getKey());

    holder.mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.HORIZONTAL,false));
    holder.mRecyclerView.setHasFixedSize(true);
    holder.mRecyclerView.setAdapter(new Main_Recycler_Sinle_Item(mContext,entry.getValue()));

}

Solution

  • If you are trying to get Value from HashMap using position, you also need to maintain Array of keys

    keys = (String[])mDataSet.keySet().toArray();
    

    Your ViewHolder class will look like:

    public Main_Recycler_Single_Row(Context mContext, HashMap<String,ArrayList<Products>> mDataSet) {
        this.mContext = mContext;
        this.dataSet = mDataSet;
        keys = (String[])mDataSet.keySet().toArray();
    
    } @Override
    public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder holder, int position) {
    
        holder.header.setText(keys[position]);
    
        holder.mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.HORIZONTAL,false));
        holder.mRecyclerView.setHasFixedSize(true);
        holder.mRecyclerView.setAdapter(new Main_Recycler_Sinle_Item(mContext,dataSet.get(keys[position])));
    
    }