Nitesh Kabra Nitesh Kabra - 3 months ago 10
Android Question

How to Remove Shared Preference Values in android?

I want to clear value stored in Shared preferences
I am using this code.

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


but getting this error.

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


private OnClickListener logoBarListener = new OnClickListener() {
/*
* (non-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();
}
}
};

Answer

If you are creating object of your LinearLayout class in Activity class then you should pass Context in the Constructor.

Below is snipper

Activity Class

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

MyLinearLayout Class

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);

    }

}