Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite database in android and java

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?

like image 476
SamRowley Avatar asked May 20 '26 01:05

SamRowley


1 Answers

Inside your activity do the following:

public class DBAct extends Activity {
    private DataHelper dh;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //init your activity here
        //e.g. setContentView(R.layout.main);

        dh = new DataHelper(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(0));
            } while (cursor.moveToNext());
        }
        if (cursor != null && !cursor.isClosed()) {
           cursor.close();
        }
        db.close();
    }
}
like image 134
Olivier Heidemann Avatar answered May 21 '26 14:05

Olivier Heidemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!