如何 link 应用到外部 SQlite 数据库文件

How to link app to external SQlite database file

我正处于我的应用程序的最后一个障碍,并且一直试图将应用程序连接到我已经创建的名为 "health1.db" 的外部 SQLite 数据库文件。我希望我的应用程序从该文件中读取数据。我已经编写了一些代码,但该代码是从 /data/data/...

中的默认数据库文件夹中读取的

我已经将该数据库文件复制到 assets/databases 文件夹中。这是我的代码示例 ...

Tableclass定义

package com.example.ahmed.doctorsinbahrain9.database;

public class FacilitiesTable {
    public static final String TABLE_FACILITY = "facility";
    public static final String COLUMN_ID = "facilityId";
    public static final String COLUMN_TYPE = "type";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_PHONE_NUMBER = "phoneNumber";
    public static final String COLUMN_RATING = "rating";
    public static final String COLUMN_DISTANCE = "distance";
    public static final String COLUMN_DESCRIPTION = "description";
    public static final String COLUMN_IMAGE = "image";

    public static final String[] ALL_COLUMNS =
            {COLUMN_ID, COLUMN_TYPE, COLUMN_NAME, COLUMN_PHONE_NUMBER,
            COLUMN_RATING, COLUMN_DISTANCE, COLUMN_DESCRIPTION, COLUMN_IMAGE};
}

我的数据源class:

    package com.example.ahmed.doctorsinbahrain9.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.ahmed.doctorsinbahrain9.Facility;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class DataSource {

    private Context mContext;
    private SQLiteDatabase mDatabase;
    SQLiteOpenHelper mDbHelper;

    public DataSource(Context context) {
        this.mContext = context;
        mDbHelper = new DBHelper(mContext);
        mDatabase = mDbHelper.getWritableDatabase();
    }

    public void open() {
        mDatabase = mDbHelper.getWritableDatabase();
    }

    public void close() {
        mDbHelper.close();
    }

    public List<Facility> getAllFacilities() {
        List<Facility> facilities = new ArrayList<>();
        Cursor cursor = mDatabase.query(FacilitiesTable.TABLE_FACILITY, FacilitiesTable.ALL_COLUMNS,
                        null, null, null, null, null);

        while(cursor.moveToNext()) {
            Facility facility = new Facility();
            facility.setFacilityID(cursor.getString(cursor.getColumnIndex(FacilitiesTable.COLUMN_ID)));
            facility.setFacilityType(cursor.getString(cursor.getColumnIndex(FacilitiesTable.COLUMN_TYPE)));
            facility.setFacilityName(cursor.getString(cursor.getColumnIndex(FacilitiesTable.COLUMN_NAME)));
            facility.setFacilityPhoneNumber(cursor.getString(cursor.getColumnIndex(FacilitiesTable.COLUMN_PHONE_NUMBER)));
            facility.setFacilityRating(cursor.getFloat(cursor.getColumnIndex(FacilitiesTable.COLUMN_RATING)));
            facility.setFacilityDistance(cursor.getDouble(cursor.getColumnIndex(FacilitiesTable.COLUMN_DISTANCE)));
            facility.setFacilityDescription(cursor.getString(cursor.getColumnIndex(FacilitiesTable.COLUMN_DESCRIPTION)));
            facility.setFacilityImage(cursor.getString(cursor.getColumnIndex(FacilitiesTable.COLUMN_IMAGE)));
            facilities.add(facility);
        }

        return facilities;
    }
}

我的 DBHelper class:

public class DBHelper extends SQLiteOpenHelper {

    public static final String DB_FILE_NAME = "health1.db";
    public static final int DB_VERSION = 1;

    public DBHelper(Context context) {
        super(context, DB_FILE_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}

最后在我的 activity class 中编码:

public class DisplayActivity extends AppCompatActivity {

    DataSource mDataSource;                  // Make an instance of the DataSource class

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mDataSource = new DataSource(this);
        mDataSource.open();                 // Open database file

        List<Facility> listFromDB = mDataSource.getAllFacilities();
        FacilitiesAdapter adapter = new FacilitiesAdapter(this, listFromDB);
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.displayActivityRecyclerView);
        recyclerView.setAdapter(adapter);
    }
}

您在下面的代码中从资产文件夹访问您的 sqlite 数据库

    public class Databasehelper extends SQLiteOpenHelper
{
      private SQLiteDatabase myDataBase;
      private final Context myContext;
      private static final String DATABASE_NAME = "db.sqlite";
      public final static String DATABASE_PATH ="/data/data/com.shir60bhushan/databases/";
      public static final int DATABASE_VERSION = 1;
      //public static final int DATABASE_VERSION_old = 1;

      //Constructor
      public Databasehelper(Context context)
      {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.myContext = context;
      }

      //Create a empty database on the system
      public void createDatabase() throws IOException
      {
            boolean dbExist = checkDataBase();

            if(dbExist)
            {
                  Log.v("DB Exists", "db exists");
                  // By calling this method here onUpgrade will be called on a
                  // writeable database, but only if the version number has been
                  // bumped
                  //onUpgrade(myDataBase, DATABASE_VERSION_old, DATABASE_VERSION);
            }

            boolean dbExist1 = checkDataBase();
            if(!dbExist1)
            {
                  this.getReadableDatabase();
                  try
                  {
                        this.close();    
                        copyDataBase();
                  }
                  catch (IOException e)
                  {
                        throw new Error("Error copying database");
               }
            }
      }

      //Check database already exist or not
      private boolean checkDataBase()
      {
            boolean checkDB = false;
            try
            {
                  String myPath = DATABASE_PATH + DATABASE_NAME;
                  File dbfile = new File(myPath);
                  checkDB = dbfile.exists();
            }
            catch(SQLiteException e)
            {
            }
            return checkDB;
      }

      //Copies your database from your local assets-folder to the just created empty database in the system folder
      private void copyDataBase() throws IOException
      {
            String outFileName = DATABASE_PATH + DATABASE_NAME;
            OutputStream myOutput = new FileOutputStream(outFileName);
            InputStream myInput = myContext.getAssets().open(DATABASE_NAME);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0)
            {
                  myOutput.write(buffer, 0, length);
            }
            myInput.close();
            myOutput.flush();
            myOutput.close();
      }

      //delete database
      public void db_delete()
      {
            File file = new File(DATABASE_PATH + DATABASE_NAME);
            if(file.exists())
            {
                  file.delete();
                  System.out.println("delete database file.");
            }
      }

      //Open database
      public void openDatabase() throws SQLException
      {
            String myPath = DATABASE_PATH + DATABASE_NAME;
            myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
      }

      public synchronized void closeDataBase()throws SQLException
      {
            if(myDataBase != null)
                  myDataBase.close();
            super.close();
      }

      public void onCreate(SQLiteDatabase db)
      {
      }

      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
      {    
            if (newVersion > oldVersion)
            {
                  Log.v("Database Upgrade", "Database version higher than old.");
                  db_delete();
            }
      }

 //add your public methods for insert, get, delete and update data in database.
}

为了完成你想要的;在给定 class 中:DBHelper.class 定义为:

public class DBHelper extends SQLiteOpenHelper {
    public static final String DB_FILE_NAME = "health1.db";
  /*
   code , code...
  */

用外部数据库完整路径替换DB_FILE_NAME值("health1.db"):

    /*
     In this exemple, my data base with name "health1.db"  is currently present 
     on my sdcard, inside directory "myAppDir/"
    */
    public static final String DB_FILE_NAME = "/sdcard/myAppDir/health1.db";