Easy database access methods in Android

后端 未结 1 1960
不知归路
不知归路 2020-12-11 11:32

I am currently following a SQLite access tutorial for Android. It has presented to me a sample \'DBAdapter\' class, as below:

import android.content.ContentV         


        
相关标签:
1条回答
  • 2020-12-11 12:11

    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.

    public class CustomDataHelper {
    
    private static final int DATABASE_VERSION = 30;
    public SQLiteDatabase db = null;
    
    public CustomDataHelper() {
    
        SQLiteOpenHelper o = new MyOpenHelper(CustomApp.app, "MyData.db");
        this.db = o.getWritableDatabase();
    
    }
    
        // Rest of standard DataHelper class
    
    private class MyOpenHelper extends SQLiteOpenHelper {
    
        MyOpenHelper(Context context,String DatabaseName) {
            super(context, DatabaseName, null, DATABASE_VERSION);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
                  // Standard data code here
        }
    
        @Override
        public void onUpgrade(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.

    public class CustomApp extends Application {
    
    public static CustomDataHelper data; // Access the data class from anywhere
    
    public static CustomApp app; // Access the application context from anywhere
    
    @Override
    public void onCreate() {
        super.onCreate();
    
        app = this;
        data = new CustomDataHelper();
    }
    }
    

    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.

    public class contact {
    
        public void Save() {
    
            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.

    0 讨论(0)
提交回复
热议问题