我尝试遵循此示例Shared Preferences Example 在此示例中创建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, ""));
}
}
}