在我的主要活动中,我正在查看变量,如果变量包含一个字符串(“示例字符串”),那么它将进入主屏幕。如果变量不包含任何内容(“”),它会将它们重定向到一个页面,在那里他们可以通过editText
输入值,然后永久存储它。因此,下次他们打开应用程序时,它将具有此永久字符串(直到应用程序被删除),因此它将进入主屏幕。
从研究中我了解到我可能不得不使用共享首选项。我已经尝试了这个,我想我做的不对。
请有人用一个代码示例来说明我发布的代码需要做些什么。
MainActivity.class
//this class uses the string, to see if its blank or contains a string
public class MainActivity extends Activity {
public static final String Verified = ""; //Originally comes blank
private EditText NumberET; //editText for user to enter a string
//the string verified is used in the main activity to determine which xml file to open.
Verified.class
// this is the class used to enter the string and permanently store it
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.verified);
Button VerifyCompleteButton = (Button) findViewById(R.id.VerifyCompleteButton);
VerifyCompleteButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String Verified;
String Number;
Bundle bundle = getIntent().getExtras();
Verified = bundle.getString("Verified");
NumberString = bundle.getString("NumberString")
Verified = NumberString.toString(); //set String Verified permenantly
}
});
答案 0 :(得分:0)
可以在Google's Android developer website上找到使用SharedPreference的好例子。
保存数据:
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY", "VALUE");
editor.commit();
获取数据:
SharedPreferences sharedPref = context.getPreferences(Context.MODE_PRIVATE);
String savedValue = context.getString("KEY", "");
要照顾的事情:
答案 1 :(得分:0)
您可以这样使用,与上述答案非常相似 用于保存字符串
SharedPreferences sharedPref = getSharedPreferences("App_Name_Prefs",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Verified", Verified);
editor.commit();
获取字符串
SharedPreferences shared = getSharedPreferences("App_Name_Prefs",
Context.MODE_PRIVATE);
String keyReturn = shared.getString(key, "");
Log.d("return value" , "Verified is " + verified);