The Sqlite helper class helps us manage database creation and versioning. SQLiteOpenHelper takes care of all database management activities. To use it,
1.Override onCreate(), onUpgrade() SQLiteOpenHelper methods. It is not necessary to override the onOpen () method.
2. Use this subclass to create either a readable or writable database and use the four API methods SQLiteDatabase insert(), execSQL(), update(), delete() to create, read, update, and delete rows in your table.
An example of creating a table MyEmployees and to select and insert records:
public class MyDatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "DBName"; private static final int DATABASE_VERSION = 2;
Now you can use this class as shown below.
public class MyDB{ private MyDatabaseHelper dbHelper; private SQLiteDatabase database; public final static String EMP_TABLE="MyEmployees"; // name of table public final static String EMP_ID="_id"; // id value for employee public final static String EMP_NAME="name"; // name of employee /** * * @param context */ public MyDB(Context context){ dbHelper = new MyDatabaseHelper(context); database = dbHelper.getWritableDatabase(); } public long createRecords(String id, String name){ ContentValues values = new ContentValues(); values.put(EMP_ID, id); values.put(EMP_NAME, name); return database.insert(EMP_TABLE, null, values); } public Cursor selectRecords() { String[] cols = new String[] {EMP_ID, EMP_NAME}; Cursor mCursor = database.query(true, EMP_TABLE,cols,null , null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; // iterate to get each value. } }
Now you can use the MyDB class in your activity to have all database operations. The created records will help you insert values ββin the same way, you can have your own functions for updating and deleting.
Vinay Aug 18 2018-12-12T00: 00Z
source share