我想在单击按钮时将用户输入保存到SharedPreferences,以便当用户再次启动活动时,用户输入将设置为EditText和TextView。我已经创建了一个sharedPreferences文件,我将一些文本保存到以前的活动中。 我想用我创建的这个新活动的其他细节更新SharedPreferences文件。
这是用于创建和保存到SharedPreferences
的代码viewDidLoad()
这是我将代码首选项的值设置为EditText和TextView
的代码WebDriver test_driver = new FirefoxDriver();
driver.findElement(By.id("element id"))
答案 0 :(得分:1)
File f = new File(PREF_FILE_NAME);
只有偏好的名称
f.exists()
将始终返回false
解决方案:删除
File f = new File(PREF_FILE_NAME);
if (f.exists()){
因为如果你没有任何价值,那么只需使用默认值
@Override
public void onStart(){
super.onStart();
//File f = new File(PREF_FILE_NAME); // not a right path
//if (f.exists()){ // false
idType = prefs.getInt("idType", 0);
idNumber = prefs.getString("idNumber", "");
expiryDate = prefs.getString("expiryDate", "");
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
txtDate = (TextView) findViewById(R.id.txtDate);
txtDate.setText(expiryDate);
edtIdNumber.setText(idNumber);
edtIdNumber.setText(idNumber);
txtDate.setText(expiryDate);
//}
}
或者您可以使用contains
答案 1 :(得分:1)
要实现你的工作: 首先尝试理解android中onCreate()和onStart()方法之间的区别,遵循以下url:https://developer.android.com/guide/components/activities/activity-lifecycle.html - :使用onCreate()方法而不是onStart()来设置ui变量;
其次更改您的代码,如:
public void onClick(View view) {
expiryDate = txtDate.getText().toString();
edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
idNumber = edtIdNumber.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("idType", idType);
editor.putString("idNumber", idNumber);
editor.putString("expiryDate", expiryDate);
editor.commit();
}
答案 2 :(得分:0)
只需从Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnRegister.Click
Dim firstname, lastname, email, mobile, level, currentschool, currenttrack, institution1, institution2, institution3, institution4, institution5, institution6, courses1, courses2, courses3 As String
firstname = txtFName.Text
lastname = txtLName.Text
email = txtEmail.Text
mobile = txtMobile.Text
level = cmbLevel.Text
currentschool = cmbCurrentSchool.Text
currenttrack = cmbCurrentTrack.Text
institution1 = cmbInstitution1.Text
institution2 = cmbInstitution2.Text
institution3 = cmbInstitution3.Text
institution4 = cmbInstitution4.Text
institution5 = cmbInstitution5.Text
institution6 = cmbInstitution6.Text
courses1 = cmbCourse1.Text
courses2 = cmbCourse2.Text
courses3 = cmbCourse3.Text
Using sw As StreamWriter = File.AppendText("C:\Users\jmrosales\Documents\RegistrationForm\Registered.txt")
sw.WriteLine(firstname & "~" & lastname & "~" & email & "~" & mobile & "~" & level & "~" & currentschool & "~" & currenttrack & "~" & institution1 & "~" & institution2 & "~" & institution3 & "~" & institution4 & "~" & institution5 & "~" & institution6 & "~" & courses1 & "~" & courses2 & "~" & courses3)
End Using
MsgBox("Registration Complete!")
End Sub
移除if (f.exists())
条件,因为Onstart()
只有首选项的名称,因此File f = new File(PREF_FILE_NAME);
将始终返回false
,如下面的代码
f.exists()