Diogo Carvalho Diogo Carvalho - 7 months ago 126
Java Question

Android: Attempt to invoke virtual method 'void android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)' on a null object reference

I'm getting this error:


Unable to start activity
ComponentInfo{amsi.dei.estg.ipleiria.pt.ima/amsi.dei.estg.ipleiria.pt.ima.ListaEmpresas}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)' on a
null object reference" on this line in my DBHelper:


The error is in this line:

database.execSQL(createEmpresasTable);


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


The rest are just methods to create, read, update and delete.

Sorry if this is a duplicate but I haven't found the answer for this exact problem in my searches. Thank you in advance!

Omi Omi
Answer Source

use onCreate(SQLiteDatabase db) signature value instead from private final SQLiteDatabase database; for execute query like below

@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
}

like this also use in your onUpgrade()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download