【问题标题】:What is the best way to use a single instance of SQLiteOpenHelper among two different activities?在两个不同的活动中使用单个 SQLiteOpenHelper 实例的最佳方法是什么?
【发布时间】:2016-05-11 21:02:07
【问题描述】:

我第一次在 Android (Java) 中使用 sqlite 数据库编写应用程序。

两个活动必须保存一些信息,所以我在两个活动中都使用MySQLiteHelper 来访问数据库。

我读到here 认为将SQLiteOpenHelper 构建为静态数据成员可能是一个好习惯,所以我这样做了。

静态工厂方法确保任何时候都只存在一个DatabaseHelper实例。

我在每个活动中创建一个SQLiteOpenHelper,它使用getWritableDatabase() 方法,但我不知道在哪里使用close() 方法。

这个方法应该在每次修改后使用还是在活动结束时使用一次?

谢谢你=)

【问题讨论】:

  • 咒语:open, use, close
  • 您的两个活动会同时进行吗?可能不是。在这种情况下,我认为不需要共享 SQLiteOpenHelper。每个 Activity 都可以在运行时创建自己的实例并正确关闭它。
  • @Marten,活动不会同时运行。谢谢你的回答。

标签: java android android-sqlite


【解决方案1】:

您需要创建一个类,在其中放置所有常用方法、常量、变量等。

然后你将不得不在这个类中移动“getWritableDatabase()”并请。我建议你永远记得关闭你的数据库调用。用“close()”。

但这里使用的实际解决方案如下:

在我的应用程序中,我有不同的数据库适配器,这只是一个示例:

package com.app.android;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter {

    public static final String KEY_ROWID = "id";
    public static final String KEY_NAME = "name";
    public static final String KEY_EMAIL = "email";
    public static final String TAG = "DBAdapter";

    //public static final String DATABASE_NAME = "my_db";
    //public static final String DATABASE_TABLE = "contacts";
    //public static final int DATABASE_VERSION = 1;

    public static final String START_TBL_CREATION = "create table "+Appiah.DATABASE_TABLE+" (_id integer primary key autoincrement, ";

    public static final String [] TABLE_COLUMNS_TO_BE_CREATED = new String []{
        KEY_NAME+" text not null, ",
        KEY_EMAIL+" text not null"
    };

    public static final String END_TBL_CREATION = ");";

    private static final String DATABASE_CREATE = START_TBL_CREATION
            + TABLE_COLUMNS_TO_BE_CREATED[0]
            + TABLE_COLUMNS_TO_BE_CREATED[1]
    + END_TBL_CREATION;

    private final Context context;

    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;

    public DBAdapter (Context ctx){
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);//there would be an error initially but just keep going...
    }

    private static class DatabaseHelper extends SQLiteOpenHelper{//after importing for "SQLiteOpenHelper", Add unimplemented methods

        DatabaseHelper(Context context){
            super (context, Appiah.DATABASE_NAME, null, Appiah.DATABASE_VERSION);//pls. note : "Appiah" is the class in which all the common methods, variables, etc. are sitting.
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            try{
                db.execSQL(DATABASE_CREATE);
            }catch(SQLException e){
                e.printStackTrace();
            }

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version "+ oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS contacts");
            onCreate(db);
        }
    }

    //opens the database
    public DBAdapter open() throws SQLiteException{
        db = DBHelper.getWritableDatabase();
        return this;
    }

    //closes the database
    public void close(){
        DBHelper.close();
    }

    //insert a contact into the database
    public long insertContact(String name, String email){
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);
        initialValues.put(KEY_EMAIL, email);
        return db.insert(Appiah.DATABASE_TABLE, null, initialValues);
    }

    //deletes a particular contact
    public boolean deleteContact(long rowId){
        String whereClause = KEY_ROWID + "=" + rowId;
        String[] whereArgs = null;
        return db.delete(Appiah.DATABASE_TABLE, whereClause, whereArgs) > 0;
    }

    //retrieves all the contacts
    public Cursor getAllContacts(){
        String[] columns = new String[]{KEY_ROWID, KEY_NAME, KEY_EMAIL};
        String selection = null;
        String[] selectionArgs = null;
        String groupBy = null;
        String having = null;
        String orderBy = null;
        return db.query(Appiah.DATABASE_TABLE, columns, selection, selectionArgs, groupBy, having, orderBy);
    }

    //retrieve a particular contact with ID as input
    public Cursor getContact_with_ID(long rowId) throws SQLException {
        boolean distinct = true;
        String table = Appiah.DATABASE_TABLE;
        String [] columns = new String []{KEY_ROWID, KEY_NAME, KEY_EMAIL};
        String selection = KEY_ROWID + "=" + rowId;
        String [] selectionArgs = null;
        String groupBy = null;
        String having = null;
        String orderBy = null;
        String limit = null;
        Cursor mCursor = db.query(distinct, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);

        if(mCursor != null){
            mCursor.moveToFirst();
        }

        return mCursor;

    }

    public Cursor getContact_with_nameEntered(String name_str) throws SQLException {
        boolean distinct = true;
        String table = Appiah.DATABASE_TABLE;
        String [] columns = new String []{KEY_ROWID, KEY_NAME, KEY_EMAIL};
        String selection = KEY_NAME + "=" + name_str;//check again and do "%" thing to expand scope and increase chances of a name getting found or populated
        String [] selectionArgs = null;
        String groupBy = null;
        String having = null;
        String orderBy = null;
        String limit = null;
        Cursor mCursor = db.query(distinct, table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);

        if(mCursor != null){
            mCursor.moveToFirst();
        }

        return mCursor;

    }

    //update a contact
    public boolean updateContact(long rowId, String name, String email){
        ContentValues args = new ContentValues();
        args.put(KEY_NAME, name);
        args.put(KEY_EMAIL, email);

        String table = Appiah.DATABASE_TABLE;
        ContentValues values = args;
        String whereClause = KEY_ROWID + "=" + rowId;
        String []whereArgs = null;

        return db.update(table, values, whereClause, whereArgs) > 0;
    }

    /*

     TO USE ANY OF THE ABOVE METHODS :
     1. type this before in your "onCreate()" : DBAdapter db = new DBAdapter(this);
     2. in the special case of getting all contacts to display : do the ff : 

        db.open();
        Cursor c = db.getAllContacts();
        if(c.moveToFirst()){
            do{
                textView.setText("ID : " + c.getString(0) + "\nName : " + c.getString(1) + "\nEmail Address : " + c.getString(2) );
            }while(c.moveToNext());//the "while" added ensures that, the looping process occurs
        }
        db.close();

     */

}

我希望这会有所帮助。它可以变得更深,但我希望这会有所帮助。一切顺利。

【讨论】:

  • 非常感谢您提供所有这些建议和分享这个例子! =)
  • 欢迎您加入 Galabyca。我很高兴能帮上忙。干杯,一切顺利。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-16
  • 1970-01-01
相关资源
最近更新 更多