java 存储字符串键值对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47529098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Store String Key-value pair
提问by Abhishek kumar
I am developing an android app, the main work of app is there is a scanner and i have to scan again & again and store result in key value pair.
我正在开发一个 android 应用程序,应用程序的主要工作是有一个扫描仪,我必须一次又一次地扫描并将结果存储在键值对中。
[
{
"0" : "816444014066",
"1" : "747083010945",
"2" : "816444010969"
}
]
and by API i have to send all the scan result by array. I am getting scan result by another activity by startActivityForResult.User will scan again and again and by onActivityResult user will get result.i have to store all the result in key value pair and finally there is a button by tap on button by POST request i have to send all the scan result by array like above code.
通过 API,我必须按数组发送所有扫描结果。我正在通过 startActivityForResult.User 获得另一个活动的扫描结果。用户将一次又一次地扫描,通过 onActivityResult 用户将获得结果。我必须将所有结果存储在键值对中,最后通过 POST 请求点击按钮有一个按钮我必须像上面的代码一样通过数组发送所有扫描结果。
Can i use here HashMap or i have to use Shared Preferences for storing result.
我可以在这里使用 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
}
}
}
采纳答案by Abhishek kumar
After scan result i have created a method in i'm adding in HashMap all the scan results one by one.
扫描结果后,我创建了一个方法,将所有扫描结果一一添加到 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);
}
}
}
out side of onCreate();
在 onCreate() 之外;
private void storeScanValue(String scanResult) {
count++;
data.put(String.valueOf(count), scanResult);
Log.e("Key_Value",""+count);
Log.e("SIZE",""+data.size());
}
For sending result one Activity to another:
将结果一个 Activity 发送到另一个:
Gson gson = new Gson();
String list = gson.toJson(data);
Intent intent = new Intent(AdjustInventoryCount.this, AdjustInventory.class);
intent.putExtra("list", list);
startActivity(intent);
for receiving data from previous activity:
从以前的活动接收数据:
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());
By this way i got original sequence wise result as stored in LinkedHashMap.
通过这种方式,我得到了存储在 LinkedHashMap 中的原始序列明智的结果。
回答by SepJaPro2.4
here is the sample code for saving key-values with hashmap :
这是使用 hashmap 保存键值的示例代码:
HashMap<String, String> data = new HashMap<String, String>();
data.put("key", "value");
or if the order matters to you use linkedHashMap :
或者如果订单对您很重要,请使用 linksHashMap :
HashMap<String, String> data = new LinkedHashMap<>();
the usage is the same;)
用法是一样的;)
回答by Bahadir Tasdemir
Data Structure Logic:
数据结构逻辑:
Hashmaps are used to access the content via its key.
哈希映射用于通过其键访问内容。
In this sample, I guess you are scanning 'tuples' one by one and each tuple is different from other, so you won't need to access an old tuple via it's key.
在这个示例中,我猜您正在一个一个地扫描“元组”,并且每个元组都与其他元组不同,因此您不需要通过它的键来访问旧元组。
So here, I suggest you to create the model class suitable for the key-value pairs and store them in a list. You can push that list when you are done.
所以在这里,我建议您创建适合键值对的模型类并将它们存储在列表中。完成后,您可以推送该列表。
Sample model for tuple:
元组的示例模型:
public class KeyValuePair {
private String key;
private String value;
public KeyValuePair(String key, String value) {
this.key = key;
this.value = value;
}
}
Sample List to store:
要存储的示例列表:
List<KeyValuePair> keyValuePairList = new ArrayList<>();
keyValuePairList.add(new KeyValuePair("0", "816444014066"));
keyValuePairList.add(new KeyValuePair("1", "747083010945"));
keyValuePairList.add(new KeyValuePair("2", "816444010969"));
Storing:
储存:
If you cannot pass the data between activities, check out SQLite. You can store the data in SQLite and fetch it when needed. It is an offline database works on Android devices. You can delete the data when pushed to upstream.
如果您无法在活动之间传递数据,请查看SQLite。您可以将数据存储在 SQLite 中并在需要时获取它。它是一个适用于 Android 设备的离线数据库。推送到上游时可以删除数据。
Edit:
编辑:
If the keys are the orders, you can simply use a String List like this:
如果键是订单,您可以简单地使用这样的字符串列表:
List<String> keyValuePairList = new ArrayList<>();
keyValuePairList.add("816444014066");
keyValuePairList.add("747083010945");
keyValuePairList.add("816444010969");
回答by Yamen Nassif
Well, if you want to save the stored key-value in case the user closed the app then you will need to use one of: sqllite, file, sharedprefernces. But if the user closed the app and restart it then its gonna be new (key-value)s then you just simply use HashMap something like this:
好吧,如果您想在用户关闭应用程序的情况下保存存储的键值,那么您将需要使用以下之一:sqllite、文件、共享首选项。但是,如果用户关闭应用程序并重新启动它,那么它将会是新的(键值),那么您只需简单地使用 HashMap 如下所示:
Map <Integer,String> hashMap = new HashMap<Integer,String>();
Map <Integer,String> hashMap = new HashMap<Integer,String>();
回答by jorjSB
For this it's better to use a HashMap to store non-persistent data. You don't need to Shared Preferences since you are posting the results, so no need for persistent storage.
为此,最好使用 HashMap 来存储非持久性数据。由于您正在发布结果,因此您不需要共享首选项,因此不需要持久存储。
Something like this:
像这样的东西:
Map <Integer,Integer> myMap = new HashMap<Integer,Integer>();
回答by dalla92
If you need the scan results somewhere else in your application, I suggest you should use SharedPreferences and put the key value pairs. Otherwise just use a HashMap.
如果您需要应用程序中其他地方的扫描结果,我建议您应该使用 SharedPreferences 并放置键值对。否则只需使用 HashMap。
Suggestion: if you need to keep an order of key value pairs, use LinkedHashMap and iterate over it.
建议:如果您需要保持键值对的顺序,请使用 LinkedHashMap 并对其进行迭代。
回答by Araju
Use hashmap to store the data and then use Gson to convert HashMap to String and then save it to SharedPrefs
使用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();
}
回答by rajan ks
if you are using Integer as key, its better to use SparseArray
over HashMap
as it stores data using primitive keys and will be faster than hashMap.
如果您使用 Integer 作为键,最好使用SparseArray
over,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);
}
}
}
回答by Skizo-oz??S
SharedPreferences
are used to store small data, so I recommend to you to store it on a File
and read it later... (if your data is big)
SharedPreferences
用于存储小数据,所以我建议你把它存储在a上File
,稍后阅读......(如果你的数据很大)
You first create an Object
, for instance a HashMap<String,String>
as follows :
您首先创建一个Object
,例如 aHashMap<String,String>
如下:
HashMap<String, String> data = new HashMap<String, String>();
data.put("0", "816444014066");
...
Now you can create those methods to store the information :
现在您可以创建这些方法来存储信息:
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();
}
}
And then if you want to read the data, you simply do that :
然后如果你想读取数据,你只需这样做:
public static synchronized Object readData(Context context, String filename) {
Object obj = new Object();
try {
String tempPath = context.getFilesDir() + "/" + binFileName + ".bin";
File file = new File(tempPath);
if (file.exists()) {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
obj = ois.readObject();
ois.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}