首页 > 解决方案 > 我想以共享偏好保存,但应用程序崩溃

问题描述

我想制作一个基本上用户输入一些字符串的应用程序

 <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();
    }

}

标签: javaandroidandroid-studio

解决方案


只需做这个小改动:

    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 对象。您不需要再次创建它。


推荐阅读