6

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


              }
        }
    }
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Abhishek kumar
  • 4,347
  • 8
  • 29
  • 44

9 Answers9

11

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

SepJaPro2.4
  • 704
  • 9
  • 19
7

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");
Bahadir Tasdemir
  • 10,325
  • 4
  • 49
  • 61
  • But in my case automatically i have to set key first time "1" second time "2", only i will add scan result. – Abhishek kumar Nov 28 '17 at 10:39
  • So You can create a List of Strings and sore the string data in it. LinkedList will keep it in order and you can get them one by one or the index number from the list. – Bahadir Tasdemir Nov 28 '17 at 10:40
  • There must be a common (core java) class that does key/value pair. In JavaFX I think there is a class called Pair, what about in core java? java.utils.Pair or something. Or maybe Map.Entry is good enough? – Alexander Mills Feb 04 '19 at 05:23
2

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

Araju
  • 539
  • 8
  • 20
2

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

Yamen Nassif
  • 2,416
  • 2
  • 24
  • 48
1

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>();
jorjSB
  • 610
  • 4
  • 12
1

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.

dalla92
  • 432
  • 2
  • 8
1

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);
              }
        }
    }
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37
1

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;
    }
Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
1

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.

Abhishek kumar
  • 4,347
  • 8
  • 29
  • 44