SharedPreferencesCompat.java revision f185f104c4786740765e549d535f9ba1052f96cc
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 public void apply(@NonNull SharedPreferences.Editor editor) { 31 try { 32 editor.apply(); 33 } catch (AbstractMethodError unused) { 34 // The app injected its own pre-Gingerbread 35 // SharedPreferences.Editor implementation without 36 // an apply method. 37 editor.commit(); 38 } 39 } 40 } 41 42 private final Helper mHelper; 43 44 private EditorCompat() { 45 mHelper = new Helper(); 46 } 47 48 public static EditorCompat getInstance() { 49 if (sInstance == null) { 50 sInstance = new EditorCompat(); 51 } 52 return sInstance; 53 } 54 55 public void apply(@NonNull SharedPreferences.Editor editor) { 56 // Note that this redirection is needed to not break the public API chain 57 // of getInstance().apply() calls. Otherwise this method could (and should) 58 // be static. 59 mHelper.apply(editor); 60 } 61 } 62 63 private SharedPreferencesCompat() {} 64 65} 66