如标题所述,我遇到了NullPointerException
,它出现在以下方法的第一个getString()
处。为了调试,我使用了DatabaseUtils.dumpCursorToString()
来查看游标,并且游标中有值,但是在if
语句和do
语句之间,有些变化。我在单独的活动中的另一种方法中使用了相同的代码,并且可以完美地工作。
public ArrayList<String> getMusic() {
helper = new DbHelper(context);
db = helper.getReadableDatabase();
String[] cols = new String[]{MUSIC_ID, MUSIC_COUNTRY, MUSIC_BLUES, MUSIC_ROCK, MUSIC_METAL,
MUSIC_HIPHOP, MUSIC_CLASSICAL, MUSIC_PUNK, MUSIC_TECHNO, MUSIC_JAZZ, MUSIC_OTHER};
Cursor c = db.query(TABLE_MUSIC_INT, cols, null, null, null, null, null);
int count = c.getCount();
Log.v("INTEREST CURSOR ", "Count: " + count); // log row count
if (c.moveToFirst()) {
Log.v("INTEREST CURSOR ", DatabaseUtils.dumpCursorToString(c)); // dump cursor values
do {
musicInt.add(c.getString(0));
musicInt.add(c.getString(1));
musicInt.add(c.getString(2));
musicInt.add(c.getString(3));
musicInt.add(c.getString(4));
musicInt.add(c.getString(5));
musicInt.add(c.getString(6));
musicInt.add(c.getString(7));
musicInt.add(c.getString(8));
musicInt.add(c.getString(9));
musicInt.add(c.getString(10));
} while (c.moveToNext());
} else {
Log.e("DB_GET_DATA ", " DB_GET_DATA == null");
}
c.close();
return musicInt;
}
DatabaseUtils.dumpCursorToString(c)输出:
01-15 19:57:01.201 6247-6247/us.enyi.enyi D/DB OPEN READ: Successful
01-15 19:57:20.440 6247-6247/us.enyi.enyi V/INTEREST CURSOR: Count: 1
01-15 19:57:27.897 6247-6247/us.enyi.enyi V/INTEREST CURSOR: >>>>> Dumping cursor android.database.sqlite.SQLiteCursor@2f32900f
01-15 19:57:27.897 6247-6247/us.enyi.enyi V/INTEREST CURSOR: 0 {
01-15 19:57:27.897 6247-6247/us.enyi.enyi V/INTEREST CURSOR: _id=1
01-15 19:57:27.897 6247-6247/us.enyi.enyi V/INTEREST CURSOR: country=null
01-15 19:57:27.897 6247-6247/us.enyi.enyi V/INTEREST CURSOR: blues=null
01-15 19:57:27.897 6247-6247/us.enyi.enyi V/INTEREST CURSOR: rock=Rock
01-15 19:57:27.897 6247-6247/us.enyi.enyi V/INTEREST CURSOR: metal=Metal
01-15 19:57:27.897 6247-6247/us.enyi.enyi V/INTEREST CURSOR: hiphop=HipHop
01-15 19:57:27.897 6247-6247/us.enyi.enyi V/INTEREST CURSOR: classical=Classical
01-15 19:57:27.897 6247-6247/us.enyi.enyi V/INTEREST CURSOR: punk=null
01-15 19:57:27.897 6247-6247/us.enyi.enyi V/INTEREST CURSOR: techno=Techno
01-15 19:57:27.897 6247-6247/us.enyi.enyi V/INTEREST CURSOR: jazz=null
01-15 19:57:27.897 6247-6247/us.enyi.enyi V/INTEREST CURSOR: musicother=Other
01-15 19:57:27.897 6247-6247/us.enyi.enyi V/INTEREST CURSOR: }
01-15 19:57:27.897 6247-6247/us.enyi.enyi V/INTEREST CURSOR: <<<<<
我尝试了其他方法来从游标中检索数据并在SO以及Android Docs中读取无数线程,而没有找到任何有用的解决方案。我不太明白为什么游标显然具有值,但是
c.getString()
在NPE上失败。任何帮助将不胜感激。解:
无法初始化musicInt导致Cursor无处放置其收集的数据。声明musicInt为:
ArrayList<String> musicInt;
代替:
ArrayList<String> musicInt = new ArrayList<>();
该课程是确保您适当地初始化变量。您会像其他情况一样拔出头发。
最佳答案
我看不到您在哪里声明(或初始化)musicInt
。这可能是导致您的NPE的原因。
关于java - Android Cursor NPE dumpCursorToString返回值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34823361/