I am having a bit of difficulty understanding the concepts of how SQLite databases work in android. I have created a DatabaseHelper.java class which is as follows:
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "library.db";
public static final String TITLE = "title";
public static final String MUSICTITLE = "musictitle";
public static final String AUTHOR = "author";
public static final String ARTIST = "artist";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL( "CREATE TABLE music (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, artist TEXT);");
db.execSQL( "CREATE TABLE books (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, author TEXT);");
db.execSQL( "CREATE TABLE movies (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
android.util.Log.v("Constants",
"Upgrading database which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS books");
db.execSQL("DROP TABLE IF EXISTS music");
db.execSQL("DROP TABLE IF EXISTS movies");
onCreate(db);
}
}
As far as i'm aware this does work and has been checked using the adb console.
My question is how do I query this database within the app from a different activity, for example I want in my app to query the database: SELECT title FROM books; which will return me the titles from the book table, how do I go about connecting to the database, running this query then storing all the results into an array?
----------------------------------Edit----------------------------------------
Right so in the part where I want to query I have placed this code:
if (category.equals("Books")){
img.setImageResource(R.drawable.book);
ArrayList<String> list = new ArrayList<String>();
dh = new DatabaseHelper(this);
SQLiteDatabase db = dh.getReadableDatabase();
Cursor cursor = db.query("books", new String[] { "title" }, null, null, null, null, "title desc");
if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(1));
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
list.add("Test");
cont_array = (String[]) list.toArray();
db.close();
}
Which passes the Category down prom the previous activity. From Olivier's answer. This code crashes the application and I have no idea why. the variable cont_array is used after this if statement to populate a ListView. Anybody got any ideas where I am going wrong, there is nothing in LogCat to tell me where it is failing?