Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.LinkedList;
- import java.util.List;
- import android.content.ContentValues;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- import android.util.Log;
- public class MySQLiteHelper extends SQLiteOpenHelper {
- // Database Version
- private static final int DATABASE_VERSION = 1;
- // Database Name
- private static final String DATABASE_NAME = "MedicineDb";
- public MySQLiteHelper(Context context) {
- super(context, DATABASE_NAME, null, DATABASE_VERSION);
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- // SQL statement to create medicine table
- String CREATE_BOOK_TABLE = "CREATE TABLE medicines ( " +
- "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
- "title TEXT )";
- // create medicine table
- db.execSQL(CREATE_MEDICINNE_TABLE);
- }
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- // Drop older medicine table if existed
- db.execSQL("DROP TABLE IF EXISTS medicines");
- // create fresh medicine table
- this.onCreate(db);
- }
- //----------------------------------------------------------
- public Medicine getMedicineList(int id){
- // 1. get reference to readable DB
- SQLiteDatabase db = this.getReadableDatabase();
- // 2. build query
- Cursor cursor =
- db.query(TABLE_MEDICINS, // a. table
- COLUMNS, // b. column names
- " id = ?", // c. selections
- new String[] { String.valueOf(id) }, // d. selections args
- null, // e. group by
- null, // f. having
- null, // g. order by
- null); // h. limit
- // 3. if we got results get the first one
- if (cursor != null)
- cursor.moveToFirst();
- // 4. build medicine object
- Medicine medicine = new Medicine();
- medicine.setId(Integer.parseInt(cursor.getString(0)));
- medicine.setTitle(cursor.getString(1));
- Log.d("getMedicineList("+id+")", medicine.toString());
- // 5. return medicine
- return medicine;
- }
- // Get All medicines
- public List<Medicine> getAllMedicines() {
- List<Medicins> medicines = new LinkedList<Medicine>();
- // 1. build the query
- String query = "SELECT * FROM " + TABLE_MEDICINS;
- // 2. get reference to writable DB
- SQLiteDatabase db = this.getWritableDatabase();
- Cursor cursor = db.rawQuery(query, null);
- // 3. go over each row, build medicine and add it to list
- Medicine medicine = null;
- if (cursor.moveToFirst()) {
- do {
- medicine = new Medicine();
- medicine.setId(Integer.parseInt(cursor.getString(0)));
- medicine.setTitle(cursor.getString(1));
- // Add medicine to medicines
- medicines.add(medicine);
- } while (cursor.moveToNext());
- }
- Log.d("getMedicineList()", medicines.toString());
- // return medicines
- return medicines;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement