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

时间:2013-01-09 09:40:01

标签: java android database sqlite external

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

所有教程都假设你没有任何数据库,你可以从应用程序中创建它,然后填充它。

我已将数据放入我的数据库,但不想创建新数据。

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

5 个答案:

答案 0 :(得分:0)

我没有看到问题。我使用了相同的例子并且它有效。 在我的项目中,我必须检查并最终在内部数据库上加载缺少的表。

除非您这样说,否则不会删除数据库。

因此,添加新表将不会删除任何预先存在的表。

无论如何,你说'它有点工作但它并不完美',你的意思是什么?它要么复制表,要么不复制。正确?

答案 1 :(得分:0)

您提供了一个很好的链接示例,但最佳做法是在您的Android应用程序中构建您的数据库,因此您可以将数据作为插入语句导出就绪数据库DLL,将这些插入语句添加到文件中在原始文件夹下说,创建数据库后,您可以读取插入语句并执行它们以插入数据。

答案 2 :(得分: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();
        }

希望它会对你有所帮助。

答案 3 :(得分:0)

com/bigbluehat/byoung.couch

答案 4 :(得分:0)

关注此链接: https://github.com/jgilfelt/android-sqlite-asset-helper

然后

  1. 将yourSqliteDb.db添加到资产/数据库中的文件夹。创建文件夹(如果不存在)。     资产/数据库/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;
      }