此应用程序在TextView中显示数据库中的一些数据
但每当我运行它时,由于java.lang.IllegalArgumentException: column
_ id'而导致的应用崩溃不存在,但_id
列存在。
起初,我使用了getColumnIndex()
经过一些研究后,我发现getColumnIndexOrThrow()
可以解决我的问题,但我无法理解为什么列_id
不存在。
我错过了导致此错误的内容吗?
private void displayDatabaseInfo() {
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {
petsEntry.COLUMN_ID,
petsEntry.COLUMN_NAME,
petsEntry.COLUMN_BREED,
petsEntry.COLUMN_GENDER,
petsEntry.COLUMN_WEIGHT };
Cursor cursor = db.query(
petsEntry.TABLE_NAME,
projection,
null,
null,
null,
null,
null);
TextView displayView = (TextView) findViewById(R.id.text_view_pet);
try {
displayView.setText("The pets table contains " + cursor.getCount() + " pets.\n\n");
displayView.append(petsEntry.COLUMN_ID + " - " +
petsEntry.COLUMN_NAME + " - " +
petsEntry.COLUMN_BREED + " - " +
petsEntry.COLUMN_GENDER + " - " +
petsEntry.COLUMN_WEIGHT + "\n");
//Error occurs at this line, The column becomes invisible from here
int idColumnIndex = cursor.getColumnIndexOrThrow(petsEntry.COLUMN_ID);
int nameColumnIndex = cursor.getColumnIndexOrThrow(petsEntry.COLUMN_NAME);
int breedColumnIndex = cursor.getColumnIndexOrThrow(petsEntry.COLUMN_BREED);
int genderColumnIndex = cursor.getColumnIndexOrThrow(petsEntry.COLUMN_GENDER);
int weightColumnIndex = cursor.getColumnIndexOrThrow(petsEntry.COLUMN_WEIGHT);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int currentID = cursor.getInt(idColumnIndex);
String currentName = cursor.getString(nameColumnIndex);
String currentBreed = cursor.getString(breedColumnIndex);
int currentGender = cursor.getInt(genderColumnIndex);
int currentWeight = cursor.getInt(weightColumnIndex);
displayView.append(("\n" + currentID + " - " +
currentName + " - " +
currentBreed + " - " +
currentGender + " - " +
currentWeight));
cursor.moveToNext();
}
} finally {
cursor.close();
}
}
PetDBHelper.java
public class PetDBHelper extends SQLiteOpenHelper {
private static final String LOG_TAG = PetDBHelper.class.getSimpleName();
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "pets.db";
private static final String SQL_EXECUTE = "CREATE TABLE " + petsEntry.TABLE_NAME + " ( " +
petsEntry.COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
petsEntry.COLUMN_NAME + " TEXT NOT NULL, " +
petsEntry.COLUMN_BREED + " TEXT, " +
petsEntry.COLUMN_GENDER + " INTEGER, " +
petsEntry.COLUMN_WEIGHT + " INTEGER );";
public PetDBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_EXECUTE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}