gpt4 book ai didi

java - SQLite 游标处的 NullPointerException

转载 作者:太空宇宙 更新时间:2023-11-03 10:59:00 25 4
gpt4 key购买 nike

我在我的 Google Play 控制台中收到了这份崩溃报告。我从来没有在自己的设备和模拟器上遇到过这样的崩溃。

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)

这是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;
}

这是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;
}
}

如何解决这个问题?

最佳答案

与其在 getHistoryWords() 中使用对应用程序上下文的静态引用,我建议您添加一个上下文参数,并从主 Activity 中传递该参数。

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

然后在主 Activity 中...

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

关于java - SQLite 游标处的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49173002/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com