从新应用程序访问现有数据库

时间:2015-03-31 05:51:34

标签: android android-sqlite android-contentprovider

我使用特定应用程序在外部存储中创建了数据库,并使用相同的应用程序创建了表。现在我想从新的Android应用程序访问该数据库中的数据,所以我必须使用内容提供商,否则我可以直接访问数据库而不使用内容提供商?请帮忙!

listView.setOnItemClickListener(new OnItemClickListener() {

        private static final int DATABASE_VERSION = 5;
        private static final String UID = "_id";
        private static final String STEP = "Steps";
        private static final String ImagePath = "Image_Path";
        private static final String AudioPath = "Audio_Path";


        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // TODO Auto-generated method stub
            Message.message(KitchenData.this, "Click List Item Number");
            SQLiteDatabase db = openOrCreateDatabase("/mnt/sdcard/Kitchen_Data.db",
                    MODE_MULTI_PROCESS, null);


            try
            {
String CREATE_TABLE = "CREATE Table " + li.get(position) + "("+ UID + " INTEGER PRIMARY KEY AUTOINCREMENT ," + STEP+ " VARCHAR(255) NOT NULL ,"+ImagePath+" VARCHAR(255) NOT NULL,"+AudioPath+" VARCHAR(255) NOT NULL); ";
            db.execSQL(CREATE_TABLE);
             pos=li.get(position);
            }catch(SQLException e)
            {
                Message.message(KitchenData.this,"Errors in creating table "+e);
            }

1 个答案:

答案 0 :(得分:2)

private static String DB_NAME ="YourDbName";// Database name 

此处的DB_NAME是您的数据库的名称。假设您在assets文件夹中有数据库的副本,例如,如果您的数据库名称是mbDB,那么DB_NAME的值将是mbDB。

private static String DB_NAME ="ordersDB";

将数据库复制到程序中的ASSETS文件夹中。

将以下代码放入Dbhelper类中,并在CreateDatabase函数中调用它。

private void copyDataBase() throws IOException
{
    InputStream mInput = mContext.getAssets().open(DB_NAME);
    String outFileName = DB_PATH + DB_NAME;
    OutputStream mOutput = new FileOutputStream(outFileName);
    byte[] mBuffer = new byte[1024];
    int mLength;
    while ((mLength = mInput.read(mBuffer))>0)
    {
        mOutput.write(mBuffer, 0, mLength);
    }
    mOutput.flush();
    mOutput.close();
    mInput.close();
}

希望这是你需要的答案:)