0

I have a shared_preference.xml file Named as Item details like this,

<map>
    <string name="Product A">{"Item Name":&quot;Product A","Item Total":"₹ 58.00"}</string>
    <string name="Product B">{"Item Name":"Product B","Item Total":"₹ 63.00"}</string>
<string name="Product C">{"Item Name":"Product C","Item Total":"₹ 87.00"}</string>
<string name="Product D">{"Item Name":"Product D","Item Total":"₹ 74.00"}</string>
</map>

I want to get all values of Item Total from this shared preference even if i dont know the name of Product. Is there any way to get all the values by just giving the key Item Total.

Code used

private String getItemValue(String ProductName, String ValueName) {
    SharedPreferences Prefs = this.getSharedPreferences("Item details", Context.MODE_PRIVATE);
    Gson gson = new Gson();
    String json = Prefs.getString(ProductName, "");
    java.lang.reflect.Type type = new TypeToken<HashMap<String, Object>>() { }.getType();
    HashMap<String, Object> obj = gson.fromJson(json, type);
    return String.valueOf(obj.get(ValueName));
}
cmak
  • 576
  • 1
  • 4
  • 15
  • 1
    Save all in a json string within a single preference – cmak Feb 28 '22 at 13:58
  • By this I have to give it a product name as Key, i dont want to use product name, can u give me an example brother – Gurdeep Singh Feb 28 '22 at 14:04
  • 1
    Here there's an example. You can convert product list to json https://stackoverflow.com/a/23732670 But if you need sorting (e.g. sorting by price or product name) you may be better off using a sqlite database with an ORM like android room https://stackoverflow.com/a/64539689 – cmak Mar 01 '22 at 13:16

0 Answers0