简体   繁体   English

如何存储HashMap <Integer,ArrayList<String> &gt;到SQLite?

[英]How to Store HashMap<Integer,ArrayList<String>> to SQLite?

I have to store the HashMap value on SQLite with Keyset and reuse when application is restart using shared preference. 我必须使用Keyset将HashMap值存储在SQLite上,并在使用共享首选项重新启动应用程序时重用。

HashMap<Integer, ArrayList<String>> hashMap;
hashMap = new HashMap<>();
//Insert Value
hashMap.put(btn.getId(), listValue);
// Read a Value
Map.Entry<Integer, ArrayList<String>> entry = (Map.Entry<Integer,   ArrayList<String>>) iteratorMap.next();

for (Integer ihashId :hashMap.keySet()) {
    if( btnid == ihashId)
     {
       Set<Map.Entry<Integer, ArrayList<String>>> setMap = hashMap.entrySet();
       Iterator<Map.Entry<Integer,  ArrayList<String>>> iteratorMap =  setMap.iterator();
       while (iteratorMap.hasNext()) {
             Map.Entry<Integer, ArrayList<String>> entry = (Map.Entry<Integer, ArrayList<String>>) iteratorMap.next();
             ArrayList<String> values = entry.getValue();
             if (btnId == entry.getKey()) {
               getSetName.setText(values.get(0));
               getSetAddress.setText(values.get(1));
               getSetPin.setText(values.get(2));
               getSetValue.setText(values.get(3));
        }
    }

 }

Original Answer Before Question Edited: 问题编辑前的原始答案:
HashMap is already serialized so you can store the HashMap directly on your sqlite database as a BLOB. HashMap已经序列化,因此您可以将HashMap作为BLOB直接存储在sqlite数据库中。 Although you won't be able to read it's content until you de-serialize it. 虽然在对其进行反序列化之前,您将无法阅读其内容。

EDIT: 编辑:
You should put long running operations inside an async task. 您应该将长时间运行的操作放在异步任务中。 If you want the the reference to your variables to survive configuration changes, you should use a fragment and use setRetainInstance(true) although regardless of keeping your reference to the AsyncTask, it is independent of the UI thread and will keep running. 如果您希望对变量的引用在配置更改后继续存在,则应使用片段并使用setRetainInstance(true)但无论是否保留对AsyncTask的引用,它都独立于UI线程并将继续运行。

SIDE NOTE: 边注:
Always use manually counted loop when using ArrayList as it has better performance. 使用ArrayList时始终使用手动计数循环,因为它具有更好的性能。

As seen in this comparison , using for loop with counter set to the size of the array is significantly faster than for each loop: 如此比较所示 ,使用具有设置为数组大小的计数器的for循环比每个循环快得多:

private static List<Integer> list = new ArrayList<>();
for(int j = list.size(); j > size ; j--)
{
    //do stuff
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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