1

在我的应用程序中,我在一个处理对我的应用程序 SharedPreferences 的所有请求的类中使用 Context,该类的相关部分是构造函数:

private SharedPreferences preferences;
public AppSettings(Context context){
    preferences = PreferenceManager.getDefaultSharedPreferences(context);
}

在我的初始活动中,我可以使用类中的其他一些方法很好地设置和读取参数,我使用getApplicationContext()从扩展AsyncTask的类的doInBackground()调用中调用上下文:

public class MyTask extends AsyncTask<Void, Void, Boolean> {
    @Override
    protected Boolean doInBackground(Void... params) {
        ...
        AppSettings as = new AppSettings(context);
        ...
    }
}

这工作得很好,但是当我尝试在下一个活动中恢复设置时:

public class MainActivity extends Activity 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AppSettings as = AppSettings(getApplicationContext());
    }
    ...
}

我在 Eclipse 中收到一条错误消息:

未为 MainActivity 类型定义 AppSettings(Context) 方法

我对 getApplicationContext 的理解是它应该给我应用程序的全局上下文,但显然在每种情况下它都返回不同的东西。我该如何解决这个问题?

4

1 回答 1

2

Errr..你不是说

AppSettings as = new AppSettings(getApplicationContext()); //<-- missed the "new"
于 2013-02-25T18:08:33.757 回答