android – 如何在Singleton和SharedPreferences类中传递应用程序上下文

如何将应用程序上下文从Singleton类传递给SharedPreferences?我在其onActivityCreated(Bundle savedInstanceState)方法中有一个片段和一个GridView,在项目单击时,我在logcat中得到NullPointerException:

03-30 05:12:54.784: E/AndroidRuntime(1950): FATAL EXCEPTION: main
03-30 05:12:54.784: E/AndroidRuntime(1950): java.lang.NullPointerException
03-30 05:12:54.784: E/AndroidRuntime(1950):     at android.preference.PreferenceManager.getDefaultSharedPreferencesName(PreferenceManager.java:374)
03-30 05:12:54.784: E/AndroidRuntime(1950):     at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java:369)
03-30 05:12:54.784: E/AndroidRuntime(1950):     at com.example.duaapp.utility.SharedPreferencesSupplication.save(SharedPreferencesSupplication.java:35)

单身人士班

public class SingletonClass {

    public static Context applicationContext;

    public static int fontSi* = 17;
    public static int fontSizeMax = 35;

public static final String keySelVerseFromList = "keySelVerseFromList";
    public static final String keyFavVerses = "keyFavVerses";
    public static final String keyListOfVerses = "keyListOfVerses";

    public static final String keyIsFavSelected = "keyIsFavSelected";

}

SharedPreferences

  public class SharedPreferencesSupplication {


        public void save(String valueKey, String value) {

            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(SingletonClass.applicationContext);
            SharedPreferences.Editor edit = prefs.edit();
            edit.putString(valueKey, value);
            edit.commit();
        }

        public void save(String valueKey, int value) {

            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(SingletonClass.applicationContext);
            SharedPreferences.Editor edit = prefs.edit();
            edit.putInt(valueKey, value);
            edit.commit();
        }

        public void save(String valueKey, boolean value) {

            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(SingletonClass.applicationContext);
            SharedPreferences.Editor edit = prefs.edit();
            edit.putBoolean(valueKey, value);
            edit.commit();
        }

        public void save(String valueKey, long value) {

            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(SingletonClass.applicationContext);
            SharedPreferences.Editor edit = prefs.edit();
            edit.putLong(valueKey, value);
            edit.commit();
        }
    }

在gridview_item_Click上,每当新的SharedPreferencesSupplication().save(SingletonClass.keyIsFavSelected,false);被调用,应用程序崩溃,并在logcat中引发nullpointer异常.我哪里错了?

解决方法:

永远不要在Android中使用Context的静态引用,这会导致重要的内存泄漏,因为Context引用了所有应用程序资源.

大多数Android UI类都有对上下文的动态引用,在片段中你可以做getActivity(),在视图中getContext()考虑使用那些而不是上下文单例

有关此here的更多信息

上一篇:java – 防止NullPointerException警告的最佳方法?


下一篇:在Android Fragment中获取Java.Lang.NullPointerException