首页 > 解决方案 > 在 Android Studio 中检查 Sharedpreferences 保存复选框

问题描述

我尝试按照此示例共享首选项示例 在此示例中创建 2 个复选框。我尝试了不同的方法,但它没有保存任何更改。如果单击并具有最后选择的值,我只是不想保护复选框。我是 Java 新手,希望有人能用这个例子向我解释如何解决这个问题。

package example.com.max.lschennn;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

public class MainActivity extends Activity {
SharedPreferences sharedpreferences;
TextView name;
TextView email;
CheckBox check1;
CheckBox check2;

public static final String mypreference = "mypref";
public static final String Name = "name";
public static final String Email = "email";
public static final String CHECK1 = "check1";
public static final String CHECK2 = "check2";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    name = (TextView) findViewById(R.id.etName);
    email = (TextView) findViewById(R.id.etEmail);
    check1 = (CheckBox) findViewById(R.id.checkBox1);
    check2 = (CheckBox) findViewById(R.id.checkBox2);
    sharedpreferences = getSharedPreferences(mypreference,
            Context.MODE_PRIVATE);
    if (sharedpreferences.contains(Name)) {
        name.setText(sharedpreferences.getString(Name, ""));
    }
    if (sharedpreferences.contains(Email)) {
        email.setText(sharedpreferences.getString(Email, ""));

    }

}

public void Save(View view) {
    String n = name.getText().toString();
    String e = email.getText().toString();
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putString(Name, n);
    editor.putString(Email, e);
    editor.putBoolean(String.valueOf(check1), true); // Storing boolean - true/false
    editor.putBoolean(String.valueOf(check2), true); // Storing boolean - true/false
    editor.commit();
}

public void clear(View view) {
    name = (TextView) findViewById(R.id.etName);
    email = (TextView) findViewById(R.id.etEmail);
    name.setText("");
    email.setText("");

}

public void Get(View view) {
    name = (TextView) findViewById(R.id.etName);
    email = (TextView) findViewById(R.id.etEmail);

    sharedpreferences = getSharedPreferences(mypreference,
            Context.MODE_PRIVATE);

    if (sharedpreferences.contains(Name)) {
        name.setText(sharedpreferences.getString(Name, ""));
    }
    if (sharedpreferences.contains(Email)) {
        email.setText(sharedpreferences.getString(Email, ""));

    }
}

}

标签: checkboxsavesharedpreferences

解决方案


推荐阅读