存储字符串键值对

时间:2017-11-28 10:20:48

标签: java android sharedpreferences

我正在开发一个Android应用程序,应用程序的主要工作是有扫描仪,我必须再次扫描&再次将结果存储在键值对中。

  [
   {
    "0" : "816444014066",
    "1" : "747083010945",
    "2" : "816444010969"
  }
 ]

并且通过API我必须通过数组发送所有扫描结果。 我通过startActivityForResult获取另一个活动的扫描结果.User会一次又一次地扫描,而onActivityResult用户将获得result.i必须将所有结果存储在键值对中,最后通过POST请求按下按钮我有一个按钮必须像上面的代码一样通过数组发送所有扫描结果。

我可以在这里使用HashMap,或者我必须使用共享首选项来存储结果。

// Call Back method  to get the Message form other Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // check if the request code is same as what is passed  here it is 2
        if (requestCode == 2 && data!=null) {
            String message = data.getStringExtra(SCAN_RESULT);
            // textView1.setText(message);
            if(message!= null){
                Log.e("SCAN_RESULT", "" + message);

                //Adding code will be here


              }
        }
    }

9 个答案:

答案 0 :(得分:3)

这是使用hashmap保存键值的示例代码:

HashMap<String, String> data = new HashMap<String, String>();
data.put("key", "value");

或者如果订单对您有用,请使用linkedHashMap:

HashMap<String, String> data = new LinkedHashMap<>();

用法相同;)

答案 1 :(得分:2)

数据结构逻辑:

Hashmaps用于通过其密钥访问内容。

在此示例中,我猜您正在扫描&#39;元组&#39;一个接一个,每个元组与其他元组不同,因此您不需要通过它的密钥访问旧元组。

所以在这里,我建议您创建适合键值对的模型类,并将它们存储在列表中。完成后,您可以推送该列表。

元组的示例模型:

public class KeyValuePair {
    private String key;
    private String value;
    public KeyValuePair(String key, String value) {
        this.key = key;
        this.value = value;
    }
}

要存储的样本列表:

List<KeyValuePair> keyValuePairList = new ArrayList<>();
keyValuePairList.add(new KeyValuePair("0", "816444014066"));
keyValuePairList.add(new KeyValuePair("1", "747083010945"));
keyValuePairList.add(new KeyValuePair("2", "816444010969"));

<强>存储

如果您无法在活动之间传递数据,请查看SQLite。您可以将数据存储在SQLite中,并在需要时获取它。它是一个可在Android设备上运行的脱机数据库。您可以在推送到上游时删除数据。

修改

如果键是订单,您只需使用如下字符串列表:

List<String> keyValuePairList = new ArrayList<>();
keyValuePairList.add("816444014066");
keyValuePairList.add("747083010945");
keyValuePairList.add("816444010969");

答案 2 :(得分:1)

为此,最好使用HashMap存储非持久性数据。您不需要共享首选项,因为您要发布结果,因此不需要持久存储。

这样的事情:

Map <Integer,Integer> myMap = new HashMap<Integer,Integer>();

答案 3 :(得分:1)

如果您需要在应用程序中的其他位置使用扫描结果,我建议您使用SharedPreferences并放置键值对。 否则只需使用HashMap。

建议:如果需要保持键值对的顺序,请使用LinkedHashMap并迭代它。

答案 4 :(得分:1)

使用hashmap存储数据,然后使用Gson将HashMap转换为String,然后将其保存到SharedPrefs

private void hashmaptest()
{
    //create test hashmap
    HashMap<String, String> testHashMap = new     HashMap<String, String>();
testHashMap.put("key1", "value1");
testHashMap.put("key2", "value2");

//convert to string using gson
Gson gson = new Gson();
String hashMapString = gson.toJson(testHashMap);

//save in shared prefs
SharedPreferences prefs = getSharedPreferences("test", MODE_PRIVATE);
prefs.edit().putString("hashString", hashMapString).apply();

//get from shared prefs
String storedHashMapString = prefs.getString("hashString", "oopsDintWork");
java.lang.reflect.Type type = new TypeToken<HashMap<String, String>>(){}.getType();
HashMap<String, String> testHashMap2 = gson.fromJson(storedHashMapString, type);

//use values
String toastString = testHashMap2.get("key1") + " | " + testHashMap2.get("key2");
Toast.makeText(this, toastString, Toast.LENGTH_LONG).show();
}

来源:Saving a hash map into Shared Preferences

答案 5 :(得分:1)

好吧,如果你想保存存储的键值,以防用户关闭应用程序,那么你需要使用以下方法之一:sqllite,file,sharedprefernces。但是如果用户关闭应用程序并重新启动它,那么它将是新的(键值),那么你只需使用这样的HashMap:

Map <Integer,String> hashMap = new HashMap<Integer,String>();

答案 6 :(得分:1)

如果你使用Integer作为键,最好使用SparseArray而不是HashMap,因为它使用原始键存储数据,并且比hashMap更快。

 SparseArray<String> spa = new SparseArray();
 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // check if the request code is same as what is passed  here it is 2
        if (requestCode == 2 && data!=null) {
            String message = data.getStringExtra(SCAN_RESULT);
            // textView1.setText(message);
            if(message!= null){
                //Adding code will be here 
                spa.put(key,value);
              }
        }
    }

答案 7 :(得分:1)

render: (data: any, type: any, row: any, meta) => { return ` <a href="/store' + row.id + '/'+ storeid +'" title="View"> <i class="fa fa-file-text-o"></i> </a> `; } 用于存储小数据,因此我建议您将其存储在SharedPreferences并稍后阅读...(如果您的数据很大)

首先创建File,例如Object,如下所示:

HashMap<String,String>

现在您可以创建这些方法来存储信息:

HashMap<String, String> data = new HashMap<String, String>();
data.put("0", "816444014066");
...

然后,如果你想阅读数据,你只需这样做:

public static synchronized void saveData(Context context, Object object, String filename) {
        try {
            String tempPath = context.getFilesDir() + "/" + filename+ ".bin";
            File file = new File(tempPath);
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
            oos.writeObject(object);
            oos.flush();
            oos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

答案 8 :(得分:1)

扫描结果后,我创建了一个方法,即在HashMap中逐个添加所有扫描结果。

 LinkedHashMap<String, String> data = new LinkedHashMap<String, String>();

  // Call Back method  to get the Message form other Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // check if the request code is same as what is passed  here it is 2
    if (requestCode == 2 && data!=null) {
        String message = data.getStringExtra(SCAN_RESULT);
       if(message!= null){
            Log.e("SCAN_RESULT", "" + message);
            showBarCodeContentDialoig(message);
            storeScanValue(scanResult);
        }
    }
}

onCreate();

的外侧
 private void storeScanValue(String scanResult) {
    count++;
    data.put(String.valueOf(count), scanResult);
    Log.e("Key_Value",""+count);
    Log.e("SIZE",""+data.size());
  }

将结果一个活动发送给另一个:

 Gson gson = new Gson();
    String list = gson.toJson(data);
    Intent intent = new Intent(AdjustInventoryCount.this, AdjustInventory.class);
    intent.putExtra("list", list);
    startActivity(intent);

用于接收之前活动的数据:

String str=  getIntent().getStringExtra("list");
    Gson gson = new Gson();

    Type entityType = new TypeToken< LinkedHashMap<String, String>>(){}.getType();
    data = gson.fromJson(str, entityType);

    String jsonList = gson.toJson(data, LinkedHashMap.class);

    Log.e("list", ""+jsonList);
    Log.e("Size", ""+data.size());

通过这种方式,我获得了存储在LinkedHashMap中的原始序列结果。