任何人都可以看到我做错了什么:(?
我正在尝试使用按钮创建活动,该按钮将在其他活动的共享偏好中执行明确保存的数据。
这是明确的数据活动
public class Clear_data extends Activity {
public Button bt1;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.cdata);
LoadPreferences();
bt1 = (Button)findViewById(R.id.cData);
bt1.setOnClickListener(remove_data);
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getSharedPreferences(Test.SharedP, MODE_PRIVATE);
String strSaved1 = sharedPreferences.getString("SP1", "");
}
View.OnClickListener remove_data = new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(Test.SharedP, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
finish();
finish();
}
};
}
这是我试图清除
数据的主要活动public class Test extends Activity {
public TextView tv3, tv5;
public EditText et1, et2;
public Button b1, b2, b3, b4 ;
public ImageView img1, img2;
public static String SharedP = "MyPrefsFile";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
LoadPreferences();
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getSharedPreferences(Test.SharedP, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getSharedPreferences(Test.SharedP, MODE_PRIVATE);
String strSaved1 = sharedPreferences.getString("SP1", "");
tv5.setText(strSaved1);
}
View.OnClickListener convert_handlermtok = new View.OnClickListener() {
public void onClick(View v) {
if (et1.getText().toString().equals("")) {
Toast.makeText(Test.this, "put sommat in then you idiot!" , Toast.LENGTH_SHORT).show();
} else {
// Conversion is here
// Defining the value and method to display the result
int Amount = (int) Float.parseFloat(et1.getText().toString());
int exchanged = (int) (Amount * 1.609344) ;
String result = String.valueOf(exchanged);
Toast.makeText(Test.this, "Converted Speed " + (et1.getText().toString()) +
" Mph = " + result + " Kph",
Toast.LENGTH_LONG).show();
SavePreferences("SP1", et1.getText().toString() +
" Mph = " + result + " Kph");
LoadPreferences();
}
}
};
答案 0 :(得分:0)
您无需再调用其他活动来清除共享偏好。从当前活动中做到这一点就足够了。
顺便说一句。你可以将sharedPreference作为类的属性,而不是每次需要时打开它。