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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android:尝试在空对象引用[duplicate]上调用虚方法'void android.database.sqlite.SQLiteDatabase.execSQL(java.lang.相关的知识,希望对你有一定的参考价值。

这个问题在这里已有答案:

我收到这个错误:

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

错误在这一行:

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);
}

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

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

答案

使用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()

以上是关于Android:尝试在空对象引用[duplicate]上调用虚方法'void android.database.sqlite.SQLiteDatabase.execSQL(java.lang.的主要内容,如果未能解决你的问题,请参考以下文章

尝试在空对象引用上调用虚拟方法 'android.view.Window$Callback android.view.Window.getCallback()'

Android错误尝试在空对象引用上调用虚拟方法[重复]

尝试在空对象引用上调用虚拟方法 'android.os.Handler android.support.v4.app.FragmentHostCallback.getHandler()'

JPE:尝试在空对象引用上调用虚拟方法“android.content.res.Resources”

Android Studio:尝试在空对象引用上调用虚拟方法“void android.view.View.setOnClickListener”

尝试在空对象引用上调用虚拟方法 'void android.view.View.measure(int, int)'