简体   繁体   中英

How to use HashMap data in RecyclerView?

I count the same value with HashMap (says hasmap ), but how to display key and value of the HashMap in RecyclerView ?

HashMap<String, Integer> hasmap = new HashMap<>();
for (int i = 0; i < data.length(); i++){
    JSONObject List_data_kecamatan = data.getJSONObject(i);

    String nama_kecamatan = List_data_kecamatan.getString("dapil_kecamatan");

    int count = 0;
    if (hasmap.containsKey(nama_kecamatan)){
        count = hasmap.get(nama_kecamatan)+1;
        hasmap.put(nama_kecamatan, count);
    }else {
        hasmap.put(nama_kecamatan, 1);
    }

}

I Using JSON Object as key in hasmap .

Thinking something like:

public class MyRVAdapter extends RecyclerView.Adapter<MyViewHolder> {

    private HashMap<String, String> mData;
    private ArrayList<Pair<String, String>> mActualData;

    public MyRVAdapter(HashMap<String, String> mData) {
        this.mData = mData;
        mActualData = new ArrayList<>(mData.size());
        mData.forEach((s, s2) -> mActualData.add(new Pair<>(s, s2)));
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        TextView v = (TextView) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.my_text_view, holder, false);

        return new MyViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        holder.mTextView.setText(
                String.format("%s - %s", mActualData.get(position).first, mActualData.get(position).second)
        );
    }

    @Override
    public int getItemCount() {
        return mActualData.size();
    }
}

public class MyViewHolder extends RecyclerView.ViewHolder {

    TextView mTextView;
    public MyViewHolder(@NonNull View itemView) {
        super(itemView);
        mTextView = (TextView)itemView;
    }
}

So this will convert the HashMap into an ArrayList of Key Value Pairs (the .forEach will only work on API 24+; swap out with an Iterator if you need lower version support).

You would then use the setAdapter method for the RecyclerView in your layout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM