我有一个方法来搜索特定的项目,但是当我使用这个代码并尝试使用返回对象时,我得到NullPointerException
public Obra buscarInfoObra(String filtro) {
SQLiteDatabase db = helper.getReadableDatabase();
Obra obraSelecionada = null;
Cursor cursor = db.rawQuery("SELECT * FROM " +BancoDadosHelper.TABELA_OBRA+ " WHERE "+BancoDadosHelper.COLUNA_NUM_OBRA + "=" +filtro, null);
if (cursor.moveToFirst()){
String numObra = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_NUM_OBRA));
int anoObra = cursor.getInt(cursor.getColumnIndex(BancoDadosHelper.COLUNA_ANO_OBRA));
String descObra = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_DESCRICAO_OBRA));
String jurisdicionado = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_JURISDICIONADO));
String tipoObra = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_TIPO_OBRA));
String tipoObjeto = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_TIPO_OBJETO));
String endereco = cursor.getString(cursor.getColumnIndex(BancoDadosHelper.COLUNA_ENDERECO_OBRA));
obraSelecionada = new Obra(numObra,anoObra,descObra,jurisdicionado,tipoObra,tipoObjeto,endereco);
}
cursor.close();
db.close();
return obraSelecionada;
我做错了什么?
[编辑]这不是重复,我知道什么是NullPointerException,但我不明白为什么我得到这个例外。我已经尝试将现有数据直接放在代码上,但仍然得到NullPointer ..
答案 0 :(得分:0)
您应该检查光标上的null,然后使用,然后关闭。
public Obra buscarInfoObra(String filtro) {
SQLiteDatabase db = helper.getReadableDatabase();
Obra obraSelecionada = null;
Cursor cursor = db.rawQuery(...);
if (cursor != null) {
if (cursor.moveToFirst()) {
// use cursor
obraSelecionada = ...
}
cursor.close();
}
db.close();
return obraSelecionada;
}
但是 null游标可以由错误的sql语句组成。你需要用等于
的引号来包装你的等号的字符串"SELECT * FROM table_name WHERE column_name = 'some value'"
你有一些看起来更像是
的东西"SELECT * FROM table_name WHERE column_name = some value"
所以这应该修复
Cursor cursor = db.rawQuery("SELECT * FROM " + BancoDadosHelper.TABELA_OBRA + " WHERE " + BancoDadosHelper.COLUNA_NUM_OBRA + "=" + "'" + filtro + "'", null);
侧面提示,您应该编写这样的查询,以避免sql注入
db.query(BancoDadosHelper.TABELA_OBRA, null,
BancoDadosHelper.COLUNA_NUM_OBRA + "=?",
new String[] { filtro },
null, null, null);
希望有所帮助
答案 1 :(得分:-1)
尝试这种方式
public RentMasterModel getRent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_RENTMASTER, new String[]{KEY_RENTMASTER_ITEMID,
KEY_RENTMASTER_RENTHOUR, KEY_RENTMASTER_RENTDAY, KEY_RENTMASTER_RENTWEEK, KEY_RENTMASTER_RENTMONTH}
, KEY_RENTMASTER_ITEMID + "=?",
new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
RentMasterModel rm = new RentMasterModel(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4));
// return contact
return rm;
}
这里将游标值添加到bean类