· 8 years ago · Aug 26, 2018, 01:24 AM
1Access DB outside an activity on android
2import java.io.FileOutputStream;
3import java.io.IOException;
4import java.io.InputStream;
5import java.io.OutputStream;
6import java.util.UUID;
7
8import android.content.Context;
9import android.database.Cursor;
10import android.database.SQLException;
11import android.database.sqlite.SQLiteDatabase;
12import android.database.sqlite.SQLiteException;
13import android.database.sqlite.SQLiteOpenHelper;
14import android.util.Log;
15
16public class AnyDBAdapter {
17
18 private static final String TAG = "AnyDBAdapter";
19 private DatabaseHelper mDbHelper;
20 private static SQLiteDatabase mDb;
21
22 //make sure this matches the
23 //package com.MyPackage;
24 //at the top of this file
25 private static String DB_PATH = "/data/data/com.MyPackage/databases/";
26
27 //make sure this matches your database name in your assets folder
28 // my database file does not have an extension on it
29 // if yours does
30 // add the extention
31 private static final String DATABASE_NAME = "data";
32
33 //Im using an sqlite3 database, I have no clue if this makes a difference or not
34 private static final int DATABASE_VERSION = 3;
35
36 private final Context adapterContext;
37
38 public AnyDBAdapter(Context context) {
39 this.adapterContext = context;
40 }
41
42 public AnyDBAdapter open() throws SQLException {
43 mDbHelper = new DatabaseHelper(adapterContext);
44
45 try {
46 mDbHelper.createDataBase();
47 } catch (IOException ioe) {
48 throw new Error("Unable to create database");
49 }
50
51 try {
52 mDbHelper.openDataBase();
53 } catch (SQLException sqle) {
54 throw sqle;
55 }
56 return this;
57 }
58
59
60 //----------------------->> Usage from outside<<---------------------------//
61 // AnyDBAdapter dba = new AnyDBAdapter(contextObject); //in my case contextObject is a Map
62 // dba.open();
63 // Cursor c = dba.ExampleSelect("Rawr!");
64 // contextObject.startManagingCursor(c);
65 // String s1 = "", s2 = "";
66 // if(c.moveToFirst())
67 // do {
68 // s1 = c.getString(0);
69 // s2 = c.getString(1);
70 // } while (c.moveToNext());
71 // dba.close();
72
73
74 public Cursor ExampleSelect(string myVariable)
75 {
76 String query = "SELECT locale, ? FROM android_metadata";
77 return mDb.rawQuery(query, new String[]{myVariable});
78 }
79
80 //Usage
81 // AnyDBAdatper dba = new AnyDBAdapter(contextObjecT);
82 // dba.open();
83 // dba.ExampleCommand("en-CA", "en-GB");
84 // dba.close();
85 public void ExampleCommand(String myVariable1, String myVariable2)
86 {
87 String command = "INSERT INTO android_metadata (locale) SELECT ? UNION ALL SELECT ?";
88 mDb.execSQL(command, new String[]{ myVariable1, myVariable2});
89 }
90
91 public void close() {
92 mDbHelper.close();
93 }
94
95 private static class DatabaseHelper extends SQLiteOpenHelper {
96
97 Context helperContext;
98
99 DatabaseHelper(Context context) {
100 super(context, DATABASE_NAME, null, DATABASE_VERSION);
101 helperContext = context;
102 }
103
104 @Override
105 public void onCreate(SQLiteDatabase db) {
106 }
107
108 @Override
109 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
110 Log.w(TAG, "Upgrading database!!!!!");
111 //db.execSQL("");
112 onCreate(db);
113 }
114
115 public void createDataBase() throws IOException {
116 boolean dbExist = checkDataBase();
117 if (dbExist) {
118 } else {
119
120 //make sure your database has this table already created in it
121 //this does not actually work here
122 /*
123 * db.execSQL("CREATE TABLE IF NOT EXISTS "android_metadata" ("locale" TEXT DEFAULT 'en_US')"
124 * );
125 * db.execSQL("INSERT INTO "android_metadata" VALUES ('en_US')"
126 * );
127 */
128 this.getReadableDatabase();
129 try {
130 copyDataBase();
131 } catch (IOException e) {
132 throw new Error("Error copying database");
133 }
134 }
135 }
136
137 public SQLiteDatabase getDatabase() {
138 String myPath = DB_PATH + DATABASE_NAME;
139 return SQLiteDatabase.openDatabase(myPath, null,
140 SQLiteDatabase.OPEN_READONLY);
141 }
142
143 private boolean checkDataBase() {
144 SQLiteDatabase checkDB = null;
145 try {
146 String myPath = DB_PATH + DATABASE_NAME;
147 checkDB = SQLiteDatabase.openDatabase(myPath, null,
148 SQLiteDatabase.OPEN_READONLY);
149 } catch (SQLiteException e) {
150 }
151 if (checkDB != null) {
152 checkDB.close();
153 }
154 return checkDB != null ? true : false;
155 }
156
157 private void copyDataBase() throws IOException {
158
159 // Open your local db as the input stream
160 InputStream myInput = helperContext.getAssets().open(DATABASE_NAME);
161
162 // Path to the just created empty db
163 String outFileName = DB_PATH + DATABASE_NAME;
164
165 // Open the empty db as the output stream
166 OutputStream myOutput = new FileOutputStream(outFileName);
167
168 // transfer bytes from the inputfile to the outputfile
169 byte[] buffer = new byte[1024];
170 int length;
171 while ((length = myInput.read(buffer)) > 0) {
172 myOutput.write(buffer, 0, length);
173 }
174
175 // Close the streams
176 myOutput.flush();
177 myOutput.close();
178 myInput.close();
179 }
180
181 public void openDataBase() throws SQLException {
182 // Open the database
183 String myPath = DB_PATH + DATABASE_NAME;
184 mDb = SQLiteDatabase.openDatabase(myPath, null,
185 SQLiteDatabase.OPEN_READWRITE);
186 }
187
188 @Override
189 public synchronized void close() {
190
191 if (mDb != null)
192 mDb.close();
193
194 super.close();
195
196 }
197 }