Skip to content Skip to sidebar Skip to footer

Easy Database Access Methods In Android

I am currently following a SQLite access tutorial for Android. It has presented to me a sample 'DBAdapter' class, as below: import android.content.ContentValues; import android.con

Solution 1:

This method works well for me.

Create a DataHelper class that opens your database and maintains a reference to the database object and which exposes the database.

publicclassCustomDataHelper {

privatestaticfinalintDATABASE_VERSION=30;
publicSQLiteDatabasedb=null;

publicCustomDataHelper() {

    SQLiteOpenHelpero=newMyOpenHelper(CustomApp.app, "MyData.db");
    this.db = o.getWritableDatabase();

}

    // Rest of standard DataHelper classprivateclassMyOpenHelperextendsSQLiteOpenHelper {

    MyOpenHelper(Context context,String DatabaseName) {
        super(context, DatabaseName, null, DATABASE_VERSION);
    }

    @OverridepublicvoidonCreate(SQLiteDatabase db) {
              // Standard data code here
    }

    @OverridepublicvoidonUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
              // Standard data code here
    }

}

}

Extend your Application class and store your Data object as a static field within it. Modify your Android.manifest to use your custom app class instead of the default one.

publicclassCustomAppextendsApplication {

publicstatic CustomDataHelper data; // Access the data class from anywherepublicstatic CustomApp app; // Access the application context from anywhere@OverridepublicvoidonCreate() {
    super.onCreate();

    app = this;
    data = newCustomDataHelper();
}
}

Any classes that require data access can refer to this object and get a reference to the open database. You can then put all data access code within the class that it relates to.

e.g. In your Contact class you could have a "Save" method that gets the database from the Application class and performs all necessary commands to save the contact details. This keeps all your data access code in the classes that it relates to. i.e All code that modifies contacts is within your contact class.

publicclasscontact {

    publicvoidSave() {

        CustomApp.data.db.execSQL("Your SQL Here");
        // etc

    }

}

As the DataHelper is in a static field, you can access it from anywhere at any time and it already has its own context from the Application Class.

Note the above excludes any error handling for the sake of simplicity.

Post a Comment for "Easy Database Access Methods In Android"