java - 我想以共享偏好保存,但应用程序崩溃
问题描述
我想制作一个基本上用户输入一些字符串的应用程序
<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();
}
}
解决方案
只需做这个小改动:
prefs=
getSharedPreferences("my_data",MODE_PRIVATE);
String name=prefs.getString("MY_NAME","name");
代替
SharedPreferences prefs=
getSharedPreferences("my_data",MODE_PRIVATE);
String name = prefs.getString("MY_NAME","name");
您已经在全局范围内定义了 sharedpref 对象。您不需要再次创建它。
推荐阅读
- grid - 带有 ALV Grid 和 Tabstrip 控件的分屏
- python-3.x - 从 tkinter 中的其他类调用按钮功能
- android - 将文本打印到列表视图,从对话框输入
- sql - 与 NULL 或使用 NVL 函数相比,哪个更好?
- android - 带有 GridView 的 ScrollView 不滚动到底部
- asp.net-core - 使用 ASP.NET Core(POST、PUT 和 DELETE)时出现错误 500
- java - 画布绘制文本未在真实设备/模拟器上显示文本
- java - Spring - 是否可以在 post 方法的请求映射中提供相同的 url?
- c# - 使用 iTextSharp 将 HTML 转换为 PDF 不支持阿拉伯语
- java - Gradle Error URI 有一个权限组件