NullPointerException on SQLite Course

I received this crash report in the Google Play console. I have never experienced such a failure on my device and emulator.

Caused by: java.lang.NullPointerException: 
  at android.preference.PreferenceManager.getDefaultSharedPreferencesName (PreferenceManager.java:498)
  at android.preference.PreferenceManager.getDefaultSharedPreferences (PreferenceManager.java:487)
  at DictionaryDB2.getHistoryWords (DictionaryDB2.java)
  or                     .hasObject (DictionaryDB2.java)

it getHistoryWords

public List<Bean> getHistoryWords() {
        SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(MyApp.getAppContext());
        String historyNum = SP.getString("history","50");

        SQLiteDatabase db = initializer.getReadableDatabase();

        String sql = "SELECT * FROM " + HISTORY_NAME +
                " WHERE " + STATUS + " ORDER BY " + STATUS + " DESC LIMIT " + historyNum ;

        Cursor cursor = db.rawQuery(sql, null);

        List<Bean> wordList = new ArrayList<Bean>();
        while(cursor.moveToNext()) {
            int id = cursor.getInt(0);
            String english = cursor.getString(1);
            String malay = cursor.getString(2);
            wordList.add(new Bean(id, english, malay));
        }

        cursor.close();
        db.close();
        return wordList;
    }

This is MyApp:

public class MyApp extends Application {  

    private static Context context;

    public void onCreate() {
        super.onCreate();
        MobileAds.initialize(this, "my admob ");
        MyApp.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return MyApp.context;
    }
}

How to solve this problem?

+4
source share
2 answers

Instead of using a static link to the application context inside getHistoryWords(), I would suggest adding a context parameter and passing this from the main action.

public List<Bean> getHistoryWords(Context context) {
    SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(context);
    ...
}

Then in the main action ...

public void onCreate( Bundle savedInstanceState ) {
    setContentView( ... );
    ...
    List<Bean> beans = getHistoryWords( getApplicationContext() );
    ...
}
0
source

Your problem is how you get your context for the Preferences Manager.

Problem 1:

Do not use static links for context, I'm sure Android Studio gives you a warning about this.

Problem 2:

, , ApplicationContext, null .

, ,

:

myMethod(getApplicationContext()); // Application context
myMethod(this); //In case you call from Activity
myMethod(getActivity()); //In case you call from Fragment

:

public void myMethod(Context context){ ... }
0

Source: https://habr.com/ru/post/1694643/


All Articles