简体   繁体   English

如何将外部 SqliteDatabase 连接到 Android 应用程序?

[英]How to connect external SqliteDatabase to Android application?

here is my problem.这是我的问题。 I am creating my database of text in program called SqliteDbBrowser after that I want to put it into /assets/ folder in android and load it to the application.我在名为 SqliteDbBrowser 的程序中创建我的文本数据库之后,我想将其放入 android 中的 /assets/ 文件夹并将其加载到应用程序中。

All the tutorials assume that you don't have any database and you create it clean from application and then fill it.所有教程都假设您没有任何数据库,并且您从应用程序中创建干净然后填充它。

I have already put data into my database and don't want to create new one.我已经将数据放入我的数据库中,不想创建新的。

Here is some guy's tutorial http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/ and it somehow work's but it's not perfect, is it any other way to solve this ?这是一些人的教程http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/它以某种方式工作但并不完美,是否有其他方法可以解决这个问题? Using ony SQLiteOpenHelper not mixing stuff?使用任何 SQLiteOpenHelper 不混合东西?

I don't see the problem.我看不出问题。 I used that same example and it worked.我使用了同样的例子,它奏效了。 In my project I had to check and, eventually, load the missing tables on the internal DB.在我的项目中,我必须检查并最终在内部数据库上加载丢失的表。

The DB will not be erased, unless you state so.除非您声明,否则数据库不会被擦除。

Therefore adding new tables will not erase any pre-existing ones.因此,添加新表不会删除任何预先存在的表。

Anyway, you said 'it somehow work's but it's not perfect', what do you mean?无论如何,你说'它以某种方式工作,但它并不完美',你是什么意思? It either copies the tables or it doesn't.它要么复制表,要么不复制。 Right?对?

您提供的链接的示例运行良好,但最佳实践是在您的 android 应用程序中构建您的数据库,这样您就可以将准备好的数据库 DLL 与数据一起导出为插入语句,将这些插入语句添加到文件中,让我们在您的raw 文件夹,在创建数据库后,您可以读取插入语句并执行它们以插入数据。

First Put your Created Database in your Asset Folder.首先将您创建的数据库放在您的资产文件夹中。

Add Below Java File to your Project将下面的 Java 文件添加到您的项目中

package com.app.ourforms.database;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Vector;

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

public class DBConnect extends SQLiteOpenHelper {
    ArrayList<String> arraylistUrl;
    public int GetCursor;

    public DBConnect(Context context, String db_name) {
        super(context, db_name, null, 2);

        if (db != null && db.isOpen())
            close();

        this.myContext = context;
        DB_NAME = db_name;

        try {
            createDataBase();
            openDataBase();
        } catch (IOException e) {
            // System.out.println("Exception in creation of database : "+
            // e.getMessage());
            e.printStackTrace();
        }

    }

    public void createDataBase() throws IOException {
        // boolean dbExist = checkDataBase();

        boolean dbExist = databaseExist();

        if (dbExist) {
            // System.out.println("Database Exist");
        } else {
            this.getReadableDatabase();

            try {
                copyDatabase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    private void copyDatabase() throws IOException {
        InputStream input = myContext.getAssets().open(DB_NAME);
        String outputFileName = DB_PATH + DB_NAME;
        OutputStream output = new FileOutputStream(outputFileName);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }

        // Close the streams
        output.flush();
        output.close();
        input.close();
        // System.out.println(DB_NAME + "Database Copied !");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

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

    }

    public void openDataBase() throws SQLException {
        // Open the database
        String myPath = DB_PATH + DB_NAME;
        db = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    }

    public boolean isOpen() {
        if (db != null)
            return db.isOpen();
        return false;
    }

    @Override
    public synchronized void close() {
        if (db != null)
            db.close();
        super.close();
    }

    public boolean databaseExist() {
        File dbFile = new File(DB_PATH + DB_NAME);
        return dbFile.exists();
    }

    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            // System.out.println("My Pathe is:- " + myPath);
            // System.out.println("Open");
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READWRITE);
            // System.out.println("checkDB value:" + checkDB);
            // System.out.println("My Pathe is:- " + myPath);
        } catch (Exception e) {
            // database does't exist yet.
        }

        if (checkDB != null) {
            // System.out.println("Closed");
            checkDB.close();
            // System.out.println("My db is:- " + checkDB.isOpen());
        }

        return checkDB != null ? true : false;
    }

    public Cursor execCursorQuery(String sql) {
        Cursor cursor = null;
        try {
            cursor = db.rawQuery(sql, null);
            GetCursor = cursor.getCount();
            Log.i("Inside execCursorQuery try", sql);
        } catch (Exception e) {
            Log.i("Inside execCursorQuery exception", e.getMessage());
        }
        return cursor;
    }

    public void execNonQuery(String sql) {
        try {
            db.execSQL(sql);
            // Log.d("SQL", sql);
        } catch (Exception e) {
            // Log.e("Err", e.getMessage());
        } finally {
            // closeDb();
        }
    }

    // ****************** Declare all the global variable
    // ****************************//

    private Context myContext;
    public String DB_PATH = "data/data/com.app.ourforms/databases/"; // path
    // of
    // your
    // datbase
    public static String DB_NAME = "OurForms.sqlite";// your database
                                                        // name
    @SuppressWarnings("unused")
    private static String ASSETS_DB_FOLDER = "db";
    private SQLiteDatabase db;

    public Vector<ArrayList<String>> getQuestion(String Query) {
        Vector<ArrayList<String>> alldata = new Vector<ArrayList<String>>();
        ArrayList<String> Question = new ArrayList<String>();
        ArrayList<String> Option1 = new ArrayList<String>();
        ArrayList<String> Option2 = new ArrayList<String>();
        ArrayList<String> Option3 = new ArrayList<String>();
        ArrayList<String> Option4 = new ArrayList<String>();
        ArrayList<String> Option5 = new ArrayList<String>();
        ArrayList<String> correct = new ArrayList<String>();
        ArrayList<String> correctness = new ArrayList<String>();
        ArrayList<String> Description = new ArrayList<String>();

        Cursor alldata_ques = execCursorQuery(Query);

        // GetCursor = alldata_ques.getCount();

        if (alldata_ques != null) {
            Log.e("Cursor length", "" + alldata_ques.getCount());
            GetCursor = alldata_ques.getCount();
            if (alldata_ques.getCount() > 0)

                while (alldata_ques.moveToNext()) {
                    Question.add((alldata_ques.getString(alldata_ques
                            .getColumnIndex("Question"))));
                    Option1.add(alldata_ques.getString(alldata_ques
                            .getColumnIndex("A")));
                    Option2.add(alldata_ques.getString(alldata_ques
                            .getColumnIndex("B")));
                    Option3.add(alldata_ques.getString(alldata_ques
                            .getColumnIndex("C")));
                    Option4.add(alldata_ques.getString(alldata_ques
                            .getColumnIndex("D")));
                    Option5.add(alldata_ques.getString(alldata_ques
                            .getColumnIndex("E")));
                    correct.add(alldata_ques.getString(alldata_ques
                            .getColumnIndex("Answer")));
                    correctness.add(alldata_ques.getString(alldata_ques
                            .getColumnIndex("Correctness")));
                    Description.add(alldata_ques.getString(alldata_ques
                            .getColumnIndex("Description")));
                }
            alldata.add(Question);
            alldata.add(Option1);
            alldata.add(Option2);
            alldata.add(Option3);
            alldata.add(Option4);
            alldata.add(Option5);
            alldata.add(correct);
            alldata.add(correctness);
            alldata.add(Description);
            // Log.d("VECTORSIZE", String.valueOf(alldata.size()));
        }

        return alldata;
    }

    public Vector<ArrayList<String>> getQuestions(String Query) {
        Vector<ArrayList<String>> alldata = new Vector<ArrayList<String>>();
        ArrayList<String> Question = new ArrayList<String>();
        ArrayList<String> Option1 = new ArrayList<String>();
        ArrayList<String> Option2 = new ArrayList<String>();
        ArrayList<String> Option3 = new ArrayList<String>();
        ArrayList<String> Option4 = new ArrayList<String>();
        ArrayList<String> Option5 = new ArrayList<String>();
        ArrayList<String> correct = new ArrayList<String>();
        ArrayList<String> Description = new ArrayList<String>();

        Cursor alldata_ques = execCursorQuery(Query);

        if (alldata_ques != null) {
            Log.e("Cursor length", "" + alldata_ques.getCount());
            if (alldata_ques.getCount() > 0)
                GetCursor = alldata_ques.getCount();
            while (alldata_ques.moveToNext()) {
                Question.add((alldata_ques.getString(alldata_ques
                        .getColumnIndex("Question"))));
                Option1.add(alldata_ques.getString(alldata_ques
                        .getColumnIndex("A")));
                Option2.add(alldata_ques.getString(alldata_ques
                        .getColumnIndex("B")));
                Option3.add(alldata_ques.getString(alldata_ques
                        .getColumnIndex("C")));
                Option4.add(alldata_ques.getString(alldata_ques
                        .getColumnIndex("D")));
                Option5.add(alldata_ques.getString(alldata_ques
                        .getColumnIndex("E")));
                correct.add(alldata_ques.getString(alldata_ques
                        .getColumnIndex("Answer")));
                Description.add(alldata_ques.getString(alldata_ques
                        .getColumnIndex("Description")));
            }
            alldata.add(Question);
            alldata.add(Option1);
            alldata.add(Option2);
            alldata.add(Option3);
            alldata.add(Option4);
            alldata.add(Option5);
            alldata.add(correct);
            alldata.add(Description);
            // Log.d("VECTORSIZE", String.valueOf(alldata.size()));
        }

        return alldata;
    }
}

In Above Code Change below line as per your project:在上面的代码中,根据您的项目更改以下行:

 public String DB_PATH = "data/data/YOUR_PACKAGE_NAME/databases/"; // path of your datbase

 public static String DB_NAME = "OurForms.sqlite";// your database Name

Inside your Activity Write Below Code For First Time Copy your Database to Application.在您的 Activity 中首次写入下面的代码将您的数据库复制到应用程序。

// For Database Copy
        myPrefs = getSharedPreferences("myPrefs", 0);

        // sharedPreferences = PreferenceManager
        // .getDefaultSharedPreferences(getApplicationContext());

        Data.FIRST_TIME_LAUNCH = myPrefs.getBoolean("FIRST_TIME_LAUNCH", true);

        if (Data.FIRST_TIME_LAUNCH) {

            Log.i(TAG, "FIRST TIME*************************");
            dbConnect = new DBConnect(getApplicationContext(),
                    "OurForms.sqlite");
            SharedPreferences.Editor editor = myPrefs.edit();
            editor.putBoolean("FIRST_TIME_LAUNCH", false);
            editor.commit();
        }

Hope it will help you.希望它会帮助你。

public void getDataBaseData() {
        // /PawnStorescopy.db
        if (!new File("/data/data/" + this.getPackageName()
                + "/PawnStorescopy.sqlite").exists()) {
            try {
                FileOutputStream out = new FileOutputStream("data/data/"
                        + this.getPackageName() + "DatabaseName.sqlite");
                InputStream in = getAssets().open("DatabaseName.db");
                byte[] buffer = new byte[1024];
                int readBytes = 0;

                while ((readBytes = in.read(buffer)) != -1)
                    out.write(buffer, 0, readBytes);

                in.close();
                // out.close();
            } catch (IOException e) {
            }
        }

        SQLiteDatabase sqliteDB = SQLiteDatabase.openOrCreateDatabase( 
                "/data/data/" + this.getPackageName()
                        + "/DatabaseName.sqlite", null);

        Cursor cursor = sqliteDB.rawQuery("SELECT * FROM TableName", null);

        if (cursor.moveToFirst()) {
            do {
                ////Get Data
            } while (cursor.moveToNext());


            imageFilter(listDatabase);
        }

    }

Follow this link: https://github.com/jgilfelt/android-sqlite-asset-helper按照此链接: https : //github.com/jgilfelt/android-sqlite-asset-helper

Then,然后,

  1. Add your yourSqliteDb.db to folder in assets/databases.将 yourSqliteDb.db 添加到 assets/databases 中的文件夹。 Create the folders if not present.如果不存在,则创建文件夹。 assets/databases/yourSqliteDb.db How to create asset folder: http://code2care.org/2015/create-assets-folder-in-android-studio/ assets/databases/yourSqliteDb.db 如何创建资产文件夹: http ://code2care.org/2015/create-assets-folder-in-android-studio/

  2. Create SQLiteAssetHelper Class as:创建 SQLiteAssetHelper 类为:

     public class MyDatabaseHelper extends SQLiteAssetHelper { private static final String DATABASE_NAME = "yourSqliteDb.db"; private static final int DATABASE_VERSION = 1; public MyDatabase(Context mContext) { super(mContext, DATABASE_NAME, null, DATABASE_VERSION ); } public Cursor getItems() { SQLiteDatabase db = getReadableDatabase(); Cursor c = db.rawQuery("Select * from items", null); //items is a column name in your table in database c.moveToFirst(); return c; }

    } }

  3. Now in MainActivity or wherever you need to read data from database,现在在 MainActivity 或任何需要从数据库读取数据的地方,

     MyDatabaseHelper myDbHelper = new MyDatabaseHelper(this); SQLiteDatabase db = myDbHelper.ReadableDatabase(); String items = getResult(1); //number value from database table public String getResult(int id) { String name = null; try { Cursor c = null; c = db.rawQuery("select item from items where _id="+id, null); c.moveToFirst(); name = c.getString(c.getColumnIndex("item")); c.close(); } catch(Exception e) { e.printStackTrace(); } return name; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM