Well this is my DatabaseHelper class
public class DatabaseHelper extends SQLiteOpenHelper {
static final String dbName="demoDB";
public DatabaseHelper(Context context) {
super(context, dbName, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS players (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"playerName TEXT)";
db.execSQL(sql);
ContentValues values = new ContentValues();
values.put("playerName", "John");
db.insert("players", "playerName", values);
values.put("playerName", "George");
db.insert("players", "playerName", values);
values.put("firstName", "Marie");
db.insert("players", "playerName", values);
System.out.println("Hello");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS players");
onCreate(db);
}
}
And in my main activity this is what I do to get its data.
if (cursor!= null) {
if (cursor.moveToFirst()) {
do {
System.out.println(cursor.getString(cursor.getColumnIndexOrThrow("playerName")));
} while (cursor.moveToNext());
}
}
Why the column is not created?
and I am getting this exception.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mkyong.android/com.mkyong.android.Stats}: java.lang.IllegalArgumentException: column 'playerName' does not exist
Are you selecting anything before you interact with the cursor? Your cursor should be the result from a “Select…” SQL call, but I don’t see one in your DatabaseHelper or anything in your MainActivity to indicate you are doing any sort of selection.
Also, when you are inserting values into your table , I believe the second parameter should be null [
db.insert("players", null, values)]. It’s intended for thenullColumnHack, which you use if you aren’t entering any data into row.Edit
Well, so far you’ve created a table and inserted some records. The next step would be to create basic CRUD operations (Create, Retrieve, Update, Delete), but for your case, you need to start with Retrieve.
Retrieve basically means you are reading/retrieving data from your database, so you can use it in your application. When you read the data from a DB, it gets stored in a Cursor. So, you need to:
Here is a link to a great tutorial on setting up a databse and how to create CRUD operations for your database. For now, scroll down and read up on the Retrieve operation.
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
I would read the entire tutorial if I were you. There are lots of other helpful tips and suggestions that will be well worth the investment now. For example, creating constants in your DatabaseHelper class for the table name, database name, column name is a really good idea because sooner or later you’re going to make a typo if you keep typing in all the column and table names manually. If you use variables, you’ll get a compile error rather than an exception at runtime.