我编写了一个方法(verifyUser)来检查用户是否已经存在于数据库中,但是出现此错误:
(java.lang.NullPointerException:尝试调用虚拟方法 'android.database.sqlite.SQLiteDatabase com.example.testapp.DatatBaseHelper.getReadableDatabase()'为null 对象参考)
那是我的ContentProvider类:
public class TestProvider extends ContentProvider {
private DatatBaseHelper helper;
private SQLiteDatabase db;
public static final String LOG_TAG = TestProvider.class.getSimpleName();
private static final int test=1;
private static final int test_id=2;
private static final UriMatcher urim=new UriMatcher(UriMatcher.NO_MATCH);
static{
urim.addURI(Test.test.authority,Test.test.TABLE_NAME,test);
urim.addURI(Test.test.authority,Test.test.TABLE_NAME+"/#",test_id);
}
@Override
public boolean onCreate() {
helper=new DatatBaseHelper(getcontext());
return false;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri,@Nullable String[] projection,@Nullable String selection,@Nullable String[] selectionArgs,@Nullable String sortOrder) {
int match=urim.match(uri);
db=helper.getReadableDatabase();
Cursor c;
switch(match){
case test:
c=db.query(Test.test.TABLE_NAME,projection,selection,selectionArgs,null,sortOrder);
break;
case test_id:
selection= Test.test.ID+"=?";
selectionArgs=new String[]{String.valueOf(Contenturis.parseId(uri))};
c=db.query(Test.test.TABLE_NAME,sortOrder);
break;
default:
throw new IllegalStateException("Cannot query form: " + uri);
}
return null;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri,@Nullable Contentvalues values) {
db=helper.getwritabledatabase();
String email=values.getasString(Test.test.EMAIL);
int match=urim.match(uri);
switch (match){
case test:
int id=(int)(db.insert(Test.test.TABLE_NAME,values));
uri= Contenturis.withAppendedId(uri,id);
}
return uri;
}
@Override
public int delete(@NonNull Uri uri,@Nullable String[] selectionArgs) {
return 0;
}
@Override
public int update(@NonNull Uri uri,@Nullable Contentvalues values,@Nullable String[] selectionArgs) {
return 0;
}
public boolean verifyUser(String email){
SQLiteDatabase db=helper.getReadableDatabase();
Cursor c;
String pro[]={Test.test.ID};
String select=Test.test.EMAIL+"=?";
String args[]={email};
c=db.query(Test.test.TABLE_NAME,pro,select,args,null);
if(c.getcount()>0){
return true;
}
return false;
}
那是我的数据库类:
public class DatatBaseHelper extends SQLiteOpenHelper {
public static final String DB_NAME="dress.db";
public static final int DB_VERSION=1;
public DatatBaseHelper(Context c){
super(c,DB_NAME,DB_VERSION);
}
private String TABLE_CREATE= "CREATE TABLE " + test.TABLE_NAME+ "( "+
test. ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"+ test.NAME+" TEXT NOT NULL,"+
test. EMAIL+" TEXT NOT NULL,"+ test.PASSWORD+ " TEXT NOT NULL);";
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) {
}
}