gpt4 book ai didi

java - Android Java - 共享首选项编辑器问题

转载 作者:行者123 更新时间:2023-12-01 13:16:04 24 4
gpt4 key购买 nike

我正在尝试将 3 个不同字符串的值永久存储到共享首选项中。这些字符串肯定包含我通过在 textView 中设置字符串来测试它们的值。

public class verified extends Activity{

SharedPreferences sharedpreferences;
TextView textView100;
String MyPREFERENCES = "MyPreferences" ;

String NString;
String MString;
String EAString;

public static final String MVerified = "";
public static final String NVerified = "";
public static final String EAVerified = "";



public void onCreate(Bundle savedInstanceState)

{
super.onCreate(savedInstanceState);
setContentView(R.layout.verified);

sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

Bundle bundle = getIntent().getExtras();
NString = bundle.getString("NString");
MString = bundle.getString("MString");
EAString = bundle.getString("EAString");

textView100 = (TextView) findViewById(R.id.textView100);

textView100.setText(MString + " , " + NString + " , " + EAString);


Button VCompleteButton = (Button) findViewById(R.id.VCompleteButton);

VCompleteButton.setOnClickListener(new View.OnClickListener()

{
public void onClick(View view)
{



Editor editor = sharedpreferences.edit();
editor.putString(MVerified, MString);
editor.putString(NVerified, NString);
editor.putString(EAVerified, EAString);
editor.commit();


}



});


}



}

但是现在的问题是 EAString 将其值存储在所有三个中。共享首选项。当我在主要 Activity 上执行此操作时。它向我显示了 EAStrin 3 次。

textView2.setText((sharedpreferences.getString(MobileVerified, "")) + " , "+ (sharedpreferences.getString(NameVerified, "")) +  " , "+ (sharedpreferences.getString(EmailAddressVerified, "")));

最佳答案

您从未启动sharedpreferences:

SharedPreferences sharedpreferences;

这就是你在这里得到 NullPointerException 的原因:

Editor editor = sharedpreferences.edit();

在使用 SharedPreferences 之前,在 onCreate 方法中添加类似的内容:

sharedpreferences = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);

这是你的 key :

public static final String MVerified = "";
public static final String NVerified = "";
public static final String EAVerified = "";

每个键都是一个空字符串。您必须为 SharedPreferences 中的每个条目定义一个键:

public static final String MVerified = "key1";
public static final String NVerified = "key2";
public static final String EAVerified = "key3";

否则您将用下一个条目覆盖每个条目...

关于java - Android Java - 共享首选项编辑器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22461375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com