我是安卓系统的新手。我试图从Database
中获取数据并将其放入HashMap
中。但我遇到了一个小问题。当我尝试放入我得到的数据时,我遇到了一个错误。
我在代码的错误行上加了一条注释。你可以在下面查看
这是我的班级
private static final String TAG_ITEM_NAME = "item_name";
// Hashmap for ListView
ArrayList<HashMap<String, String>> searchlist;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
searchlist = new ArrayList<HashMap<String, String>>();
Intent search = getIntent();
String searchResult = search.getStringExtra("TAG_SEARCH");
DatabaseHandler db = new DatabaseHandler(
List <AllItem> allItems = new ArrayList<AllItem>();
allItems = db.getAllSearchResult(searchResult);
HashMap<String, AllItem> all_Items = new HashMap<String, AllItem>();
for(AllItem cn : allItems) {
String item_name = cn.getItem_name();
//AllItem item_name = all_Items.put(cn.getItem_name(), cn);
all_Items.put(TAG_ITEM_NAME,item_name); // I got error here
}
searchlist.add(all_Items);
ListAdapter adapter = new SimpleAdapter(
Search.this, searchlist,
R.layout.searchlayout, new String[] {TAG_ITEM_NAME},
new int[] { R.id.category_name}
);
// Assign adapter to ListView
listview.setAdapter(adapter);
}
错误表示The Method put(String, Allitem) int type Hashmap<String,Allitem> is not applicable for the argument (String, String)
如何修复此错误?感谢之前:D
all_items接受一个String
和一个AllItem
,但您在这一行中放入了两个String
:
// TAG_ITEM_NAME is a String and item_name is also a String
all_Items.put(TAG_ITEM_NAME,item_name);
您试图将映射作为值字符串,但您将expect映射为值AllItem,因此您必须以这种方式修改代码:
for(AllItem cn : allItems) {
String item_name = cn.getItem_name();
all_Items.put(item_name , cn );
}
此代码将使用与对象名称相等的键将类对象添加到映射中。
all_Items
被定义为哈希映射,包含此处定义的<String, AllItem>
键值对:
HashMap<String, AllItem> all_Items = new HashMap<String, AllItem>();
但您正试图将<String,String>
键值对推送到all_Items
哈希图中:
all_Items.put(TAG_ITEM_NAME,item_name); // I got error here
你似乎想把AllItem
对象推到它的item_name
上,可以这样做:
all_Items.put(item_name, cn);
您的HashMap
如下所示:
HashMap<String, AllItem> all_Items = new HashMap<String, AllItem>();
这意味着它具有String
密钥和AllItem
值。您可以在此HashMap
中放置一个AllItem
对象。
当你写
all_Items.put(TAG_ITEM_NAME,item_name); // I got error here
您将CCD_ 18放入CCD_。
你应该做:
all_Items.put(TAG_ITEM_NAME,cn);
您的哈希图是<String, Allitem>
。当你试着把<String, String>
放进去的时候。
all_Items.put(TAG_ITEM_NAME, item_name);
应该改为
all_Items.put(TAG_ITEM_NAME, cn);
希望你能有所不同。
我在代码中没有看到连接,但根据给定的信息,您的错误可能与代码中的searchlist
变量有关。
更改此项:
ArrayList<HashMap<String, String>> searchlist;
到此:
ArrayList<HashMap<String, AllItem>> searchlist;
这是因为您声明了HashMap<String, AllItem>
,并尝试放置all_Items.put(TAG_ITEM_NAME,item_name); which would probably be HashMap<String, String>()
。