简体   繁体   中英

Save a list of values from a user to storage then display them in a list

I am creating an app that will convert a user input then display it in a TextView . But what I need to do is display the last 5 conversions. So I'm trying to figure out a way to do so. Would the best way be to get the user's input then store the input into some type of this and position it? I'm new to this so I might be completely wrong, if so can someone please tell me another route to go about this. The code below is the code for getting the users input then converting it and adding it to the TextView but I need it to be stored so I can have the last 5 conversions displayed

if (copper1Pressed && copper2Pressed) {
    convertedCost.setText("Converted cost: " + convert);

    myList.add(editText.getText().toString());
    myList.add(convertedCost.getText().toString());
    editText.setText("");
    String string1 = "Copper";
    String string2 = "Copper";
    for(String edit : myList) {
        edit = (string1 + " " + myList.get(0) + " = " + string2 + " " + myList.get(1));
        txtList.setText(edit);
    }
}

Unfortunately, SharedPreferences does not provide an easy way to store an ordered list. A 'standard' Android developer trick is to use a JSON array instead:

To Save:

final JSONArray array = new JSONArray();
array.put("string1");
array.put("string2");
final String jsonString = array.toString();
sharedPreferences.edit().put("data", jsonString).apply();

The value of jsonString stored in SharedPreferences is:

(string1,string2)

To Retrieve:

final String stringData = sharedPreferences.getString("data");
final JSONArray jsonArray = new JSONArray(stringData);
final String string1 = jsonArray.getString(0);
final String string2 = jsonArray.getString(1);

I'm assuming myList is of type List<String> , it should be possible to convert it directly into a JSONArray using the following constructor:

JSONArray(Collection copyFrom)

Sorry I am not in front of my computer or I would try it myself...

This is a simple example, but you could also store an array of JSONObject strings for example if you decide to associate another piece of data with your chat message, perhaps the timestamp.

But for a real commercial product, you should generally use a DB rather than storing JSONObjects as strings in SharedPreferences since you will probably want to run efficient queries on the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM