我想请问下,为什么我往数据库插入语句时,总报
空指针异常,具体代码如下:
下面代码是我建库和表的,还有插入方法:
public class DBNews {
private static final String DATABASE_NAME = "NewsDB.db";
private static final String DB_TABLE1 = "People";
private static final String DB_TABLE2 = "News";
private static final int DB_VERSON = 1;
public static final String KEY_ID = "id";
public static final String KEY_Name = "name";
public static final String KEY_Password = "password";
public static final String New_Id="id";
public static final String New_Name="name";
public static final String New_Matter="matter";
public static final String New_Data="dataTime";
private SQLiteDatabase db;
private final Context context;
private Dbnewpeople newpeople;
public DBNews(Context _context) {
context = _context;
}
public void open() throws SQLiteException {
newpeople = new Dbnewpeople(context, DATABASE_NAME, null, DB_VERSON);
try {
db = newpeople.getWritableDatabase();
} catch (Exception ex) {
db = newpeople.getReadableDatabase();
}
}
public void close() {
if (db != null) {
db.close();
db = null;
}
}
private static class Dbnewpeople extends SQLiteOpenHelper {
public Dbnewpeople(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
private static final String DB_CREATEPEOPLE = "create table " + DB_TABLE1
+ "(" + KEY_ID + " integer primary key autoincrement,"
+ KEY_Name + " text not null," + KEY_Password + " text not null);";
private static final String DB_CREATENEWS= "create table " + DB_TABLE2
+ "(" + New_Id + " integer primary key autoincrement,"
+ New_Name + " text not null," + New_Matter + New_Data + " integer);";
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_CREATEPEOPLE);
db.execSQL(DB_CREATENEWS);
}
@Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
_db.execSQL("DROP TABLE IF EXTSTS" + DB_TABLE1);
_db.equals("DROP TABLE IF EXTSTS"+DB_TABLE2);
onCreate(_db);
}
}
//添加数据
public long insert(Peoples people){
Log.i("tag", "aaa");
//ContentValues类是一个数据承载容器,主要用来向数据库表中添加一条数据
ContentValues newValues=new ContentValues();
//newValues.put(KEY_ID, people.nameid);
newValues.put(KEY_Name, people.name);
newValues.put(KEY_Password, people.password);
return db.insert(DB_TABLE1, null, newValues);
}
下面是我插入方法调用的地方,其中运行说的是long a=dbnew.insert(peoples);这句报
空指针异常
if(etpassword1.getText().toString().equals(etpassword2.getText().toString())){
peoples.setName(etname1.getText().toString());
peoples.setPassword(etpassword1.getText().toString());
long a=dbnew.insert(peoples);
Toast.makeText(RegisterActivity.this, "添加成功!"+a,Toast.LENGTH_LONG).show();
Log.i("tag", "succsful");
}
------解决方案--------------------
dbnew为null呗,自己看看是什么原因导致dbnew为null的