运行 db.exec(q)方法时,它显示空对象引用。 db 是 SQLiteDatabase 类的对象。 和exec()是被覆盖的抽象方法。 这是由SQLiteOpenHelper
扩展的DatabaseHelper类的代码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();
}
}
答案 0 :(得分:1)
替换此
db.execSQL(q);
用这个
sqLiteDatabase.execSQL(q);
首次安装应用时将触发 onCreate
,您需要使用sqLiteDatabase
引用来执行sql命令,并在实例化db
时初始化MyDbHelper
班级