android上下文和sharedpreferences
我正在尝试获取上下文以运行异步sharedpreferences.试图通过以下方式获取上下文:
I am trying to get context to run async sharedpreferences. Tried to get context with:
public class MainActivity2 extends Activity implements OnClickListener {
public MainActivity2(final Context context) {
this.context = context;
}
private Context context;
//....rest of class.....
}
但是包含该应用程序时该应用程序崩溃.但是需要这样的东西才能进入sharedpreferences:
But the app crashes when that it is included. But need something like that to get to sharedpreferences:
class CreateUser extends AsyncTask<String, String, String> {
// .....rest of ....
@Override
protected String doInBackground(String... args) {
SharedPreferences prefs = android.preference.PreferenceManager.getDefaultSharedPreferences(context);
String myIntegerValue = prefs.getString("ok", "f");
android.util.Log.d("your_tag", "myint: " + myIntegerValue);
}
//rest of.....
}
试图获得这样的共享首选项不起作用:
trying to get sharedpreferences like this does not work:
SharedPreferences prefs = android.preference.PreferenceManager.getDefaultSharedPreferences(getactivity());
试图获得这样的共享首选项不起作用:
trying to get sharedpreferences like this does not work:
SharedPreferences prefs = android.preference.PreferenceManager.getDefaultSharedPreferences(this);
使用此方法时,
getDefaultSharedPreferences不能应用于MainActivity2.CreateUser
getDefaultSharedPreferences cannot be applied to MainActivity2.CreateUser when using this
但是包含该应用程序时该应用程序崩溃.但是需要这样的东西 进入共享首选项:
But the app crashes when that it is included. But need something like that to get to sharedpreferences:
Activity
扩展ContextWrapper
.您不需要(也不能拥有)以上下文为参数的构造函数.您在活动中的上下文是关键字this
.如果需要在Fragment中使用它,则可以使用getActivity()
来检索托管Fragment
的活动的上下文.
Activity
extends ContextWrapper
. You don't need (and you can't have it) the constructor that takes a context as parameter. Your context in the activity is the keyword this
. If you need it in a Fragment you can use getActivity()
to retrieve the context of the activity that is hosting the Fragment
.
在您的情况下,您必须拥有各种可能性.您可以在AsyncTask
中添加一个采用Context
的构造函数,或者读取Activity中的值并将其传递给AsyncTask
.我建议您使用第二种方法
in your case you have to possibilities. You add a constructor that takes a Context
to the AsyncTask
, or you read the values in the Activity and pass it to the AsyncTask
. I would recommend you the second approach