Abhishek kumar
Abhishek kumar

Reputation: 4445

Store String Key-value pair

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.

  [
   {
    "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.

Can i use here HashMap or i have to use Shared Preferences for storing result.

// 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


              }
        }
    }

Upvotes: 6

Views: 33365

Answers (9)

Bahadir Tasdemir
Bahadir Tasdemir

Reputation: 10793

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.

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");

Upvotes: 7

Abhishek kumar
Abhishek kumar

Reputation: 4445

After scan result i have created a method in i'm adding in HashMap all the scan results one by one.

 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();

 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:

 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.

Upvotes: 1

Skizo-ozᴉʞS ツ
Skizo-ozᴉʞS ツ

Reputation: 20626

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)

You first create an Object, for instance a HashMap<String,String> as follows :

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;
    }

Upvotes: 1

Rajan Kali
Rajan Kali

Reputation: 12953

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.

 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);
              }
        }
    }

Upvotes: 1

Yamen Nassif
Yamen Nassif

Reputation: 2476

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:

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

Upvotes: 2

Araju
Araju

Reputation: 549

Use hashmap to store the data and then use Gson to convert HashMap to String and then save it to 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();
}

Source : Saving a hash map into Shared Preferences

Upvotes: 2

SepJaPro2.4
SepJaPro2.4

Reputation: 635

here is the sample code for saving key-values with hashmap :

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

or if the order matters to you use linkedHashMap :

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

the usage is the same;)

Upvotes: 11

dalla92
dalla92

Reputation: 442

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.

Suggestion: if you need to keep an order of key value pairs, use LinkedHashMap and iterate over it.

Upvotes: 1

jorjSB
jorjSB

Reputation: 610

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.

Something like this:

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

Upvotes: 1

Related Questions