如何使用sharedPreferenceputString



我想从另一个活动中使用sharedpreference字符串,但没有传递值,它总是传递默认值?创建变量toast显示inp值,但未传递值

name_next = (Button) findViewById(R.id.name_next);
sp= getSharedPreferences("name_pref",Context.MODE_PRIVATE);
name_next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
inp = nameInput.getText().toString();
SharedPreferences.Editor editor= sp.edit();
editor.putString(inp,nameInput);
editor.commit();
Toast.makeText(com.calmo.name.this,"welcome "+inp,Toast.LENGTH_LONG).show();
Intent intent = new Intent(name.this,MainActivity.class);
startActivity(intent);
}
});```    
**Calling **
**The Value is always returned as error that is default**
```            SharedPreferences sp=getApplicationContext().getSharedPreferences("name_pref",Context.MODE_PRIVATE);
String name_in =sp.getString("inp","Error");
name.setText(name_in);
public class AppSharedPreferences {
public static final String TAG = "AppSharedPreferences";
private static SharedPreferences sharedPref;
private String demo_string = "demo string's key"
public AppSharedPreferences() {
}
public static void init(Context context)
{
if(sharedPref == null)
sharedPref = context.getSharedPreferences(
context.getPackageName(), Activity.MODE_PRIVATE);
}
public static void setDemoString(String demoString) {
Editor prefs = sharedPref.edit();
prefs.putString(demo_string, demoString);
prefs.apply();
}
public static String getDemoString() {
return sharedPref.getString(demo_string, "");
}}

把这个放在你想使用共享首选项的地方:

AppSharedPreferences.init(this);

可以将this交换为activitycontext,具体取决于代码的使用位置。

要设置首选项中的值,请使用以下代码:

AppSharedPreferences.setDemoString("Some Text");

从偏好中获取值:

String text = AppSharedPreferences.getDemoString();

删除inp = nameInput.getText().toString();underonclick和改变editor.putString(inp,nameInput);editor.putString("inp",nameInput.getText().toString());

相关内容

  • 没有找到相关文章

最新更新