如何解决如何使用sharedPrefrence putString?
我想在其他活动中使用sharedprefrence字符串,但是没有传递值,它总是传递默认值吗? 创建可变吐司显示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);
解决方法
删除
inp = nameInput.getText().toString();
在onclick下
并改变
editor.putString(inp,nameInput);
至
editor.putString("inp",nameInput.getText().toString());
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
换成activity
或context
,这取决于您在哪里使用代码。
要优先设置值,请使用以下代码:
AppSharedPreferences.setDemoString("Some Text");
要从首选项中获取值:
String text = AppSharedPreferences.getDemoString();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。