数据库从外部存储SD卡打开

时间:2018-01-22 14:04:21

标签: android sql database sqlite android-studio

持续努力在设备中创建数据库由于运行权限问题,我在运行应用程序时无法在Samsung设备中创建数据库文件。所以我试图从已经提供数据的SD卡打开db文件。任何人都可以提供同样的建议。我的数据库代码如下。



package com.bar.example.androidspinnerexample;

    import java.util.ArrayList;
    import java.util.List;
    import java.io.File;

    import android.os.Environment;
    import android.os.StatFs;
    import android.util.Log;
    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;

    public class DatabaseHandler extends SQLiteOpenHelper {
        // Database Version
        public static final int DATABASE_VERSION = 1;

        // Database Name
        public static final String DATABASE_NAME = "spinnerExample";
        private static String DB_PATH = "/sdcard/android/com.bar.example.androidspinnerexample/databases/spinnerExample.db";

        // Labels table name
        public static final String TABLE_LABELS = "labels"; //<<<< Made public
        public static final String TABLE_LABELS1= "labels1";
        public static final String TABLE_LABELS2= "labels2";
        // Labels Table Columns names
        public static final String KEY_ID4 = "input_label";
        public static final String KEY_ID = "id";           //<<<< Made public
        public static final String KEY_NAME = "name";       //<<<< made public
        public static final String KEY_ID1 = "id1";           //<<<< Made public
        public static final String KEY_NAME1 = "name1";
        public static final String KEY_1 = "number";           //<<<< Made public
        public static final String KEY_2 = "outletname";       //<<<< made public
        public static final String KEY_3 = "sunday";           //<<<< Made public
        public static final String KEY_4 = "monday";
        public static final String KEY_5 = "tuesday";
        public static final String KEY_6 = "wednesday";
        public static final String KEY_7 = "thursday";
        public static final String KEY_8 = "saturday";
        public static final String KEY_9 = "closed";
        public static final String KEY_10 = "calling";

        public DatabaseHandler(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        // Creating Tables
        @Override
        public void onCreate(SQLiteDatabase db) {
            // Category table create query
            String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
                    + KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
            String CREATE_CATEGORIES_TABLE1 = "CREATE TABLE " + TABLE_LABELS1 + "("
                    + KEY_ID1+ " TEXT," + KEY_NAME1+ " TEXT)";
            db.execSQL(CREATE_CATEGORIES_TABLE);
            db.execSQL(CREATE_CATEGORIES_TABLE1);
        }

        // Upgrading database
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // Drop older table if existed
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS1);
            // Create tables again
            onCreate(db);
        }

        // Added for adding new data
        public void insertlabel(String id, String label) {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues cv = new ContentValues();
            cv.put(KEY_ID,id);
            cv.put(KEY_NAME,label);
            db.insert(TABLE_LABELS,null,cv);
            db.close();
        }

        /**
         * Inserting new lable into lables table
         * */
            public void insertLabel(String message1, String message2,String message3,String message4,String message5,String message6,String message7,String message8,String message9,String message10){
                SQLiteDatabase db = this.getWritableDatabase();

                ContentValues values = new ContentValues();

                values.put(KEY_1, message1);
                values.put(KEY_2, message2);
                values.put(KEY_10,message10);
                values.put(KEY_3,message3);
                values.put(KEY_4,message4);
                values.put(KEY_5,message5);
                values.put(KEY_6,message6);
                values.put(KEY_7,message7);
                values.put(KEY_9,message9);

                values.put(KEY_8,message8);


                // Inserting Row
                db.insert(TABLE_LABELS2, null, values);
                db.close(); // Closing database connection
            }

        public void insertLabel1(String label){
            SQLiteDatabase db = this.getWritableDatabase();

            ContentValues values = new ContentValues();
            values.put(KEY_NAME1, label);

            // Inserting Row
            db.insert(TABLE_LABELS1, null, values);
            db.close(); // Closing database connection
        }
        public void insertLabel2(String label){
            SQLiteDatabase db = this.getWritableDatabase();


            ContentValues values = new ContentValues();
            values.put(KEY_NAME1, label);
            values.put(KEY_10, label);
            values.put(KEY_ID, label);

            db.insert(TABLE_LABELS2, null, values);
            db.close(); // Closing database connection
        }

        public List<String> getAllLabels(){
            List<String> labels = new ArrayList<String>();

            // Select All Query
            String selectQuery = "SELECT  * FROM " + TABLE_LABELS1;

            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);

            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    labels.add(cursor.getString(1));
                } while (cursor.moveToNext());
            }

            // closing connection
            cursor.close();
            db.close();

            // returning lables
            return labels;
        }
        public List<String> getAllLabels1(){
            List<String> labels = new ArrayList<String>();

            // Select All Query
            String selectQuery = "SELECT  count (*) FROM " + TABLE_LABELS;

            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor1 = db.rawQuery(selectQuery, null);
            final ArrayList<String> row1 = new ArrayList<String>();
            // looping through all rows and adding to list
            if (cursor1.moveToFirst()) {
                do {
                    labels.add(cursor1.getString(1));
                } while (cursor1.moveToNext());
            }

            // closing connection
            cursor1.close();
            db.close();

            // returning lables
            return labels;
        }




        // Added to get Cursor for Simple CursorAdapter
        public Cursor getAllLabelsAsCursor() {
            String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
            return this.getWritableDatabase().query(TABLE_LABELS,columns,null,null,null,null,null);
        }

        public Cursor getAllLabelsExceptedSelected(long selected) {
            String[] columns = new String[]{"rowid AS _id, *"};
            String whereclause = "rowid <> ?";
            String[] whereargs = new String[]{String.valueOf(selected)};
            return this.getWritableDatabase().query(TABLE_LABELS,
                    columns,
                    whereclause,
                    whereargs,
                    null,
                    null,
                    null
            );
        }

        public Cursor getByRowid(long id) {
            String[] columns = new String[]{"rowid AS _id, *"};
            return this.getWritableDatabase().query(
                    TABLE_LABELS,
                    columns,
                    "rowid=?",
                    new String[]{String.valueOf(id)},
                    null,null,null
            );


        }

    }
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

使用此代码将您的数据库导出到内部存储

private void exportDatabase(){
    File data = Environment.getDataDirectory();
    FileChannel source=null;
    FileChannel destination=null;
    String currentDBPath = "/data/"+ "your_package_name" +"/databases/your_db_name.db";
    String backupDBPath = "/sdcard/your_db_name.db";
    File currentDB = new File(data, currentDBPath);
    File backupDB = new File(backupDBPath);
    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        Toast.makeText(this, "DB Exported!", Toast.LENGTH_LONG).show();
    } catch(IOException e) {
        e.printStackTrace();
    }
}

并在清单

中添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />