首页 > 解决方案 > HashMap 中的项目不按顺序排列

问题描述

我正在从 SQLiteDatabase 填充 Hashmap 中的值,并使用简单适配器在自定义列表视图中显示它们。目标是当单击项目时,它将移动到其他活动并显示项目的详细信息。

public void custNameContact() {
        custDatabase = new CustomerDatabase(this); //It is object of class which extends SQLiteDatabaseHelper

        customersNameList = new ArrayList<String>(); // ArrayList for customers' Name
        customersContactList = new ArrayList<String>(); // ArrayList for customers' Contact

        HashMap<String, String> nameContact = new HashMap<>(); // HashMap in which value fetched to be pass

        Cursor cursorNameContact = custDatabase.customerNameContact();  // fetching data from database. Data is queried such that it will give data ORDERED BY name.

        if (cursorNameContact.getCount() == 0)
        {
            Toast.makeText(this, "No Entry", Toast.LENGTH_SHORT).show();
            return;
        }
        while (cursorNameContact.moveToNext())
        {
            custNameInList = cursorNameContact.getString(0); // To get customers' Name
            customersNameList.add(custNameInList);
            custContactInList = cursorNameContact.getString(1); // To get customers' Contact
            customersContactList.add(custContactInList);

            nameContact.put(custNameInList, custContactInList); // Passing values in HashMap
        }

        List<HashMap<String, String>> listItems = new ArrayList<>();

// 使用 SimpleAdapter 在自定义 listView 布局中显示值

        adapter = new SimpleAdapter(this, listItems, R.layout.listview_item_subitem, new String[]{"Name", "Contact"}, new int[]{R.id.custName, R.id.custContact});

        Iterator it = nameContact.entrySet().iterator();
        while (it.hasNext())
        {
            HashMap<String, String> nameContactMap = new HashMap<>();
            Map.Entry pair = (Map.Entry) it.next();
            nameContactMap.put("Name", pair.getKey().toString());
            nameContactMap.put("Contact", pair.getValue().toString());
            listItems.add(nameContactMap);
        }

        customerListView.setAdapter(adapter);

    }

public void itemInteraction() {
        // Click On Item to View Data
        customerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                custName = customersNameList.get(i);
                Intent viewData = new Intent(getApplicationContext(), ViewShirtDataActivity.class);
                startActivity(viewData);
            }
        });
       }

出现的问题是单击的项目和获取的项目不一样。看起来 ArrayList customerNameList 中的项目按名称排序,但不是 Hashmap 中的项目。

我能做些什么?如果有更好的方法,请建议我

标签: javaandroid-studiohashmapandroid-sqlitesimpleadapter

解决方案


推荐阅读