getSharedPreferences in android does not work-ThrowExceptions

Exception or error:

I want use “getSharedPreferences” in class that it extends “ActionBarActivity” so it :

public class HomescreenWidget extends AppWidgetProvider  {

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    // TODO Auto-generated method stub
    super.onUpdate(context, appWidgetManager, appWidgetIds);

    for(int i = 0; i<appWidgetIds.length;i++)
    {

        .
        .
  SharedPreferences shared =getSharedPreferences("Prefs", MODE_PRIVATE);
  String str=shared.getString("string_" + ct.month + ct.date, "");//read from shard point
  viws.setTextViewText(R.id.wtv3, str);
        .       

    }


}

now how use “getsharedpreferences” ? so can’t use two extends.
i want show string that saved in shared point
and that is my shard point class

public class Prefs extends PreferenceActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    String [][] all_strings = new String [12][31];
    for(int x = 1; x < 13; x++){
        for(int y = 1; y < 32; y++){
        String name = "string_" + String.valueOf(x)+String.valueOf(y);
        all_strings [x][y] = prefs.getString(name, "");
    }
    }
}

}

How to solve:

getSharedPreferences() is a method in the class Context. Call it on your context object:

SharedPreferences shared = context.getSharedPreferences("Prefs", MODE_PRIVATE);

Why it works e.g. in an activity is because Activity is-a Context.

###

Completed structure:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Boolean Music;

    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //restore preferences
        SharedPreferences settings = this.getSharedPreferences(PREFS_NAME, 0);
        Music = settings.getBoolean("key", true);
    }

    @Override
    public void onClick() {

                //save music setup to system
                SharedPreferences settings = this.getSharedPreferences(PREFS_NAME, 0);
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean("key", Music);
                editor.apply();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *