按钮单击时删除Sharedpreferences

时间:2017-10-03 14:36:31

标签: android

我是android的初学者。我已将共享偏好传递给意图活动。我想在用户点击按钮时将其删除。我怎样才能在代码中执行它?我尝试了不同的方法,但没有成功。 谢谢。

以下代码

            String computer_name = ComputerName.getText().toString();
            SharedPreferences computerNamePrefs = getSharedPreferences(PREFERENCE,0);
            SharedPreferences.Editor computerNameeditor = computerNamePrefs.edit();
            computerNameeditor.putString("COMPUTERNAME",computer_name);
            computerNameeditor.commit();

            Intent computerIntent = new Intent(getApplicationContext(), SelectedService.class);
            startActivity(computerIntent);

            // SelectedService Activity below

            computer_brandname = (TextView)findViewById(R.id.COMPUTER_BRAND);
            final SharedPreferences computerPreference = getSharedPreferences(PREFERENCE,0);
            String computerName = computerPreference.getString("COMPUTERNAME","");
            computer_brandname.setText(computerName);

           removeButton = (Button)findViewById(R.id.remove);
    removeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          // i am unable to figure out this code

        }

    });

2 个答案:

答案 0 :(得分:2)

检索SharedPreferences对象以访问此活动专用的首选项。

SharedPreferences preferences = getSharedPreferences("YOUR PREF", Context.MODE_PRIVATE);

SharedPreferences.Editor editor = preferences.edit();
editor.clear().apply(); //remove all

//OR

editor.remove("KEY").apply(); //remove by key

单击

使用
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
         editor.remove("KEY").apply(); //remove by key
    }
});

答案 1 :(得分:1)

SharedPreference.Editor pref = context.getSharedPreferences("A_PREFS_FILE", 0).edit();
pref.clear();
pref.commit();