我有使用数据库的源代码。
我的数据库代码在一个类中,当我从这个类中插入任何东西时没有问题。但是,如果在其他类中调用该方法,则会从该行显示错误消息“java.lang.nullpointerexception”SQLiteDatabase sd = getWritableDatabase();
这是我的主要课程:
public static class SchemaHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "adv_data.db";
// TOGGLE THIS NUMBER FOR UPDATING TABLES AND DATABASE
private static final int DATABASE_VERSION = 1;
SchemaHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// CREATE JOINT TABLE
db.execSQL("CREATE TABLE"+ JointTable.TABLE_NAME
+ "("+ JointTable.ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ JointTable.NAME +" TEXT, "
+ JointTable.FAMILY + " TEXT,"
+ JointTable.ADDRESS+"TEXT,"
+ JointTable.PARTICIPATIONNUM +"Text,"
+ JointTable.RECOGNITIONNUM + "TEXT,"
+ JointTable.USAGE +"TEXT );");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
Log.w("LOG_TAG", "Upgrading database from version "
+ oldVersion + " to " + newVersion + ", which will destroy all old data");
// KILL PREVIOUS TABLES IF UPGRADED
db.execSQL("DROP TABLE IF EXISTS "+ JointTable.TABLE_NAME);
// CREATE NEW INSTANCE OF SCHEMA
onCreate(db);
} // End of onUpdate class
=============================== 插入表================ ====================
public long addJoit(String name, String family, String address,
String participationNum ,String recognitionNum, String usage ){
ContentValues cv= new ContentValues();
cv.put(JointTable.NAME, name);
cv.put(JointTable.FAMILY, family);
cv.put(JointTable.ADDRESS, address);
cv.put(JointTable.PARTICIPATIONNUM, participationNum);
cv.put(JointTable.RECOGNITIONNUM,recognitionNum);
cv.put(JointTable.USAGE, usage);
SQLiteDatabase sd = this.getWritableDatabase();// this line get the error
long result= sd.insert(JointTable.TABLE_NAME,
JointTable.NAME, cv);
return result;
}
}
}
这是调用该方法的另一个类
MainActivity.SchemaHelper sh = new MainActivity.SchemaHelper(null);
long result= sh.addJoit("name", "family", "address", "participationNum", "recognitionNum", "usage");
我想知道原因谢谢