I'm creating an app on android studio and I want to store user input into textview even after they close the app. I used SharedPreferences to store, load, and update data, but after I close the app the second time, it does not save the data I stored and instead shows: {}.
Is there a way I can fix this?
My code:
private String getUserName;
listTitle = (TextView)findViewById(R.id.listTitle);
listTitle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View view = getLayoutInflater().inflate(R.layout.input_name_edittext, null);
EditText name = (EditText)view.findViewById(R.id.name);
builder.setView(view)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onClick(DialogInterface dialog, int which) {
String nameInputted = name.getText().toString();
if(nameInputted.chars().filter(ch -> ch != ' ').count() <= 15){
saveName(nameInputted);
listTitle.setText(nameInputted);
}
else{
Toast.makeText(MainActivity.this,
"Name is too long",
Toast.LENGTH_LONG).show();
}
}
});
builder.show();
}
loadName();
updateName();
The methods:
public void saveName(String name) {
SharedPreferences sharedPreferences = getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(HASHMAP_KEY, name);
editor.apply();
}
public void loadName() {
SharedPreferences sharedPreferences = getSharedPreferences(preferenceName, Context.MODE_PRIVATE);
getUserName = sharedPreferences.getString(HASHMAP_KEY, "Name");
}
public void updateName() {
listTitle.setText(getUserName);
}