我想制作一个应用程序,基本上用户可以在其中输入一些字符串
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:textColorHint="#ffffff"
app:errorEnabled="true">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/texto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#4249ff"
android:hint="@string/BtnO"
android:textColor="#ffffff" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="confirmInput"
android:text="@string/Btns" />
</LinearLayout>
因此,当用户按下确认按钮时,我希望保存它,但应用程序崩溃了,这是我第一次使用共享首选项,我不太理解它。我没有保存用户的值.此外,我知道我已经使用了提示,但根据我的共享偏好,它将提示更改为文本,而不是保持原样。 这是我的java代码:
public class MainActivity extends AppCompatActivity {
private EditText nameInput;
private EditText homeInput;
private SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs= getSharedPreferences("my_data",MODE_PRIVATE);
String name = prefs.getString("MY_NAME","name");
String home = prefs.getString("MY_HOME","home");
((EditText)findViewById(R.id.texto)).setText(name);
((EditText)findViewById(R.id.textd)).setText(home);
nameInput =(EditText)findViewById(R.id.texto);
nameInput =(EditText)findViewById(R.id.textd);
}
public void copy(View view) {
}
public void confirmInput(View view) {
String name=nameInput.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("MY_NAME",name);
editor.apply();
}
public void confirmInput2(View view) {
String home=homeInput.getText().toString();
SharedPreferences.Editor editor=prefs.edit();
editor.putString("MY_HOME",home);
editor.apply();
}
}
最佳答案
我认为错误是因为有两个 SharedPreferences prefs
声明,一个在 onCreate
方法级别,另一个在类的开头
只需删除首选项声明 onCreate
并使用类开头定义的变量即可修复该错误,如下所示
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Take a look here!
this.prefs= getSharedPreferences("my_data",MODE_PRIVATE);
String name = prefs.getString("MY_NAME","name");
String home = prefs.getString("MY_HOME","home");
((EditText)findViewById(R.id.texto)).setText(name);
((EditText)findViewById(R.id.textd)).setText(home);
nameInput =(EditText)findViewById(R.id.texto);
nameInput =(EditText)findViewById(R.id.textd);
}
关于java - 我想使用共享首选项保存,但应用程序崩溃了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60821237/