我有一个Android应用程序,你只需输入promocode即可获得完整版。但是如何在其他活动中检查是否已输入?这是我的代码:
AlertDialog.Builder alert = new AlertDialog.Builder(Browser.this);
alert.setTitle("Enter your promocode.");
final View input = LayoutInflater.from(Browser.this).inflate(R.layout.edittext, null);
alert.setView(input);
final EditText edit = (EditText) input.findViewById(R.id.edit);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (edit.getText().toString().equalsIgnoreCase("TheSecretcode")) {
isPremium = true;
} else {
isPremium = false;
}
}
});
alert.show();
break;
这是第二个活动的代码。我认为它并没有更新SharedPrefs。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_view_layout);
Uri uri = getIntent() != null ? getIntent().getData() : null;
final SharedPreferences premiumSettings = getSharedPreferences("PREMIUM", Context.MODE_PRIVATE);
final boolean isPremium = premiumSettings.getBoolean("isPremium", false);
if(isPremium) {
ImageView img = (ImageView) findViewById(R.id.imageView);
img.setImageURI(uri);
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(ImageViewer.this);
builder.setTitle("Error");
builder.setMessage("You are not premium user. Please enter the promocode or buy the full version");
builder.setIcon(R.drawable.holo_dark_action_info);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
}
答案 0 :(得分:1)
AlertDialog.Builder alert = new AlertDialog.Builder(Browser.this);
alert.setTitle("Enter your promocode.");
final View input = LayoutInflater.from(Browser.this).inflate(R.layout.edittext, null);
alert.setView(input);
final EditText edit = (EditText) input.findViewById(R.id.edit);
final SharedPreferences premiumSettings= getSharedPreferences("PREMIUM", Context.MODE_PRIVATE);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
SharedPreferencesEditor.Editor editor= premiumSettings.edit();
if (edit.getText().toString() == "TheSecretCode") {
isPremium = true;
} else {
isPremium = false;
}
editor.putBoolean("isPremium", isPremium);
editor.commit();
}
});
alert.show();
break;
然后在另一个Activity中,检索您的偏好:
final SharedPreferences premiumSettings = getSharedPreferences("PREMIUM", Context.MODE_PRIVATE); // The name is the same as previously
final boolean isPremium = premiumSettings.getBoolean("isPremium", false); // false is default value