· 9 years ago · Jan 08, 2017, 04:50 PM
1public List<Item> getAllItems() {
2 List<Item> items = new ArrayList<Item>();
3 Cursor cursor = database.query(MySQLiteHelper.TABLE_ITEMS,
4 allColumns, null, null, null, null, null);
5 cursor.moveToFirst();
6
7 while (!cursor.isAfterLast()) {
8 Item item = cursorToItem(cursor);
9 items.add(item);
10 cursor.moveToNext();
11 }
12 // Make sure to close the cursor
13 cursor.close();
14 return items;
15 }
16
17 private Item cursorToItem(Cursor cursor) {
18 Item item = new Item();
19 item.setId(cursor.getLong(0));
20 item.setItem(cursor.getString(1));
21 item.setPrice(cursor.getString(2));
22 return item;
23 }
24
25Cursor cursor = database.query(MySQLiteHelper.TABLE_ITEMS,
26 allColumns, null, null, null, null, null);
27
28public Item createItem(String item, String price) {
29 ContentValues values = new ContentValues();
30 values.put(MySQLiteHelper.COLUMN_ITEM, item);
31 values.put(MySQLiteHelper.COLUMN_PRICE, price);
32 long insertId = database.insert(MySQLiteHelper.TABLE_ITEMS, null,
33 values);
34 // To show how to query
35 Cursor cursor = database.query(MySQLiteHelper.TABLE_ITEMS,
36 allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
37 null, null, null);
38 cursor.moveToFirst();
39 return cursorToItem(cursor);
40 }
41
42Cursor cursor = database.query(MySQLiteHelper.TABLE_ITEMS,
43 allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
44 null, null, null);
45
46package nupos.nupay.app;
47
48import android.content.Context;
49import android.database.sqlite.SQLiteDatabase;
50import android.database.sqlite.SQLiteOpenHelper;
51import android.util.Log;
52
53public class MySQLiteHelper extends SQLiteOpenHelper {
54
55public static final String TABLE_ITEMS = "items";
56public static final String COLUMN_ID = "_id";
57public static final String COLUMN_ITEM = "item";
58public static final String COLUMN_PRICE = "price";
59
60private static final String DATABASE_NAME = "items_test.db";
61private static final int DATABASE_VERSION = 1;
62
63// Database creation sql statement
64private static final String DATABASE_CREATE = "create table "
65 + TABLE_ITEMS + "( " + COLUMN_ID
66 + " integer primary key autoincrement, " + COLUMN_ITEM
67 + " text not null," + COLUMN_PRICE
68 +" text not null);";
69
70public MySQLiteHelper(Context context) {
71 super(context, DATABASE_NAME, null, DATABASE_VERSION);
72}
73
74@Override
75public void onCreate(SQLiteDatabase database) {
76 database.execSQL(DATABASE_CREATE);
77}
78
79@Override
80public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
81 Log.w(MySQLiteHelper.class.getName(),
82 "Upgrading database from version " + oldVersion + " to "
83 + newVersion + ", which will destroy all old data");
84 db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
85
86
87 onCreate(db);
88}
89
90 }