-2

I have created the example code below to explain myself. I have a few EditText fields that need the data stored as "entries" for later use. My question is, what is the best way to store these three variables to be "listed" in another activity. (liAmount, liAccount, and vID). I was just going to use shared preferences, but even with this, I will have multiple entries on the same EditTexts so I don't really know how to properly serialize them...

float liAmount;
String liAccount;
String vID;

btnSaveLineItem.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if(etLineItemAmount.length() == 0 || etAccountName.length() == 0) {
            Toast.makeText(NewLineActivity.this, "Fill all fields.", Toast.LENGTH_LONG).show();
        } else {
            saveLineItem();
            createVID();
        }

    }
});

public void createVID(){
    vID = String.valueOf(liAccount.charAt(0) + liAccount.charAt(1) + liAccount.charAt(2) + liAmount);
}

public void saveLineItem(){
    liAmount = Float.valueOf(etLineItemAmount.getText().toString());
    liAccount = etAccountName.getText().toString();
}

EDIT: I should clarify, I do want these data files to be stored long-term. These are essentially going to be used in a separate activity file to show a list of all previous entries.

cormeistro
  • 11
  • 4
  • 1
    Possible duplicate of [Save ArrayList to SharedPreferences](https://stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences) – Uma Kanth Jul 04 '17 at 06:43
  • FYI - ther are no best ways, as there is no rating of *bestness*. Everybody uses whatever he likes. This is called *opinion-based*, which is oftopic on the stackoverflow – Vladyslav Matviienko Jul 04 '17 at 06:54

2 Answers2

1

You can use SharedPreferences to store the data with a key value pair and then later retrieve the same when required. Here's a sample code.

Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit(); 

To Get the stored value use something like this

SharedPreferences prefs = getSharedPreferences(this); 
String restoredText = prefs.getString("key", null);
Abhinash
  • 368
  • 2
  • 13
0

You can use your application class for saving data temporarily. Declare a ArrayList if you want to store just a list of strings or a HashMap to store the values as key value pairs. Like this, in your custom application class declare

private ArrayList<String> temp;

public ArrayList<String> getTemp() {
    return temp;
}

public void setTemp(ArrayList<String> temp) {
    this.temp = temp;
}

Then in any activity call ((YourApplication)getActivity()).getTemp() and add or get data from it.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
Sony
  • 7,136
  • 5
  • 45
  • 68