-1

While running db.exec(q) method it shows null object reference. db is object of SQLiteDatabase class. and exec() is abstract method which is overridden. Here is the code of DatabaseHelper class extended by SQLiteOpenHelper

public class MyDbHelper extends SQLiteOpenHelper{

SQLiteDatabase db;
Context context;


MyDbHelper(Context context)
{
    super(context,"userDB",null,1);
    this.context = context;
    db = this.getWritableDatabase();
}


@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {


    String q = "create table user(uname text primary key,uage text,uphone text,bmi float)";
    db.execSQL(q);

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}


public void addData(String uname,String uage,String uphone,Double bmi)
{

    ContentValues cv = new ContentValues();
    cv.put("uname",uname);
    cv.put("uage",uage);
    cv.put("uphone",uphone);
    cv.put("bmi",bmi);
    long rid = db.insert("user",null,cv);

    if(rid<0)
    {
        Toast.makeText(context, "Insert Issue !!!!!", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(context, "Record Inserted !!!!!", Toast.LENGTH_SHORT).show();
    }
}

public String viewData()
{

    StringBuffer sb = new StringBuffer();
    Cursor c = db.query("user",null,null,null,null,null,null);
    c.moveToFirst();

    if(c.getCount() == 0 )
    {
        sb.append("No Records To Display");
    }
    else
    {
        do{
            String uname = c.getString(0);
            String uage = c.getString(1);
            String uphone = c.getString(2);
            float bmi = c.getFloat(3);
            sb.append("User : " +uname+ "\nAge : " +uage+ "\nPhone : " +uphone+ "\nBMI : " +bmi+ "\n\n---------------\n\n");


        }while (c.moveToNext());
    }

    return sb.toString();




}

}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

1

Replace this

 db.execSQL(q);

with this

 sqLiteDatabase.execSQL(q);

onCreate will be triggered when you first install your app and you need to use sqLiteDatabase reference to execute sql commands and db will be initialized when you instantiate your MyDbHelper class

Pavneet_Singh
  • 36,884
  • 5
  • 53
  • 68