如何为MYDBHandler编写MainActivity以在TextView中显示数据?

时间:2015-10-11 06:14:52

标签: android database sqlite

//这是我的MYDBHandler类:

public class MyDBHandler extends SQLiteOpenHelper {

    private static String DB_PATH = "/data/data/com.sachin.quiz/databases/";
    private static String DB_NAME = "question";
    private SQLiteDatabase myDataBase;
    private final Context myContext;

构造: 获取并保留传递的上下文的引用以便访问 应用程序资产和资源。

public MyDBHandler(Context context) {
    super(context, DB_NAME, null,1);
    this.myContext = context;
    this.createDatabase();
}

在系统上创建一个空数据库,并用您自己的数据库重写它。

public void createDatabase() {
    try {
        boolean dbExist = checkDataBase();
        if (dbExist) {
            //do nothing - database already exist
        } else {

通过调用此方法,将在应用程序的默认系统路径中创建一个空数据库,这样我们就可以用我们的数据库覆盖该数据库了。

            this.getReadableDatabase();
            copyDataBase();
        }
    }
    catch (Exception e) {

    }
}

检查数据库是否已存在,以避免每次打开应用程序时重新复制文件。 @return如果存在则为true,如果不存在则为false

private boolean checkDataBase() {

    SQLiteDatabase checkDB = null;

    try {
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    } catch (SQLiteException e) {

        //database does't exist yet.

    }
    if (checkDB != null) {

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

将数据库从本地assets-folder复制到系统文件夹中刚创建的空数据库,从中可以访问和处理该数据库。 这是通过传输字节流来完成的。

private void copyDataBase() {

    try {
        //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[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }
    catch (Exception e) {
        //catch exception
    }
}

public SQLiteDatabase openDataBase() throws SQLException {

    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    return myDataBase;

}

@Override
public synchronized void close() {

    if (myDataBase != null) {
        myDataBase.close();
    }

    super.close();

}


@Override
public void onCreate(SQLiteDatabase db) {
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
//End of class
}

0 个答案:

没有答案