How do I get sharedpreferences in Asynctask?

前端 未结 3 1985
心在旅途
心在旅途 2020-12-19 04:40

I am writing an android application for my school project but i am stuck here. The problem is i have to access a SharedPreferences value and need it in an

相关标签:
3条回答
  • 2020-12-19 04:52

    You can get SharedPreferences in the background using an AsyncTask.

    The mistake is in this line, where you are passing in the wrong type of variable:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    

    In your case, the word this refers to the AsyncTask instance that you are calling if from.


    What I do is I pass the Context in to the task in the execute() method. See the code below for a working example:

        new AsyncTask<Context, Void, String>()
        {
            @Override
            protected String doInBackground(Context... params)
            {
                Context context = params[0];
                SharedPreferences prefs =
                        context.getSharedPreferences("name of shared preferences file",
                                Context.MODE_PRIVATE);
    
                String myBackgroundPreference = prefs.getString("preference name", "default value");
    
                return myBackgroundPreference;
            }
    
            protected void onPostExecute(String result)
            {
                Log.d("mobiRic", "Preference received in background: " + result);
            };
    
        }.execute(this);
    

    In the above example, this refers to the Activity or Service that I call this from.

    0 讨论(0)
  • 2020-12-19 04:53

    You can get SharedPreferences in a background thread using the PreferenceManager like this:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(<YourActivity>.this);

    0 讨论(0)
  • 2020-12-19 05:14

    Override onPreExecute or onPostExecute method of AsyncTask and get SharedPreferences there:

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //get sharedPreferences here
        SharedPreferences sharedPreferences = getSharedPreferences(<SharedPreferencesName>, <Mode>);
    }
    

    Please note that getSharedPreferences is an Activity method. So, you need to call it through Context if you are not using it in Activity.

    0 讨论(0)
提交回复
热议问题