Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class DatabaseHelper extends SQLiteOpenHelper {
- private Context dbContext;
- private static String DB_NAME = "appData.db";
- private String DB_PATH = "";
- private static final int DB_VERSION = 1;
- private SQLiteDatabase mDatabase;
- public DatabaseHelper(Context context) {
- super(context, DB_NAME, null, DB_VERSION);
- this.dbContext = context;
- DB_PATH = dbContext.getApplicationInfo().dataDir + "/databases/";
- if (checkDataBase()) {
- Log.d("database_test", "Open database call");
- openDataBase();
- } else {
- try {
- Log.d("database_test", "Open database not call");
- this.getReadableDatabase();
- Log.d("database_test", "copy database call");
- copyDataBase();
- this.close();
- openDataBase();
- } catch (IOException e) {
- throw new Error("Error copying database");
- }
- Toast.makeText(context, "Initial database is created", Toast.LENGTH_LONG).show();
- }
- }
- private void copyDataBase() throws IOException {
- Log.d("database_test", "Copy database call 2");
- InputStream myInput = dbContext.getAssets().open(DB_NAME);
- String outFileName = DB_PATH + DB_NAME;
- OutputStream myOutput = new FileOutputStream(outFileName);
- byte[] buffer = new byte[1024];
- int length;
- while ((length = myInput.read(buffer)) > 0) {
- myOutput.write(buffer, 0, length);
- }
- myOutput.flush();
- myOutput.close();
- myInput.close();
- Log.d("database_test", "Open database worked finish");
- }
- public void openDataBase() throws SQLException {
- Log.d("database_test", "Open database call 2");
- String dbPath = DB_PATH + DB_NAME;
- mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
- }
- private boolean checkDataBase() {
- SQLiteDatabase checkDB = null;
- boolean exist = false;
- try {
- String dbPath = DB_PATH + DB_NAME;
- checkDB = SQLiteDatabase.openDatabase(dbPath, null,
- SQLiteDatabase.OPEN_READONLY);
- } catch (SQLiteException e) {
- Log.v("db_log", "database does't exist");
- }
- if (checkDB != null) {
- exist = true;
- checkDB.close();
- }
- return exist;
- }
- public void getAllTableName() {
- mDatabase = getReadableDatabase();
- Cursor c = mDatabase.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
- if (c.moveToFirst()) {
- while (!c.isAfterLast()) {
- Log.d("db_test", "table list: " + c.getString(0));
- // Toast.makeText(acti, "Table Name=> "+c.getString(0), Toast.LENGTH_LONG).show();
- c.moveToNext();
- }
- }
- c.close();
- }
- public Cursor getTestData() {
- Cursor cursor = mDatabase.rawQuery("SELECT * FROM qna", null);
- /*if (cursor != null) {
- while (cursor.moveToNext()) {
- String value = cursor.getString(1);
- Log.d("db_test", "table value: " + value);
- }
- // cursor.close();
- }*/
- return cursor;
- }
- @Override
- public void onCreate(SQLiteDatabase sqLiteDatabase) {
- }
- @Override
- public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
- }
- }
Add Comment
Please, Sign In to add comment