· 8 years ago · May 09, 2018, 09:02 PM
1
2
3import android.content.ContentValues;
4import android.content.Context;
5import android.database.Cursor;
6import android.database.sqlite.SQLiteDatabase;
7import android.database.sqlite.SQLiteOpenHelper;
8
9
10
11public class MySQLite extends SQLiteOpenHelper {
12
13 private static final int DATABASE_VERSION = 1;
14
15 public MySQLite(Context context) {
16 super(context, "animalsDB", null, DATABASE_VERSION);
17
18 }
19
20
21 @Override
22 public void onCreate(SQLiteDatabase
23 database) {
24 String DATABASE_CREATE =
25 "create table animals " +
26 "(_id integer primary key autoincrement," +
27 "gatunek text not null," +
28 "kolor text not null," +
29 "wielkosc real not null," +
30 "opis text not null);";
31 database.execSQL(DATABASE_CREATE);
32 }
33 @Override
34 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
35 db.execSQL("DROP TABLE IF EXISTS animals");
36 onCreate(db);
37
38 }
39
40 public void dodaj(Animal zwierz){
41 SQLiteDatabase db = this.getWritableDatabase();
42 ContentValues values = new ContentValues();
43 values.put("gatunek", zwierz.getGatunek());
44 values.put("kolor", zwierz.getKolor());
45 values.put("wielkosc", zwierz.getWielkosc());
46 values.put("opis", zwierz.getOpis());
47 db.insert("animals", null, values);
48 db.close();
49 }
50
51 public void usun(String id) {
52 SQLiteDatabase db = this.getWritableDatabase();
53
54 db.delete("animals", "_id = ?", new String[] { id });
55 db.close();
56 }
57
58 public int aktualizuj(Animal zwierz) {
59 SQLiteDatabase db =
60 this.getWritableDatabase();
61 ContentValues values = new ContentValues();
62 values.put("gatunek", zwierz.getGatunek());
63 values.put("kolor", zwierz.getKolor());
64 values.put("wielkosc", zwierz.getWielkosc());
65 values.put("opis", zwierz.getOpis());
66 int i = db.update("animals", values, "_id = ?", new String[]{String.valueOf(zwierz.get_id())});
67 db.close();
68 return i;
69 }
70
71 public Animal pobierz(int id){
72 SQLiteDatabase db =
73 this.getReadableDatabase();
74 Cursor cursor = db.query("animals", //a. table name
75 new String[] { "_id",
76 "gatunek", "kolor", "wielkosc", "opis" }, // b.column names
77"_id = ?", // c. selections
78 new String[] {
79 String.valueOf(id) }, // d. selections args
80 null, // e. group by
81 null, // f. having
82 null, // g. order by
83 null); // h. limit
84 if (cursor != null)
85 cursor.moveToFirst();
86 Animal zwierz = new
87 Animal(cursor.getString(1), cursor.getString(2),
88 cursor.getFloat(3), cursor.getString(4));
89
90 zwierz.set_id(Integer.parseInt(cursor.getString(0))
91 );
92 return zwierz;
93 }
94
95 public Cursor lista(){
96 SQLiteDatabase db = this.getReadableDatabase();
97 return db.rawQuery("Select * from animals",null);
98 }
99
100
101}