0

谁能看到我做错了什么:(?

我正在尝试使用按钮创建一个活动,该按钮将在其他活动的 sharedpreferences 中执行清除保存的数据。

这是清除数据活动

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

1 回答 1

0

您不必调用其他活动来清除您的共享首选项。从当前活动开始就足够了。

顺便提一句。您可以使您的 sharedPreference 成为该类的属性,而不是每次需要时都打开它。

于 2012-11-27T19:16:48.857 回答