开发者

SharedPreferences.Editor.apply force closes

I am using the following code:

SharedPreferences.Editor edit = mPrefs.edit();
edit.putString("UUID", UUID.randomUUID开发者_StackOverflow().toString());
edit.commit();
//edit.apply();

This works fine, but if I comment out the commit and uncomment the apply, the app force closes on my device with no error message, or exception thrown. Strangely, this runs fine in the emulator, under 2.2 and 2.3.3. It only closes on my Nexus one running 2.2.1

I have the workaround above, but am interested as to the cause of the close.

Can anyone help?

Cheers, Venatu


apply() was added in API level 9 (a.k.a., Android 2.3). Do not attempt to use it on Android 2.2.


It’s simple I use kode like this:

if (respondsTo(editor, "apply")) invoke(editor, "apply”);
else editor.commit();

and then I have those two magic methods as static imports..

public static boolean respondsTo(Object object, String methodName) {
    try {
        object.getClass().getMethod(methodName, (Class<?>[]) null);
        return Yes;
    } catch (NoSuchMethodException e) {
        return No;
    }
}

public static Object invoke(Object object, String methodName) {
    try {
        return object.getClass().getMethod(methodName, (Class<?>[]) null).invoke(object);
    } catch (Exception e) {
        return INVOKE_FAILED;
    }
}

Commit runs while blocking UI so that can be problem if saving large data. I used background thread for commit (it’s problematic...) but now many users have 2.3 so I think older should switch...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜