我在以下代码行中获得空指针异常
attendanceList = dbHelper.getAttendance(surName, name);
surName和name都不为null,有size()> 0和attendanceList的类型为ArrayList,这里是getAttendance函数:
public ArrayList<Attendance> getAttendance(String surName, String name)
{
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<Attendance> attendanceList = new ArrayList<>();
Cursor cursor = db.rawQuery("SELECT * FROM " + ATTENDANCE_TABLE + " WHERE " + COLUMN_SURNAME + " =? AND "
+ COLUMN_NAME + " =?", new String[] {surName, name});
if(cursor .moveToFirst())
{
while(!cursor.isAfterLast())
{
Attendance attendance = new Attendance();
attendance.setDate(cursor.getString(cursor.getColumnIndex(COLUMN_DATE)));
attendance.setName(cursor.getString(cursor.getColumnIndex(COLUMN_NAME)));
attendance.setSurName(cursor.getString(cursor.getColumnIndex(COLUMN_SURNAME)));
attendance.setState(cursor.getString(cursor.getColumnIndex(COLUMN_STATE)));
attendance.setTerm(cursor.getInt(cursor.getColumnIndex(COLUMN_TERM)));
attendance.setSubject(cursor.getString(cursor.getColumnIndex(COLUMN_SUBJECT_NAME)));
attendanceList.add(attendance);
cursor.moveToNext();
}
cursor.close();
db.close();
return attendanceList;
}
else
{
cursor.close();
db.close();
return null;
}
}
上面的函数没有语法错误,我知道它不应该返回null,因为我使用DB Browser for SQLite看到了ATTENDANCE_TABLE的内容。有人能指出我的代码有什么问题吗?我觉得我写了1 + 1 = 2并收到错误..
答案 0 :(得分:0)
试试这个... SQLiteDbHelper是我的数据库类,我的表已定义。 Table_Name是存储我的表名的字符串
cursor = db.rawQuery("SELECT * FROM "+SQLiteDBHelper.TABLE_NAME+" WHERE "+SQLiteDBHelper.COLUMN_SURNAME+"=? AND "+SQLiteDBHelper.COLUMN_NAME+"=?",new String[] {surName,name});
if (cursor != null) {
if(cursor.getCount() > 0) {
cursor.moveToFirst();
//Retrieving User SurName and Name
String s_name = cursor.getString(cursor.getColumnIndex(SQLiteDBHelper.COLUMN_SURNAME));
String _name= cursor.getString(cursor.getColumnIndex(SQLiteDBHelper.COLUMN_NAME));
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
答案 1 :(得分:0)
我很确定导致surName
的{{1}}或name
不是NullpointerException
,而是dbHelper
。
因此,请检查您是否在此行之后初始化dbHelper
attendanceList = dbHelper.getAttendance(surName, name);
如果是这样,那么将其移到上面,你的崩溃就会得到解决。 希望它有所帮助。