Bezdepbonusu7Программирование: статьи и ответы

Вопрос

Как удалить общие значения предпочтений в Android?

Автор вопроса: Nitesh KabraОтветов: 7

Я хочу очистить значение, хранящееся в общих настройках. Я использую этот код.

/*  SharedPreferences myPrefs = this.getSharedPreferences("myPrefs",
            Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = myPrefs.edit();
            editor.clear();
            editor.commit();   */

но получаю эту ошибку.

The method getSharedPreferences(String, int) is undefined for the type new View.OnClickListener(){}

private OnClickListener logoBarListener = new OnClickListener() { /* * (не Javadoc) * * @see android.view.View.OnClickListener#onClick(android.view.View) */ public void onClick(View v) {

        if (v.getId() == R.id.img_bottom_home) {

            showProgressBar(MainScreen.class);

        } else if (v.getId() == R.id.img_bottom_basket) {

            showProgressBar(ShopBasketGet.class);

        } else if (v.getId() == R.id.img_bottom_notification) {

            showProgressBar(Notification.class);

        } else if (v.getId() == R.id.img_bottom_login) {
            SharedPreferences myPrefs = getSharedPreferences("myPrefs",
                    MODE_WORLD_READABLE);
            SharedPreferences.Editor editor = myPrefs.edit();
            editor.clear();
            editor.commit();

            showProgressBar();
        }
    }
};
  • то, что сказал Шайфул, верно. Попробуйте использовать YourActivityName.this.getSharedPreferences(myPrefs,Context.MODE_PRIVATE); Shabbir Panjesha 31.05.2012

androidsharedpreferences

Ответы

Ответ 1 · Vipul

Если вы создаете объект своего класса LinearLayout в классе Activity, вы должны передать контекст в конструкторе.

Ниже приведен снайпер

Класс активности

public class SampleActivity extends Activity
{
    public void onCreate(Bundle bundle)
     {
         MyLinearLayout layout = new MyLinearLayout(this);
         -----
         -----
     }
}

Класс MyLinearLayout

public class MyLinearLayout extends LinearLayout {
    private Context context;
    public MyLinearLayout(Context context) {
        super(context);
        this.context=context;
        SharedPreferences preferences=context.getSharedPreference("pref",
                context.MODE_PRIVATE);

    }

}

Ответ 2 · рейтинг 1 · Shaiful

Удалите ключевое слово this (замените this.getSharedPreferences() на getSharedPreferences(). this относится к внутреннему классу View.onClickListener(), тогда как метод фактически находится в классе Activity.

Ответ 3 · Vipul

Используйте следующий фрагмент кода

    Context context=YourActivityName.this;
    SharedPreferences myPrefs = context.getSharedPreferences("myPrefs",
    Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = myPrefs.edit();
    editor.clear();
    editor.commit();

Надеюсь это поможет,

Випул

Ответ 4 · Khan

попробуй так

 SharedPreferences pref = YourActivityName.this.getSharedPreferences("myPrefs", Context.MODE_PRIVATE);
 pref.edit().clear().commit();

я думаю, вы пытаетесь очистить событие onclick, чем использовать этот способ

SharedPreferences myPrefs = v.getContext().getSharedPreferences("myPrefs",Context.MODE_PRIVATE)
SharedPreferences.Editor editor = myPrefs.edit();
editor.clear();
editor.commit();

Ответ 5 · Shabbir Panjesha

Вызовите метод clearSharedPreferences() нажатием кнопки и передайте этому методу контекст переменной класса.

public class MyLinearLayout extends LinearLayout {
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    Context context;
    public MyLinearLayout(Context context) {
        super(context);
            this.context = context;
    }

    public MyLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    private void clearSharedPreferences(Context context) {
        preferences = context.getSharedPreferences("myPrefs",
                context.MODE_PRIVATE);
        editor = preferences.edit();
        editor.clear();
        editor.commit();
    }
}

// ваш код станет

if (v.getId() == R.id.img_bottom_home) {

            showProgressBar(MainScreen.class);

        } else if (v.getId() == R.id.img_bottom_basket) {

            showProgressBar(ShopBasketGet.class);

        } else if (v.getId() == R.id.img_bottom_notification) {

            showProgressBar(Notification.class);

        } else if (v.getId() == R.id.img_bottom_login) {
            clearSharedPreferences(context);
            showProgressBar();
        }
    }
};

Ответ 6 · DarckBlezzer

Примеры удаления SharedPreference, одной переменной или всех SharedPreference...

SharedPreferences sharedPreferences = getSharedPreferences("mysharedpreferences",MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
// a specific var of sharedPreference....
//Mark in the editor that a preference value should be removed, which will be done in the actual preferences once commit() is called.
editor.remove("mySharedVar");

//if you want remove all sharedPreference...
//Mark in the editor to remove all values from the preferences. Once commit is called, the only remaining preferences will be any that you have defined in this editor.
editor.clear();

editor.apply();

Ответ 7 · Md. Rejaul Karim

Вы можете попробовать эту связку кодов, пожалуйста. Эти строки работали на меня. Надеюсь, это сработает и для вас. ^_^

SharedPreferences preferences = getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();

editor.clear();
editor.apply();

Перевод вопроса и ответов сообщества Stack Overflow, лицензия CC BY-SA. Оригинал на Stack Overflow.

Похожие материалы