SharedPreferencesCompat.java revision 552766fa685c63ad760c92239faaba12e6ad51f1
1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package android.support.v4.content;
18
19import android.content.SharedPreferences;
20import android.os.Build;
21import android.support.annotation.NonNull;
22
23public final class SharedPreferencesCompat {
24
25    public final static class EditorCompat {
26
27        private static EditorCompat sInstance;
28
29        private static class Helper {
30            Helper() {
31            }
32
33            public void apply(@NonNull SharedPreferences.Editor editor) {
34                try {
35                    editor.apply();
36                } catch (AbstractMethodError unused) {
37                    // The app injected its own pre-Gingerbread
38                    // SharedPreferences.Editor implementation without
39                    // an apply method.
40                    editor.commit();
41                }
42            }
43        }
44
45        private final Helper mHelper;
46
47        private EditorCompat() {
48            mHelper = new Helper();
49        }
50
51        public static EditorCompat getInstance() {
52            if (sInstance == null) {
53                sInstance = new EditorCompat();
54            }
55            return sInstance;
56        }
57
58        public void apply(@NonNull SharedPreferences.Editor editor) {
59            // Note that this redirection is needed to not break the public API chain
60            // of getInstance().apply() calls. Otherwise this method could (and should)
61            // be static.
62            mHelper.apply(editor);
63        }
64    }
65
66    private SharedPreferencesCompat() {}
67
68}
69