Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - shared preferences set in an AsyncTask onPostExecute() not always set?

Tags:

android

I have some code that works 98% of the time, and 100% during my own testing so I can not really reproduce the problem other than having user devices experience this issue.

What I do in onPostExecute() is set a parameter like this:

   SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( AddProblemActivity.this);
            prefs.edit().putString("recent_problem_id", result ).commit();

and then go to the next activity:

            Intent myIntent = new Intent(AddProblemActivity.this, ProblemActivity.class);
            AddProblemActivity.this.startActivity(myIntent);

and then try to get that parameter there like this:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( 
              ProblemActivity.this);         

    // display a loading message before problem loads.
    String recent_problem_id = prefs.getString( "recent_problem_id" , null );

    if ( recent_problem_id == null )
    {
        // Sometimes it is null!            
    }

Would anyone know why this happens?

Thanks!

like image 274
Genadinik Avatar asked Dec 27 '22 17:12

Genadinik


1 Answers

If you are trying to pass the data to a new activity, why not put it as a String extra in the intent? Then, get that String from the intent in the new activity. If you still need to store it, you can do so in the new activity's onCreate() after it pulls it from the intent.

Intent myIntent = new Intent(AddProblemActivity.this, ProblemActivity.class);
//Add results here
myIntent.putExtra("RecentProblemId", result);
AddProblemActivity.this.startActivity(myIntent);

Then, in the onCreate of your new Activity, do:

String recentProblemId = getIntent().getStringExtra("RecentProblemId");

Now, if you still need this information stored, do:

if(recentProblemId != null){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( 
              ProblemActivity.this);         
    prefs.putString("recent_problem_id",recentProblemId).commit();
}

I know this doesn't exactly answer your question as to why the String isn't always being committed to the preferences in onPostExecute(). However, the best practice for passing information between activities is via Intents and extras.

My guess as to why it may not always work for some users, is that their devices are not done writing the data to the shared preferences file before the new Activity starts and tries to read from that same file. Hope this helps.

like image 159
dennisdrew Avatar answered Jan 15 '23 10:01

dennisdrew