I have created a simple database table with username, title,and question. Here's my code for inserting and reading the data
public long insertData(String usernames,String title, String question) {
SQLiteDatabase sqLiteDatabase =databaseHelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.USER, usernames);
contentValues.put(DatabaseHelper.TITLE,title);
contentValues.put(DatabaseHelper.QUESTION,question);
long id =sqLiteDatabase.insert(DatabaseHelper.TABLE_NAME,null,contentValues);
return id;
}
public String readData(){
SQLiteDatabase sqLiteDatabase =databaseHelper.getWritableDatabase();
String[] columns = {DatabaseHelper.USER};
Cursor cursor = sqLiteDatabase.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext()) {
int index0 = cursor.getColumnIndex(DatabaseHelper.UID);
int index1 = cursor.getColumnIndex(DatabaseHelper.USER);
int index2 = cursor.getColumnIndex(DatabaseHelper.TITLE);
int index3 = cursor.getColumnIndex(DatabaseHelper.QUESTION);
int cid = cursor.getInt(index0);
String username = cursor.getString(index1);
String title = cursor.getString(index2);
String question = cursor.getString(index3);
buffer.append(cid+" "+ username+" "+ title+ " "+ question);
}
return buffer.toString();
}
and here's my code for creating the database
static class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "usserdatabase";
private static final String TABLE_NAME = "usertable";
private static final String UID = "_id";
private static final int DATABASE_VERSION=1;
private static final String USER = "UserName";
private static final String TITLE="Title";
private static final String QUESTION = "Question";
private static final String UPGRADE_DATABASE = "DROP TABLE IF EXISTS "+ TABLE_NAME;
private static final String CREATE_QUERY = "CREATE TABLE "+TABLE_NAME+" ("+UID +" INTEGER PRIMARY KEY AUTOINCREMENT, "+USER+" VARCHAR(255), "+TITLE+" VARCHAR(255), "+QUESTION+" VARCHAR(255));";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("Check","Constructer was called");
}
@Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(CREATE_QUERY);
Log.d("Check","Database Created Successfully!");
}catch (SQLException e){
Log.e("Check",e.getMessage());
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(UPGRADE_DATABASE);
onCreate(db);
Log.d("Check","Databasae upgraded succesfully");
} catch (SQLException e) {
Log.e("Check",e.getMessage());
}
}
}
Whenever i call readData(), my app crashes. It saysjava.lang.IllegalStateException: Couldn't read row 0, col 1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Aucun commentaire:
Enregistrer un commentaire