· 9 years ago · Jan 14, 2017, 06:34 PM
1package hu.bayer.ciklusnaplo;
2
3import java.io.*;
4import java.util.*;
5import android.content.Context;
6import android.database.Cursor;
7import android.database.sqlite.*;
8import android.util.*;
9
10public class DataHelper {
11
12 private String databaseName = "ciklusnaplo.db";
13 private String path = "";
14 private Context context;
15 private SQLiteDatabase db;
16 public final static int TYPE_CHECK = 0;
17 public final static int TYPE_STRING = 1;
18 public final static int TYPE_INT = 2;
19 public final static int TYPE_BOOL = 3;
20
21 public DataHelper(Context context) {
22 this.context = context;
23 path = "/data/data/" + context.getPackageName() + "/databases";
24 OpenHelper openHelper = new OpenHelper(databaseName, context);
25 copyDatabase();
26 this.db = openHelper.getWritableDatabase();
27 }
28
29 public long insert(String sql) {
30 final SQLiteStatement stmt = this.db.compileStatement(sql);
31 try {
32 return stmt.executeInsert();
33 } catch (Exception e) {
34 e.printStackTrace();
35 return 0;
36 }
37 }
38
39 public void execute(String sql) {
40 //Log.w("UPDATE", sql);
41 this.db.execSQL(sql);
42 }
43
44 public ArrayList<ArrayList> select(String sql) {
45 //Log.w("SELECT", sql);
46 ArrayList<ArrayList> list = new ArrayList<ArrayList>();
47 Cursor cursor = this.db.rawQuery(sql, null);
48
49 if (cursor.moveToFirst()) {
50 do {
51 ArrayList<String> row = new ArrayList<String>();
52 for (int i = 0; i < cursor.getColumnCount(); i++) {
53 row.add(cursor.getString(i));
54 }
55 list.add(row);
56 } while (cursor.moveToNext());
57 }
58 if (cursor != null && !cursor.isClosed()) {
59 cursor.close();
60 }
61 return list;
62 }
63
64 public void close() {
65 this.db.close();
66 }
67
68 public void copyDatabase() {
69 File path = new File(this.path);
70 if (!path.exists())
71 path.mkdir();
72 File f = new File(this.path, this.databaseName);
73 if (!f.exists()) {
74 InputStream assetsDB = null;
75 try {
76 assetsDB = context.getAssets().open(this.databaseName);
77 OutputStream dbOut = new FileOutputStream(this.path + "/"
78 + this.databaseName);
79
80 byte[] buffer = new byte[1024];
81 int length;
82 while ((length = assetsDB.read(buffer)) > 0) {
83 dbOut.write(buffer, 0, length);
84 }
85
86 dbOut.flush();
87 dbOut.close();
88 assetsDB.close();
89 Log.i("SQLite", "New database created...");
90 } catch (IOException e) {
91 Log.e("SQLite", "Could not create new database...");
92 e.printStackTrace();
93 }
94 }
95 }
96
97 private static class OpenHelper extends SQLiteOpenHelper {
98
99 OpenHelper(String databaseName, Context context) {
100 super(context, databaseName, null, 1);
101 }
102
103 @Override
104 public void onCreate(SQLiteDatabase db) {
105 db.execSQL("create table if not exists ...");
106 }
107
108 @Override
109 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
110 // Migration
111 }
112 }
113}