Android:尝试在空对象引用上调用虚方法'void android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)'

时间:2017-12-22 13:06:52

标签: java android sqlite nullpointerexception

我收到了这个错误:

  

无法开始活动   ComponentInfo {amsi.dei.estg.ipleiria.pt.ima / amsi.dei.estg.ipleiria.pt.ima.ListaEmpresas}:   java.lang.NullPointerException:尝试调用虚方法'void   android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)'上   null对象引用“在我的DBHelper中的这一行:

错误在这一行:

database.execSQL(createEmpresasTable);

我的DBHelper:

public class ImaBDHelper extends SQLiteOpenHelper {

private static final String DB_NAME = "IMA";
private static final int DB_VERSION = 1;

private static final String EMPRESAS_TABLE_NAME = "empresas";
private static final String NOME_EMPRESA = "nome";
private static final String DESCRICAO_EMPRESA = "descricao";
private static final String LOCALIDADE_EMPRESA = "localidade";
private static final String AREA_EMPRESA = "area";

private final SQLiteDatabase database;

public ImaBDHelper(Context context)
{
    super(context, DB_NAME, null, DB_VERSION);

    this.database = getWritableDatabase();
}


@Override
public void onCreate(SQLiteDatabase db) {
    String createEmpresasTable = "CREATE TABLE " + EMPRESAS_TABLE_NAME +
            "(id INTENGER PRIMARY KEY AUTOINCREMENT," +
            NOME_EMPRESA + " TEXT NOT NULL," +
            DESCRICAO_EMPRESA + " TEXT," +
            LOCALIDADE_EMPRESA + " TEXT NOT NULL," +
            AREA_EMPRESA + " TEXT NOT NULL," + ")";
database.execSQL(createEmpresasTable);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    String sql = "DROP TABLE IF EXISTS " + EMPRESAS_TABLE_NAME;
    database.execSQL(sql);
    this.onCreate(database);
}

其余的只是创建,阅读,更新和删除的方法。

很抱歉,如果这是重复但我在搜索中找不到这个确切问题的答案。提前谢谢!

1 个答案:

答案 0 :(得分:1)

使用onCreate(SQLiteDatabase db)签名值代替private final SQLiteDatabase database;执行查询,如下所示

@Override
public void onCreate(SQLiteDatabase db) {
    String createEmpresasTable = "CREATE TABLE " + EMPRESAS_TABLE_NAME +
            "(id INTENGER PRIMARY KEY AUTOINCREMENT," +
            NOME_EMPRESA + " TEXT NOT NULL," +
            DESCRICAO_EMPRESA + " TEXT," +
            LOCALIDADE_EMPRESA + " TEXT NOT NULL," +
            AREA_EMPRESA + " TEXT NOT NULL," + ")";
db.execSQL(createEmpresasTable);// change here
}

这样也可以在你的onUpgrade()

中使用