简体   繁体   中英

How can I get my sharedpreferences to work correctly?

I'm having trouble getting my sharedpreferences to work. I'm trying to load in data from a textbox in another activity into a textview. I don't get any errors, but it keeps returning the default value of "nameKey".

Here is where the data is being entered and saved

public class ActivitySettings extends AppCompatActivity {

 SharedPreferences sharedPreferences;
final String MyPREFERENCES = "MyPrefs";
final String Name = "nameKey";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    final EditText enterName1 = (EditText) findViewById(R.id.enterName1); 
    final EditText enterName2 = (EditText) findViewById(R.id.enterName2); 

    Button btnOK = (Button) findViewById(R.id.btnOK);
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

    btnOK.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String n = enterName1.getText().toString();

    SharedPreferences.Editor editor = preferences.edit();
    editor.putString(Name, n);
    editor.commit();

        }
    });

and here's a different activity where i'm trying to read in the data and set it to a textview

public class ActivityDuel extends AppCompatActivity {

public String getPrefs(String n, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    return preferences.getString(n, "nameKey");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_duel);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    final TextView txtD1 = (TextView) findViewById(R.id.txtD1);
    txtD1.setText(getPrefs("name", this));
}
}

Call like this

 txtD1.setText(getPrefs("nameKey", this));

And your getPrefs() function should like below

public String getPrefs(String n, Context context) {
  SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
  return preferences.getString(n, "");
}

I think it's better to create a class for handle your SharedPreferences and add your key as static string to it and use methods for insert and read. here an example:

SettingProvider.class

public class SettingProvider {

    private static final String SETTING_PROVIDER_NAME = "setting";
    public static final String NAME = "name"
    private SharedPreferences sharedPreferences;

    private static SettingProvider ourInstance;

    private SharedPreferences sharedPreferences;

    private SettingProvider(Context context) {
        if (context == null)
            throw new RuntimeException("context must be valid!");
        this.sharedPreferences = context.getSharedPreferences(SETTING_PROVIDER_NAME, 0);
    }

    public static SettingProvider getInstance(Context context) {
        if (ourInstance == null) {
            ourInstance = new SettingProvider(context);
        }
        return ourInstance;
    }
    public void setName(String name) {
        return this.sharedPreferences.edit().setString(NAME, name).apply();
    }

    public String getName() {
        return this.sharedPreferences.getString(NAME, "");
    }
}

now for use in activity


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_duel);
    SettingProvider.getInstance(this).setName("the name");
    String name = SettingProvider.getInstance(this).getName();
}

I think the issue is that you are saving a shared preferences key of 'Name', so from the field final String Name = "nameKey"; the preferences key is 'nameKey'

Then when you try and get the string out you are using "name" as the lookup key value and as it doesn't exist it gets set to the default of 'nameKey' so I think you need to change this txtD1.setText(getPrefs("name", this)); to txtD1.setText(getPrefs(Name, this));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM