通过此代码填写简单的HashMap
,其定义为
HashMap<Integer, String> complainingList = new HashMap<>();
填写HashMap
for (int p = 0; p < subjects.length(); p++) {
JSONObject subject = subjects.getJSONObject(p);
complainingList.put(subject.getInt("id"), subject.getString("title"));
}
complainingFromPostList.setLayoutManager(new LinearLayoutManager(context));
adapterComplainingItems = new AdapterComplainingItems(context, complainingList);
complainingFromPostList.setAdapter(adapterComplainingItems);
现在我怎样才能获得没有任何循环语句的项目,例如for
,which
?
通过此代码获取项目我得到null:
complainingList.get(0)
我想从hashmap的id
位置获取title
和0
,我在RecyclerView
适配器上使用此解决方案
更新:
public class AdapterComplainingItems extends RecyclerView.Adapter<AdapterComplainingItems.MainViewHolder> {
private LayoutInflater inflater;
private HashMap<Integer, String> modelList;
public AdapterComplainingItems(Context context, HashMap<Integer, String> modelList) {
this.inflater = LayoutInflater.from(context);
this.modelList = modelList;
}
@Override
public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.complaining_list_items, parent, false);
return new MainViewHolder(view);
}
@Override
public void onBindViewHolder(MainViewHolder holder, int position) {
holder.complainingText.setText(modelList.get(position));
}
@Override
public int getItemCount() {
return modelList.size();
}
public HashMap<Integer, String> getModelList() {
return modelList;
}
public void setModelList(HashMap<Integer, String> modelList) {
this.modelList = modelList;
}
class MainViewHolder extends RecyclerView.ViewHolder {
private TextView complainingText;
public MainViewHolder(View itemView) {
super(itemView);
complainingText = (TextView) itemView.findViewById(R.id.complainingText);
}
}
}
答案 0 :(得分:0)
使用
complainingList.get(0)
您正在尝试获取key =0
所在的特定Hashmap键值对。
我相信你想从列表中获得第一个键值对。
您是否从Firebase等数据库获取此数据? 如果是,您可以使用Firebase中的通用类型删除这些循环。
答案 1 :(得分:0)
从此SO Post
您可以使用LinkedHashMap
基本上使用LinkedEntrySet在内部维护其键,这不会正式提供顺序,而是按照使用的插入顺序进行迭代。
然后添加数据并按照下面的说明检索它 -
Map<Integer, String> complainingList = new LinkedHashMap<Integer, String>();
for (int p = 0; p < subjects.length(); p++) {
JSONObject subject = subjects.getJSONObject(p);
complainingList.put(subject.getInt("id"), subject.getString("title"));
}
List<String> complainingArrayList = new ArrayList<String>(complainingList.keySet()); // <== Set to List
complainingFromPostList.setLayoutManager(new LinearLayoutManager(context));
adapterComplainingItems = new AdapterComplainingItems(context, complainingArrayList);
complainingFromPostList.setAdapter(adapterComplainingItems);
System.out.println(complainingArrayList.get(0));