Search code examples
androidsqliteddmssqliteopenhelper

Fetch data from existing sqlite database


I am having an existing sqlite database. I am developing an android app and I want to connect it with this existing sqlite DataBase.

Problem 1: I have already included the sqlite database in my project via "DDMS push database function" as per my instructor's advise. Now I want to fetch the data from database, do I need to use SQLiteOpenHelper. If yes, how to use it and what will be coded in onCreate(SQLiteDatabase db) function and onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) function as we already have the Database with us, we don't really need to create it.

Problem 2: What should be done to simply fetch the required data from the existing database.

Being a newbie, I am quite confused, can someone please explain these concepts and guide me to overcome this issue. Any help would be appreciated.

I have seen a tutorial also for this purpose as sugggested by @TronicZomB, but according to this tutorial (http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/), I must be having all the tables with primary key field as _id.

I have 7 tables namely destinations, events, tour, tour_cat, tour_dest, android_metadata and sqlite_sequence. Out of all, only tour_dest is not fulfilling the conditions of having a primary key named as _id. How to figure out this one?

Following is the screenshot of table which is lacking the primary key field necessary for binding id fields of database tables. Screenshot of table which is lacking the primary key field necessary for binding id fields of database tables.


Solution

  • The onCreate and onUpgrade methods will be empty since you already have the database. There is a great tutorial on how to achieve this here.

    You could then access the database like such (example):

    public ArrayList<String> getValues(String table) {
        ArrayList<String> values = new ArrayList<String>();
    
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT value FROM " + table, null);
    
        if(cursor.moveToFirst()) {
            do {
                values.add(cursor.getString(cursor.getColumnIndex("value")));
            }while(cursor.moveToNext());
        }
    
        cursor.close();
        db.close();
        return values;
    }