|
|
|
import android.content.Context; |
|
import android.content.SharedPreferences; |
|
import android.os.Bundle; |
|
import android.support.v7.app.AppCompatActivity; |
|
import android.text.TextUtils; |
|
|
|
import org.json.JSONArray; |
|
import org.json.JSONException; |
|
|
|
import java.util.ArrayList; |
|
import java.util.List; |
|
|
|
|
|
public class ListToSharedPreferences extends AppCompatActivity { |
|
private SharedPreferences prefs; |
|
|
|
private List<Integer> selectedIntegers = new ArrayList<>(); |
|
|
|
@Override |
|
protected void onCreate(Bundle savedInstanceState) { |
|
super.onCreate(savedInstanceState); |
|
prefs = getSharedPreferences("myprefs", Context.MODE_PRIVATE); |
|
} |
|
|
|
|
|
@Override |
|
protected void onResume() { |
|
super.onResume(); |
|
loadStateFromPrefs(); |
|
} |
|
|
|
@Override |
|
protected void onPause() { |
|
super.onPause(); |
|
storeStateToPrefs(); |
|
} |
|
|
|
private void loadStateFromPrefs() { |
|
if (prefs == null) { |
|
return; |
|
} |
|
|
|
|
|
// read in json array from prefs to fill list |
|
selectedIntegers = new ArrayList<>(); |
|
String jsonArrayString = prefs.getString("selectedIntegers", ""); |
|
if (!TextUtils.isEmpty(jsonArrayString)) { |
|
try { |
|
JSONArray jsonArray = new JSONArray(jsonArrayString); |
|
if (jsonArray.length() > 0) { |
|
for (int i = 0; i < jsonArray.length(); i++) { |
|
Integer integer = jsonArray.getInt(i); |
|
selectedIntegers.add(integer); |
|
} |
|
} |
|
} catch (JSONException e) { |
|
e.printStackTrace(); |
|
} |
|
} |
|
|
|
} |
|
|
|
protected void storeStateToPrefs() { |
|
if (prefs == null) { |
|
return; |
|
} |
|
SharedPreferences.Editor editor = prefs.edit(); |
|
|
|
// store list as jsonarray |
|
JSONArray jsonArray = new JSONArray(); |
|
for (Integer z : selectedIntegers) { |
|
jsonArray.put((int) z); |
|
} |
|
editor.putString("selectedIntegers", jsonArray.toString()); |
|
editor.commit(); |
|
} |
|
} |