Android - 如何以编程方式创建数据库

时间:2014-05-12 17:11:21

标签: android database sqlite

我想创建一个测验应用程序,为此,我想我需要一个包含所有问题和答案的数据库。

我找到了关于如何在官方Android开发者网站上以编程方式创建数据库的教程,但我不认为这是我需要的,因为我不需要在应用程序时创建数据库运行,我需要一个已经编译好的数据库,我可以从中读取问题和答案。

首先,这是进行测验应用的正确方法吗?如果是的话,我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

您将使用以下方式完成此任务。

  1. 首先使用SQlite Manager / SQlite Studio创建数据库。
  2. 将该数据库存储在Asserts文件夹中并使用以下代码
  3. 公共类DataBase扩展了SQLiteOpenHelper {

    public static String DB_PATH = "/data/data/your package name here/";
    public static String DB_NAME = "your database name .sqlite";
    public static SQLiteDatabase _database;
    private final Context myContext;
    public static String apstorphe = "'";
    public static String sep = ",";
    private AtomicInteger mOpenCounter = new AtomicInteger();
    
    public DataBase(Context context) throws IOException {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
        createDataBase();
    }
    
    /**
     * Creates a empty database on the system and rewrites it with your own database.
     */
    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
    
        if (!dbExist) {
            // 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.
            try {
                copyDataBase();
            } catch (IOException e) {
                System.out.println();
            }
        }
    }
    
    /**
     * 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.OPEN_READWRITE);
        } catch (SQLiteException e) {
            // database does't exist yet.
        }
    
        if (checkDB != null) {
            checkDB.close();
        }
    
        return checkDB != null ? true : false;
    }
    
    public void copyDataBase() throws IOException {
    
        // Open your local db as the input stream
        InputStream myInput = myContext.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[2048];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }
    
        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    
    }
    
    public static SQLiteDatabase openDataBase() throws SQLException {
        // Open the database
        if (_database == null) {
            _database = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.CREATE_IF_NECESSARY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        } else if (!_database.isOpen()) {
            _database = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.CREATE_IF_NECESSARY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
        }
        return _database;
    }
    
    public static void closedatabase() {
        if (_database != null)
            _database.close();
    }
    
    @Override
    public void onCreate(SQLiteDatabase db) {
    
    }
    
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    
    }
    
    public static Cursor getdata(String query_str) {
        Cursor mCursor = _database.rawQuery(query_str, null);
        return mCursor;
    }
    
    public static void executeQuery(String strQuery) {
    
        try {
            _database.execSQL(strQuery);
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
    

    }