android中的getSharedPreferences不起作用

时间:2014-07-29 13:04:51

标签: android

我想在类中使用“getSharedPreferences”,它扩展了“ActionBarActivity”,所以:

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

    }


}

现在如何使用“getsharedpreferences”?所以不能使用两个扩展。 我想要显示保存在共享点的字符串 那是我的碎片点类

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, "");
    }
    }
}

}

2 个答案:

答案 0 :(得分:1)

getSharedPreferences()是班级Context中的一种方法。在您的上下文对象上调用它:

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

为什么会起作用,例如在一项活动中,因为Activity是一个Context

答案 1 :(得分:0)

完整的结构:

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