大家好我试图从一个名为contacts的表中检索数据,但它在
给我一个空指针异常Cursor cursor = database.query(ContactsDBOpenHelper.TABLE_CONTACTS,allcolumns,null,null,null,null,null);
任何人都可以提出什么错误? 我在表格中有适当的数据。
公共类ViewAllActivity扩展了ListActivity {
SQLiteOpenHelper dbhelper;
SQLiteDatabase database;
ContactsDataSource contactsDataSource;
public static final String[] allcolumns = {
ContactsDBOpenHelper.COLUMN_SEQUENCE,
ContactsDBOpenHelper.COLUMN_NAME,
ContactsDBOpenHelper.COLUMN_DEPT,
ContactsDBOpenHelper.COLUMN_EMAIL,
ContactsDBOpenHelper.COLUMN_PHONE,
ContactsDBOpenHelper.COLUMN_ADDRESS,
ContactsDBOpenHelper.COLUMN_ZIPCODE
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
contactsDataSource = new ContactsDataSource(this);
contactsDataSource.open();
dbhelper = new ContactsDBOpenHelper(this);
dbhelper.getWritableDatabase();
List<Contact> contacts = viewAllC();
ArrayAdapter<Contact> adapter = new ArrayAdapter<Contact>(ViewAllActivity.this,R.layout.list,contacts);
setListAdapter(adapter);
}
public List<Contact> viewAllC() {
List<Contact> contacts = new ArrayList<Contact>();
Cursor cursor = database.query(ContactsDBOpenHelper.TABLE_CONTACTS,allcolumns,null,null,null,null,null);
Log.i("LOGCAT", "rows returned : " + cursor.getCount());
Contact contact;
if(cursor.getCount()>0) {
while(cursor.moveToNext()) {
contact = new Contact();
contact.setSequence(cursor.getLong(cursor.getColumnIndex(ContactsDBOpenHelper.COLUMN_SEQUENCE)));
contact.setName(cursor.getString(cursor.getColumnIndex(ContactsDBOpenHelper.COLUMN_NAME)));
contact.setDepartment(cursor.getString(cursor.getColumnIndex(ContactsDBOpenHelper.COLUMN_DEPT)));
contact.setEmail(cursor.getString(cursor.getColumnIndex(ContactsDBOpenHelper.COLUMN_EMAIL)));
contact.setPhone(cursor.getString(cursor.getColumnIndex(ContactsDBOpenHelper.COLUMN_PHONE)));
contact.setAddress(cursor.getString(cursor.getColumnIndex(ContactsDBOpenHelper.COLUMN_ADDRESS)));
contact.setZipCode(cursor.getLong(cursor.getColumnIndex(ContactsDBOpenHelper.COLUMN_ZIPCODE)));
contacts.add(contact);
}
}
return contacts;
}
}
This is My open helper
public class ContactsDBOpenHelper extends SQLiteOpenHelper {
public ContactsDBOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
Log.i(LOGTAG, "Table has been created");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
}
答案 0 :(得分:0)
您忘记初始化database
。
首先实例化您的数据库助手,然后在其上调用getWritableDatabase()
以获得可以使用的SQLiteDatabase
:
SQLiteOpenHelper helper = new ContactsDBOpenHelper(this);
database = helper.getWritableDatabase();