Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StrictModeDiskReadViolation when

Tags:

android

I am trying to use SharedPreferences to store some user settings for my app. I have this code in my Activity.onCreate method:

sharedPreferences = context.getSharedPreferences("MMPreferences", 0);
soundOn = sharedPreferences.getBoolean("soundOn", true);

but it gives me this error (it is the getBoolean that generates the error):

11-10 16:32:24.652: D/StrictMode(706): StrictMode policy violation; ~duration=229 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=2079 violation=2

and the result is that the value is not read and I also get the same error when I try to write to the SharedPreferences with this code (it is the commit that generates the error):

SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("soundOn", soundOn);
editor.commit();

The only answers for this error I can find is about a strict mode warning, but my code actually fails to read/write the SharedPreferences key/value data.

like image 975
Neigaard Avatar asked Nov 10 '12 15:11

Neigaard


People also ask

How do I enable StrictMode?

Go to Settings > Developer options. Tap Advanced > Strict mode enabled.

What is StrictMode setThreadPolicy?

setThreadPolicy. Added in API level 9. public static void setThreadPolicy (StrictMode.ThreadPolicy policy) Sets the policy for what actions on the current thread should be detected, as well as the penalty if such actions occur.


2 Answers

You must do fileSystem operations on a separate thread, then the error will go away.

you can also turn off the StrictMode (but i am not recommending that)

StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy();
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old)
    .permitDiskWrites()
    .build());
doCorrectStuffThatWritesToDisk();
StrictMode.setThreadPolicy(old);
like image 198
Frank Avatar answered Oct 24 '22 07:10

Frank


If you have reactive (RxJava) configured in your Android project, you can take advantage of its properties like schedule a task on an I/O-specific Scheduler, for instance:

public void saveFavorites(List<String> favorites) {
    Schedulers.io().createWorker().schedule(() -> {
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        Gson gson = new Gson();
        String jsonFavorites = gson.toJson(favorites);
        editor.putString(Constants.FAVORITE, jsonFavorites);
        editor.apply();
    });
}
like image 25
yaircarreno Avatar answered Oct 24 '22 07:10

yaircarreno