· 6 years ago · Oct 30, 2019, 12:48 PM
1public class DbHelper extends SQLiteOpenHelper {
2 private static final int DATABASE_VERSION = 2;
3 static final String DATABASE_NAME = "digitaltalent.db";
4 public static final String TABLE_SQLite = "sqlite";
5
6 public static final String COLUMN_ID = "id";
7 public static final String COLUMN_NAME = "name";
8 public static final String COLUMN_ADDRESS = "address";
9
10 public DbHelper(Context context){
11 super(context, DATABASE_NAME, null, DATABASE_VERSION);
12 }
13
14 @Override
15 public void onCreate(SQLiteDatabase db) {
16 final String SQL_CREATE_MOVIE_TABLE = "CREATE TABLE "+TABLE_SQLite+ " ("+
17 COLUMN_ID + " INTEGER PRIMARY KEY autoincrement, "+
18 COLUMN_NAME + " TEXT NOT NULL, "+
19 COLUMN_ADDRESS + " TEXT NOT NULL"+
20 " )";
21 db.execSQL(SQL_CREATE_MOVIE_TABLE);
22 }
23
24 @Override
25 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
26 db.execSQL("DROP TABLE IF EXISTS "+TABLE_SQLite);
27 onCreate(db);
28 }
29
30 public ArrayList<HashMap<String, String>> getAlData(){
31 ArrayList<HashMap<String, String>> wordList;
32 wordList = new ArrayList<HashMap<String, String>>();
33 String selectQuery = "SELECT * FROM "+TABLE_SQLite;
34 SQLiteDatabase database = this.getWritableDatabase();
35 Cursor cursor = database.rawQuery(selectQuery, null);
36 if(cursor.moveToFirst()){
37 do{
38 HashMap<String, String> map = new HashMap<String, String>();
39 map.put(COLUMN_ID, cursor.getString(0));
40 map.put(COLUMN_NAME, cursor.getString(1));
41 map.put(COLUMN_ADDRESS, cursor.getString(2));
42 wordList.add(map);
43 } while (cursor.moveToNext());
44 }
45 Log.e("select sqlite", ""+wordList);
46
47 database.close();
48 return wordList;
49 }
50
51 public void insert(String name, String address){
52 SQLiteDatabase database = this.getWritableDatabase();
53 String queryValues = "INSERT INTO "+TABLE_SQLite+ " (name, address) "+
54 "VALUES ('"+name+"', '" +address+ "')";
55 Log.e("insert sqlite ", ""+queryValues);
56 database.execSQL(queryValues);
57 database.close();
58 }
59
60 public void update(int id, String name, String address){
61 SQLiteDatabase database = this.getWritableDatabase();
62
63 String updateQuery = "UPDATE "+TABLE_SQLite+" SET "
64 +COLUMN_NAME+ "='" +name+"', "
65 +COLUMN_ADDRESS+ "='"+address+"'"
66 +" WHERE "+COLUMN_ID+ "="+"'"+id+"'";
67 Log.e("update sqlite ",updateQuery);
68 database.execSQL(updateQuery);
69 database.close();
70 }
71
72 public void delete(int id){
73 SQLiteDatabase database = this.getWritableDatabase();
74
75 String updateQuery = "DELETE FROM "+TABLE_SQLite+ " WHERE "+COLUMN_ID+ "=" + "'"+id+"'";
76 Log.e("update sqlite ", updateQuery);
77 database.execSQL(updateQuery);
78 database.close();
79 }
80}