I find it hard to understand how SQLite databases work in android. I created a DatabaseHelper.java class that looks like this:
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 know, this works and is checked using the adb console.
My question is: how can I query this database in the application from another action, for example, I want my database to query the database: SELECT title FROM books; which will return the headers from the table of books to me, how can I switch to connecting to the database, running this query, and then saving all the results to an array?
---------------------------------- Edit ------------ --- -------------------------
Right in the part where I want to execute the request, I posted 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();
}
, . . , , . cont_array if ListView. - , , LogCat , , ?