DBAdapter클래스
-----------------------------
public class DBAdapter extends SQLiteOpenHelper {
//여기서 설정한 DATABASE_NAME 이름으로 db 파일명이 생성된다.
// sqlite 는 파일형태로 db를 생성합니다.
public static final String KEY_TITLE1 = "foodname";
public static final String KEY_BODY1 = "calorie";
public static final String KEY_BODY2 = "amount";
public static final String KEY_BODY3 = "counte";
public static final String KEY_ROWID = "code";
private static final String TAG = "DBAdapter";
//private static final String DATABASE_TABLE = "foodlist";
private static final String DATABASE_NAME = "food.db";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_TABLE = "foodlist";
private static final String DATABASE_CREATE =
"create table foodlist (code integer primary key autoincrement, "
+ "foodname text not null, calorie text not null,amount text not null, counte text not null);";
private DBAdapter mDbHelper;
private SQLiteDatabase mDb;
private final Context mCtx;
// 생성자는 반드시 구현해야 한다.
public DBAdapter(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.mCtx = context;
}
/** Called when the activity is first created. */
@Override
public void onCreate(SQLiteDatabase db) {
//최초에는 사용할 테이블을 생성한다.
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS foodlist");
onCreate(db);
}
//
private void copydb(Activity act) {
AssetManager am = act.getAssets();
File folder = new File("/data/data/com.fi.searchview/databases/");
folder.mkdirs();
File f = new File("/data/data/com.fi.searchview/databases/food.db");
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
InputStream is = am.open("food.db");
BufferedInputStream bis = new BufferedInputStream(is);
// 만약에 파일이 있다면 지우고 다시 생성
if (f.exists()) {
f.delete();
f.createNewFile();
}
fos = new FileOutputStream(f);
bos = new BufferedOutputStream(fos);
int read = -1;
byte[] buffer = new byte[1024];
while ((read = bis.read(buffer, 0, 1024)) != -1) {
bos.write(buffer, 0, read);
}
bos.flush();
fos.close();
bos.close();
is.close();
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//
//------------ 조회하기 ---------------------------------
public BoardCursor searchList(String searchType, String SearchValue){
StringBuffer sqlStr = new StringBuffer();
sqlStr.append("\n SELECT * FROM foodlist WHERE 1=1 ");
//사용자가 입력한 검색조건을 쿼리에 적용
if(SearchValue != null && !SearchValue.equals("")){
//이름 searchType 는 리스트의 순서대로 인덱스가 설정되어 있다 0~2
if(searchType.equals("0")){
sqlStr.append("\n AND foodname like '%"+SearchValue+"%' ");
//칼로리
}else if(searchType.equals("1")){
sqlStr.append("\n AND calorie like '%"+SearchValue+"%' ");
//이름+칼로리
}else if(searchType.equals("2")){
sqlStr.append("\n AND ( foodname like '%"+SearchValue+"%' ");
sqlStr.append("\n OR calorie like '%"+SearchValue+"%' ) ");
}
}
sqlStr.append("\n ORDER BY code DESC; ");
SQLiteDatabase rd = getReadableDatabase();
//다른 방법도 있지만 일단은 커서를 사용하여 조회하는 것 부터 해본다.
BoardCursor bc = (BoardCursor) rd.rawQueryWithFactory(
new BoardCursor.Factory()
,sqlStr.toString()
,null
,null);
//반드시 커서를 맨 위로 올려야 한다.
bc.moveToFirst();
return bc;
}
public static class BoardCursor extends SQLiteCursor{
public BoardCursor(SQLiteDatabase db, SQLiteCursorDriver driver, String editTable, SQLiteQuery query) {
super(db, driver, editTable, query);
// TODO Auto-generated constructor stub
}
public static class Factory implements SQLiteDatabase.CursorFactory{
public Cursor newCursor(
SQLiteDatabase db
,SQLiteCursorDriver masterQuery
,String editTable
,SQLiteQuery query) {
return new BoardCursor(db, masterQuery, editTable, query);
}
}
}
//------------입력하기 ---------------------------------
public void insertBoard(){
StringBuffer sqlStr = new StringBuffer();
sqlStr.append("\n INSERT INTO foodlist(foodname, calorie, amount ,counte) ");
sqlStr.append("\n VALUES('한번더','한번','20110216','20110216','하루 전','내용들'); ");
SQLiteDatabase wd = getWritableDatabase();
wd.execSQL(sqlStr.toString());
}
public DBAdapter open() throws SQLException {
mDbHelper = new DBAdapter(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public long createfoodlist(String foodname,String calorie ,String amount, String counte) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE1, foodname);
initialValues.put(KEY_BODY1, calorie);
initialValues.put(KEY_BODY2, amount);
initialValues.put(KEY_BODY3, counte);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean deletefoodlist(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
public Cursor fetchAlltype3() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE1,
KEY_BODY1,KEY_BODY2,KEY_BODY3 }, null, null, null, null, null);
}
public Cursor fetchfoodlist(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE1, KEY_BODY1,KEY_BODY2, KEY_BODY3}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean updatefoodlist(long rowId, String foodname, String calorie,String amount, String counte) {
ContentValues args = new ContentValues();
args.put(KEY_TITLE1, foodname);
args.put(KEY_BODY1, calorie);
args.put(KEY_BODY2, amount);
args.put(KEY_BODY3, counte);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
-------------------------------------------------------
SearchView 클래스
-------------------------------------------------------
public class SearchView extends Activity{
Context context;
DBAdapter db;
com.fi.searchview.DBAdapter.BoardCursor bc;
TableLayout tbl;
LinearLayout msgll;
Spinner searchType;
EditText searchVal;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.searchtext);
//DB 를 담당할 인스터스 객체를 생성한다.
db = new DBAdapter(this);
//search 버튼 이벤트 리스너
Button btn_search = (Button)findViewById(R.id.btnShowList);
btn_search.setOnClickListener(btn_search_listener);
//검색 리스트 에 넣을 내용이다.
searchType = (Spinner)findViewById(R.id.searchType);
List searchTypeList = new ArrayList();
searchTypeList.add("이름");
searchTypeList.add("칼로리");
searchTypeList.add("이름+칼로리");
//검색 리스트 세팅
ArrayAdapter AASearchType = new ArrayAdapter(this,android.R.layout.simple_spinner_item,searchTypeList);
AASearchType.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//세팅한 아이템과 설정을 적용
searchType.setAdapter(AASearchType);
//다른 메소드에서도 사용할 수 있도록 객체를 초기화한다.
tbl = (TableLayout) findViewById(R.id.tbl);
msgll = (LinearLayout) findViewById(R.id.msgll);
searchVal = (EditText) findViewById(R.id.searchVal);
}
/**
* search 버튼 이벤트 리스너
*/
private final OnClickListener btn_search_listener =
new OnClickListener(){
public void onClick(View v) {
boardList();
}
};
private void boardList(){
//검색어가 있을 경우 가져온다.
String searchType = String.valueOf(this.searchType.getSelectedItemId()).trim();
String searchVal = String.valueOf(this.searchVal.getText()).trim();
//db 에서 리스트를 조회해서 가져온다.
bc = db.searchList(searchType, searchVal);
msgll.removeAllViews();
//리스트의 행을 초기화한다. 위에서 검색한 데이터로 다시 그려야 하므로...
tbl.removeAllViews();
//조회한 리스트를 가져오는 부분
for(int i=0;i<bc.getCount();i++){
bc.moveToPosition(i);
//TableLayout 에 tr 행을 추가한다.
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(
android.view.ViewGroup.LayoutParams.FILL_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT)
);
//가운데 정렬 - 여러가지 정렬에 관한 값이 있다 소스 밑에 적어두겠다~
tr.setGravity(android.view.Gravity.CENTER);
//추가한 행의 각 열에 추가할 TextView
TextView btn1 = new TextView(this);
btn1.setText(bc.getString((bc.getColumnIndexOrThrow("foodname"))));
btn1.setPadding(5, 5, 5, 5);
btn1.setHeight(50);
btn1.setGravity(android.view.Gravity.CENTER);
btn1.setWidth(130);
btn1.setTextSize(12);
tr.addView(btn1);
TextView btn2 = new TextView(this);
btn2.setText(bc.getString(bc.getColumnIndexOrThrow("calorie")));
btn2.setPadding(5, 5, 5, 5);
btn2.setHeight(50);
btn2.setGravity(android.view.Gravity.CENTER);
btn2.setWidth(55);
btn2.setTextSize(12);
tr.addView(btn2);
TextView btn3 = new TextView(this);
btn3.setText(bc.getString(bc.getColumnIndexOrThrow("amount")));
btn3.setPadding(5, 5, 5, 5);
btn3.setHeight(50);
btn3.setGravity(android.view.Gravity.CENTER);
btn3.setWidth(55);
btn3.setTextSize(12);
tr.addView(btn3);
TextView btn4 = new TextView(this);
btn4.setText(bc.getString(bc.getColumnIndexOrThrow("counte")));
btn4.setPadding(5, 5, 5, 5);
btn4.setHeight(50);
btn4.setGravity(android.view.Gravity.CENTER);
btn4.setWidth(60);
btn4.setTextSize(12);
tr.addView(btn4);
//TableLayout 에 생성한 tr 열을 추가한다
tbl.addView(tr);
}
//검색결과가 없을 경우
if(bc.getCount()==0){
TextView msg = new TextView(this);
msg.setText("검색결과가 없습니다.");
msg.setHeight(30);
msg.setGravity(android.view.Gravity.CENTER);
msgll.addView(msg);
}
}
}
=====================================================
음식검색하는어플입니다.
어디서 줒어들은건 있어서 메인페스트수정도 했구요, db파일은 540kb정도입니다.
assets에 있는db파일을 ddms에서 data/data/패키지/database에 직접 넣으면 검색이 되는데
직접 넣지않으면 안되네요..
손을 봐야하는 느낌이 팍팍오긴하는데 어떻게 손봐야 할지 모르겠습니다.
도와주세요 ㅠㅠ