1

这是我的问题。我在名为 SqliteDbBrowser 的程序中创建我的文本数据库,之后我想将它放入 android 的 /assets/ 文件夹中并将其加载到应用程序中。

所有教程都假设您没有任何数据库,并且您从应用程序中干净地创建它,然后填充它。

我已经将数据放入我的数据库并且不想创建新的。

这是一些人的教程http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/它以某种方式工作,但它并不完美,有没有其他方法可以解决这个问题? 只使用 SQLiteOpenHelper 不混合东西?

4

5 回答 5

1
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);
        }

    }
于 2015-08-28T13:51:01.730 回答
0

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

于 2013-01-09T09:51:15.677 回答
0

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?

于 2013-01-09T09:47:50.447 回答
0

首先将您创建的数据库放入您的资产文件夹中。

将以下 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;
    }
}

在上面的代码中根据您的项目更改以下行:

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

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

在您的活动中编写以下代码第一次将您的数据库复制到应用程序。

// 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();
        }

希望它会帮助你。

于 2013-01-09T10:19:26.943 回答
0

按照这个链接: https ://github.com/jgilfelt/android-sqlite-asset-helper

然后,

  1. 将 yourSqliteDb.db 添加到 assets/databases 的文件夹中。如果不存在,请创建文件夹。assets/databases/yourSqliteDb.db 如何创建资产文件夹: http ://code2care.org/2015/create-assets-folder-in-android-studio/

  2. 创建 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. 现在在 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;
      }
    
于 2018-08-27T04:35:03.367 回答