I have updated to the latest Android SDK Tools (23.0.0), Platform-tools (20.0.0), Android Studio Gradle plugin (0.12.+) and suddenly I am receiving a weird Lint issue report saying that I should use apply() instead of commit() as apply() is asynchronous and will allow UI Thread to proceed as commit() will be blocking it for writing. Cool. But still I am getting this:
Is it an Lint bug, or am I missing something here?
Obviously I could suppress this warning, but I find it pointless and ignorant of the root cause.
EDIT: This will also be raised when building app from command line.
Unlike commit() , which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures.
We can call commit() or apply() to save the values in the SharedPreferences file. The commit() saves the values immediately whereas apply() saves the values asynchronously.
Use apply(). It writes the changes to the RAM immediately and waits and writes it to the internal storage(the actual preference file) after. Commit writes the changes synchronously and directly to the file. Save this answer.
getSharedPreferences() — Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any Context in your app. getPreferences() — Use this from an Activity if you need to use only one shared preference file for the activity.
It is a Lint bug, indeed. More specifically, this one.
The error seems to be in the CommitFinder
inner class of SharedPrefsDetector
:
@Override
public boolean visitMethodInvocation(MethodInvocation node) {
...
String name = node.astName().astValue();
boolean isCommit = "commit".equals(name);
if (isCommit || "apply".equals(name)) {
...
if (returnValueIgnored) {
String message = "Consider using apply() instead; commit writes "
+ "its data to persistent storage immediately, whereas "
+ "apply will handle it in the background";
mContext.report(ISSUE, node, mContext.getLocation(node), message,
null);
}
I guess the idea was to give this warning only if you didn't assign the return value of commit()
to anything (this part works), but they forgot to check the isCommit
flag. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With