相关:Save ArrayList to SharedPreferences
我有一个用于输入值的编辑文本,一个用于将其添加到ArrayList
并保存的按钮,一个用于检索和显示该值的按钮,以及一个用于重置ArrayList
的按钮。但是收集按钮会不断显示2。
public class test extends AppCompatActivity {
ArrayList arrayList = new ArrayList();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Button button = findViewById(R.id.create);
Button button1 = findViewById(R.id.recup);
Button button2 = findViewById(R.id.reset);
final EditText editText = findViewById(R.id.editText);
final TextView textView = findViewById(R.id.textView);
//Initialize ArrayList
loadData();
//Button for add variable in arraylist and save
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String nombre = editText.getText().toString();
arrayList.add(nombre);
saveData();
}
});
//Button for look arrayList.get(0)
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView.setText(String.valueOf(arrayList.get(0)));
}
});
//Button for reset
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferencs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("task list");
editor.commit();
}
});
}
//save data
private void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferencs", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString("task list", json);
editor.apply();
}
//load data
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferencs", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList>() {
}.getType();
arrayList = gson.fromJson(json, type);
}
}