android上下文和sharedpreferences [英] android context and sharedpreferences

查看:294
本文介绍了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

这篇关于android上下文和sharedpreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆