问题
For the code below I am trying to retrieve the shared preference, I think it saved correctly but when I go back to the login screen all the data is gone. I need it to remain when I go back to this screen. So i enter name, age and id into three separate lines on the profile page. Then i press the save button Then go to the page before by pressing back on the action bar. And when i go back to the profile page my info should still be there but its not Any help?
package com.example.myprofile;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.sql.Savepoint;
public class Profile extends AppCompatActivity {
protected EditText NameEditText;
protected EditText AgeEditText;
protected EditText IDEditText;
protected Button saveButton;
protected Button settings_id;
String name;
String age;
String id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
EditText mEdit = (EditText) findViewById(R.id.NameEditText);
mEdit.setEnabled(false);
EditText mEdit1 = (EditText) findViewById(R.id.AgeEditText);
mEdit1.setEnabled(false);
EditText mEdit2 = (EditText) findViewById(R.id.IDEditText);
mEdit2.setEnabled(false);
NameEditText = (EditText) findViewById(R.id.NameEditText);
AgeEditText = (EditText) findViewById(R.id.AgeEditText);
IDEditText = (EditText) findViewById(R.id.IDEditText);
settings_id = (Button) findViewById(R.id.settings_id);
saveButton = (Button) findViewById(R.id.SaveButton);
SharedPreferences prefs = getSharedPreferences(getString(R.string.ProfileName), Context.MODE_PRIVATE);
name = prefs.getString("userName", "");
age = prefs.getString("userAge", "");
id = prefs.getString("userID", "");
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = NameEditText.getText().toString();
String age = AgeEditText.getText().toString();
String id = IDEditText.getText().toString();
SharedPreferences sharedPreferences = getSharedPreferences(getString(R.string.ProfileName), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(getString(R.string.ProfileName), name);
editor.putString(getString(R.string.ProfileAge), age);
editor.putString(getString(R.string.ProfileID), id);
editor.apply();
if (Integer.parseInt(age) < 18)
{
Toast toast1 = Toast.makeText(getApplicationContext(), "Invalid Age", Toast.LENGTH_LONG);
toast1.show();
}
else if (!name.isEmpty() && !age.isEmpty() && !id.isEmpty())
{
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Toast toast = Toast.makeText(getApplicationContext(), "Name Saved!", Toast.LENGTH_LONG);
toast.show();
}
else
{
Toast toast2 = Toast.makeText(getApplicationContext(), "Incomplete Info", Toast.LENGTH_LONG);
toast2.show();
}
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings_id:
{
EditText mEdit = (EditText) findViewById(R.id.NameEditText);
mEdit.setEnabled(true);
EditText mEdit1 = (EditText) findViewById(R.id.AgeEditText);
mEdit1.setEnabled(true);
EditText mEdit2 = (EditText) findViewById(R.id.IDEditText);
mEdit2.setEnabled(true);
saveButton.setEnabled(Boolean.parseBoolean("True"));
}
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
回答1:
To save data use the following code sample
name = NameEditText.getText().toString();
age = AgeEditText.getText().toString();
id = IDEditText.getText().toString();
SharedPreferences prefs = getSharedPreferences(
"com.example.myprofile", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("userName", name);
editor.putString("userAge", age);
editor.putString("userID", id);
editor.apply();
To retrieve the data use the following code sample
SharedPreferences prefs = getSharedPreferences(
"com.example.myprofile", Context.MODE_PRIVATE);
name = prefs.getString("userName", "");
age = prefs.getString("userAge", "");
id = prefs.getString("userID", "");
Before onCreate
method
String name;
String age;
String id;
Explanation:
- The first parameter of
getSharedPreferences
is your package name, basically the first line in your code. - You don't need to create multiple
SharedPreferences
instances, one is enough - You don't need to create multiple
SharedPreferences.Editor
instances, one is also enough. - You might not want to use a random
key
, such as the user's username for saving data, since you would then need to pass the key to other activities through intents, and if you are going to do that, why not send the username instead of the key? - Use
editor.apply()
instead ofeditor.commit()
- It is common to save data in
onPause()
and retrieve it inonResume()
, so it can be useful to declare them global, to avoid writing extra lines of code.
回答2:
try (apply() at the end of the line):
editor.putString(getString(R.string.ProfileName), name).apply();
editor1.putString(getString(R.string.ProfileAge), age).apply();
editor2.putString(getString(R.string.ProfileID), id).apply();
回答3:
You are using particular strings ( getString(R.string.ProfileAge) ....)to save data in shared preferences in private mode by using commit() or apply():-
SharedPreferences sharedPreferences1 = getSharedPreferences(getString(R.string.ProfileAge), Context.MODE_PRIVATE);
SharedPreferences sharedPreferences2 = getSharedPreferences(getString(R.string.ProfileID), Context.MODE_PRIVATE);
But you are not trying to get that data using these strings in private mode you have to use :-
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.ProfileAge), Context.MODE_PRIVATE);
String name = sharedPref.getString("key", "defaultValue");
回答4:
For save
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("keyname",true);
editor.putString("keyname","string value");
editor.putInt("keyname","int value");
editor.putFloat("keyname","float value");
editor.putLong("keyname","long value");
editor.commit();
For get
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
pref.getString("keyname",null);
pref.getInt("keyname",0);
pref.getFloat("keyname",0);
pref.getBoolean("keyname",true);
pref.getLong("keyname",0);
For single delete
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.remove("keyname");
editor.commit();
For all delete
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.commit();
回答5:
You can use share preference like this
To save data in preference
SharedPreferences share = getSharedPreferences("Data", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = share.edit();
edit.putLong("user_id", 1);
edit.putString("token","1243434sfdfsf");
edit.commit();
To get data from preference
SharedPreferences share = getSharedPreferences("Data", Context.MODE_PRIVATE);
share.getLong("user_id", 0);
share.getString("token", "");
You can try this link for more details: Shared preference in android
来源:https://stackoverflow.com/questions/54394215/shared-preferences-android-studio