Android SQLite database shared between activities

后端 未结 2 794
粉色の甜心
粉色の甜心 2021-01-31 12:10

What is the best way to share one SQLite DB between several activities? Tables from the DB are shown in ListView, and also deleting/inserting records is to be performed. I heard

相关标签:
2条回答
  • 2021-01-31 13:11

    You could do this implementing a BaseActivity class what is extended by all Activity classes in the application:

    public class BaseActivity extends Activity {
    
        protected static SQLiteOpenHelper database;
    
        @Override
        protected void onPause() {
    
                // TODO close database
    
                super.onPause();
        }
    
        @Override
        protected void onResume() {
    
                super.onResume();
    
                // TODO open database
        }
    }
    
    
    
    
    public class OneSubActitivy extends BaseActivity {
    
        // methods using database from BaseActivity
    }
    
    0 讨论(0)
  • 2021-01-31 13:14

    Create an Application class for your app. This will remain active in memory for as long as any part of your App is running. You can create your DB from the onCreate method and clean it up in the onTerminate method. (Note that there is no guarantee that onTerminate will be called, so you should be careful about what you depend upon here. However, since a SQLite database is just a file, and is agressively flushed, the close operation is a courtesy more than a necessity.)

    You can access the application from any Activity via "getApplication", so the DB will always be available to you.

    For more info, see http://developer.android.com/guide/appendix/faq/framework.html#3.

    Update:

    As requested, here's an example of using getApplication. It's really incredibly simple.

      SQLiteDatabase mDB;
      @Override protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDB = ((MyApplication)getApplication()).mDB;
      }
    

    If every activity includes this code, then every activity will have its own mDB field which references the same underlying shared DB object.

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