private SQLiteDatabase db;
private static final String DATABASE_NAME = "Sample.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "sample_table";
private static String DB_PATH = "";
private static final String CREATE_TABLE = "create table TABLE_NAME (id integer primary key autoincrement, name text, surname text);";
private static final String DROP_TABLE = "drop table TABLE_NAME if exist");";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
db.onCreate();
}
private static boolean isDataBaseExist(){
File file =new File(DB_PATH + DATABASE_NAME);
return file.exists();
}
public DBHelper open() throws SQLException {
isDataBaseExist();
if (isDataBaseExist() == false) {
db=getWritableDatabase();
if (db.isOpen())
db.close();
}
db = getWritableDatabase();
return this;
}
public void closedb() {
db.close();
}
public void addMethod(String id, String name) {
try {
ContentValues initialValues = new ContentValues();
initialValues.put("id", id);
initialValues.put("name", name);
db.insert(TABLE_NAME, null, initialValues);
} catch (Exception e) {
e.printStackTrace();
}
}
public ArrayList<SampleData> viewMethod(){
ArrayList<SampleData> sampleData=new ArrayList<SampleData>();
sampleData.clear();
db=this.getWritableDatabase();
String[] columns={"id", "name"};
Cursor cursor=db.query(TABLE_NAME, columns, null, null, null, null, null);
while(cursor.moveToNext()){
sampleData.add(new sampleData(cursor.getString(0), cursor.getString(1)));
}
cursor.close();
return sampleData;
}
public void removeMethod(){
db.delete(TABLE_NAME, null, null);
}
No comments:
Post a Comment