이렇게 하면 DB 사용이 깔끔해 진다.
Ex)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_bar);
dbAdapter = new DiscoverDbAdapter(getApplicationContext());
dbAdapter.open();
....................
..................
}
............
............
dbAdapter.insearchKeyword(dateFormat.format(calendar.getTime()), keyword);
..................................
ArrayList<String> lstHistory = dbAdapter.getHistory();
........................
........................
dbAdapter.close();
}
public class DiscoverDbAdapter {
private static final String DATABASE_NAME = "discover_history.db";
private static final String TABLE_NAME = "search_history_discover";
private static final String HISTORY_DATE = "history_date";
private static final String HISTORY_SEARCH = "search_keyword";
private DatabaseHelper dbHelper;
private SQLiteDatabase db = null;
private Context context = null;
public DiscoverDbAdapter(Context context){
this.context = context;
}
/* open 메써드를 만들어서 dbHelper를 생성하고, 읽기&쓰기 속성을 준다.
public DiscoverDbAdapter open() throws SQLException{
dbHelper = new DatabaseHelper(context);
db = dbHelper.getWritableDatabase();
return this;
}
/* close 메써드를 만들어서 helper와 db 객체를 닫는다.
public void close(){
if(dbHelper != null) dbHelper.close();
if(db != null) db.close();
}
/* helper 클래쓰를 내부에 만든다.
private class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1); //version
}
/* 생성 함수 - Create Table
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(_id INTEGER PRIMARY KEY, " + HISTORY_DATE + " CHAR(14), " + HISTORY_SEARCH + " VARCHAR(30));");
}
/* Upgade 는 옵션
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
}
}
/* 각종 DB를 사용하는 여러 Function 들(inSearchKeyWord(), getHistory(), ... 등등)을 메서드로 Adapter 내부에 선언해서,
객체를 호출 한 뒤, 메서들 사용하는 방식으로 쓴다. */
public void insearchKeyword(String date, String keyword){
Cursor c = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
if(c.getCount() > 9){
deleteHistory();
}
if(!keyword.trim().equals(""))
db.execSQL("INSERT INTO " + TABLE_NAME + "(" + HISTORY_DATE + ", " + HISTORY_SEARCH + ") values('" + date + "', '" + keyword + "');");
c.close();
}
private void deleteHistory(){
db.execSQL("DELETE FROM " + TABLE_NAME + " WHERE " + "_id" +"=(SELECT " + "_id" + " FROM " + TABLE_NAME + " ORDER BY " + HISTORY_DATE + " ASC LIMIT 1);");
}
public ArrayList<String> getHistory(){
ArrayList<String> lstHistory = new ArrayList<String>();
Cursor c = db.rawQuery("SELECT * FROM " + TABLE_NAME + " ORDER BY " + HISTORY_DATE + " DESC", null);
while(c.moveToNext()){
lstHistory.add(c.getString(c.getColumnIndex(HISTORY_SEARCH)));
}
c.close();
return lstHistory;
}
}
댓글 없음:
댓글 쓰기