android - 在 Android 中设置数据库

标签 android sqlite

Android 官方开发者网站首先提到我们必须先“定义模式和契约”,大概是这样的:

public static abstract class FeedEntry implements BaseColumns {
public static final String TABLE_NAME = "entry";
public static final String COLUMN_NAME_ENTRY_ID = "entryid";
public static final String COLUMN_NAME_TITLE = "title";
public static final String COLUMN_NAME_SUBTITLE = "subtitle";
...

提到的第二步是“使用 SQL Helper 创建数据库”。

但是我在网上看到的所有教程都是直接使用'helper'创建一个类;对于 example . 哪种方法是正确的?两者?

此外,我应该在主 Activity 中定义和创建我的数据库,还是为数据库创建一个单独的 Activity?

最佳答案

在 SQLite 浏览器(如 SQLite Maestro)中创建数据库,将数据库复制到项目的 Assets 文件夹中。在您的 MainActivity 中调用 createDatabase() 方法(在您的应用启动器 Activity 中是第一个)。

private void createDataBase(){
    DataBaseHelper db = new DataBaseHelper(this);
    try {
        db.createDataBase();
    } catch (IOException e) {
        e.printStackTrace();
    }finally{
        db.close();
    }
}

辅助类:

public class DataBaseHelper extends SQLiteOpenHelper{   

    private static String DB_PATH = "/data/data/your.package/databases/";   
    private static String DB_NAME = "YourDataBaseName.sqlite";
    private static int DB_VERSION = 1;

    private static short WRITE_BUFFER_SIZE = 8192;

    private Context context;

    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context Current application context
     */
    public DataBaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);

        this.context = context;
    }   

  /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public synchronized void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();

        if(dbExist){
            //do nothing - database already exist
        }
        else
        {
            //By calling this method and empty database will be created into the default system path
               //of your application so we are gonna be able to overwrite that database with our database.
            this.getWritableDatabase();

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

        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){
        SQLiteDatabase checkDB = null;
        try{
            String myPath = DB_PATH + DB_NAME;

            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        }catch(SQLException e){
            e.printStackTrace();
            //database does't exist yet.
        }catch(Exception e){
            e.printStackTrace();
        }

        if(checkDB != null){
            if(checkDB.getVersion() < DB_VERSION){
                checkDB.close();
                return false;
            }else{ 
                checkDB.close();
                return true;
            }
        }

        return false;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     */
    private void copyDataBase() throws IOException{     
        //Open your local db as the input stream    
        InputStream myInput = context.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[WRITE_BUFFER_SIZE];
        int length;
        while ((length = myInput.read(buffer)) > 0){
            myOutput.write(buffer, 0, length);
        }
        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
        this.getWritableDatabase().close();
    }

    @Override
    public synchronized void close() {
            super.close();
    }

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

    @Override
    public void onCreate(SQLiteDatabase db) {   
    }

    /**
     * Delete database and create new one or copy from assets if exists.
     */
    public void clearDatabase(){      
        context.deleteDatabase(DB_NAME);
        try {
            createDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }

        this.getWritableDatabase().close();
    }
}

关于android - 在 Android 中设置数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13911268/

相关文章:

android - 更新在 SQLite 数据库中不起作用

java - 61 classes.jar 中有重复的类,classes.jar 位于何处?

Android - 取消发布应用程序问题

android - 如何将 LaTex 文本从服务器解码到 Android TextView?

sql - 获取多个表的最大值

android - SQLite没有打开的构造函数错误

java - 在 SQLiteDatabase 中保存和检索计数器并使用它来保存唯一的文件名

android - Ionic 应用程序因 braintree 插件而崩溃 - java.lang.NoSuchMethodError : No static method getFont

android - android studio-卡在刷新项目构建gradle

android - 在 SQLite 中保存图像的优点和缺点