Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 전화걸기
- Menu
- 이클립스
- AWT
- 생성자
- OGNL
- 메서드
- oracle
- 메소드
- JavaScript
- 어노테이션
- mybatis
- struts2
- HTML
- 예외처리
- 국제화
- Eclips
- 클래스
- 기본
- Graphic
- JSP
- 안드로이드
- paint
- 배열
- 에러페이지
- 오버로딩
- Android
- layout
- Spring
- Java
Archives
- Today
- Total
note
SQLite 연동하기 본문
실행 화면입니다.
db파일 생성 여부 확인방법은
DDMS 진입후
data > data > 자신의 패키지명 > databases > 파일
저장 해서 보려면은 바로 이 이미지 위에 디스켓 모양이 있는데 파일 선택후 그것을 클릭하면 됩니다.
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:layout_height="wrap_content" android:layout_width="fill_parent" > <TextView android:id="@+id/view_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:width="50dp" android:hint="@string/id_label" /> <EditText android:id="@+id/edit_memo" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:layout_height="wrap_content" android:layout_width="fill_parent" > <Button android:id="@+id/delete_button" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_weight="1" android:text="@string/delete_label" /> <Button android:id="@+id/modify_button" android:layout_height="wrap_content" android:layout_weight="1" android:layout_width="fill_parent" android:text="@string/modify_label" /> <Button android:id="@+id/add_button" android:layout_height="wrap_content" android:layout_weight="1" android:layout_width="fill_parent" android:text="@string/add_label" /> </LinearLayout> <ListView android:id="@android:id/list" android:choiceMode="singleChoice" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <!-- ListView에 표시할 데이터가 없을 ㄸㅐ 위아래 위젯이 보여짐 --> <TextView android:id="@android:id/empty" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/no_memo" /> </LinearLayout>
memo_row.xml
<?xml version="1.0" encoding="utf-8"?> <!-- memo_row.xml --> <!-- 목록보기 1 줄에 배치 --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" > <!-- ID가 표시되는 텍스트 뷰 --> <TextView android:id="@+id/_id" android:layout_width="50dp" android:layout_height="wrap_content" /> <!-- 메모보기 텍스트 뷰 --> <TextView android:id="@+id/memo_text" android:padding="5px" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>
DatabaseAdapter
package kr.android.sqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseAdapter {
/*=-=-=-=-=-=-=-=-상수 정의 시작=-=-=-=-=-=-=-=-*/
//Log 처리를 위한 TAG지정
static final String TAG = "DatabaseHandler";
//데이터 베이스 파일이름
static final String DB_NAME ="daily_memo.db";
//테이블 이름
static final String TABLE_NAME="daily_memo";
//데이터베이스 각열의 이름
static final String MEMO_ID="_id";
static final String MEMO_CONTENT="content";
//컬럼 인덱스
static final int ID_INDEX= 0;
static final int CONTENT_INDEX =1;
//컬럼 명세
static final String[] PROJECTION = new String[] {MEMO_ID,MEMO_CONTENT};
//테이블 생성 SQL
static final String CREATE_TABLE ="CREATE table "+TABLE_NAME+" ("+MEMO_ID+" integer primary key autoincrement, "+MEMO_CONTENT+" text not null);";
//테이블 삭제 SQL
static final String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_NAME+";";
/*=-=-=-=-=-=-=-=-상수 정의 끝=-=-=-=-=-=-=-=-*/
//데이터 베이스 연동 객체
private SQLiteDatabase db;
//데이터 베이스를 이용하는 어플리케이션의 컨텍스트
private Context context;
public DatabaseAdapter(Context context){
this.context=context;
}
//SQLiteDatabase 생성
public void open() throws SQLException{
try{
db =(new DatabaseHelper(context)).getWritableDatabase();
}catch(SQLiteException e){
db =(new DatabaseHelper(context)).getReadableDatabase();
}
}
//SQLiteDatabase 자원정리
public void Close(){
db.close();
}
//전체 행을 ID의 내림차순으로 호출
public Cursor fetchAllMemo(){
return db.query(TABLE_NAME, //테이블명
PROJECTION, //컬럼명세
null, //where 절
null, //where 절에 전달될 데이터
null, //group by
null, //having
MEMO_ID + " DESC " //order by
);
}
//업데이트
public void setMemo(String id, String content){
//업데이트 값 설정
ContentValues values = new ContentValues();
//데이터 등록(컬럼명 , 수정할 데이터)
values.put(MEMO_CONTENT, content);
//행을 업데이트
db.update(TABLE_NAME, //테이블 명
values, //수정할 데이터
MEMO_ID + " = ?", //where절
new String[]{ id } //where절 ?에 전달될 primary key
);
}
//검색
public String searchMemo(String str){
//읽을 데이터의 조건
String where = MEMO_CONTENT+" like ?";
//where의 ?을 대체할 매개 변수
String param = str.substring(0,1) + "%";
//검색
Cursor c = db.query(
TABLE_NAME,
PROJECTION,
where, //WHERE
new String[] { param }, //LIKE
null, //GROUP BY
null, //HAVING
MEMO_ID+ " DESC", //ORDERED BY 새로운 정렬
"10"); //LIMIT 최대 10개
StringBuffer buff = new StringBuffer();
if(c.moveToFirst()){
//검색 결과를 차례로 꺼내 문자열에 추가
do{
long id = c. getLong(ID_INDEX);
buff.append("id(").append(id).append(") ");
String memo = c.getString(CONTENT_INDEX);
buff.append(memo).append("\n");
}while(c.moveToNext());
}
c.close();
return buff.toString();
}
//데이터를 추가하고 추가된 데이터의 primary key(_id)반환
public String addMemo(String content){
ContentValues values = new ContentValues();
values.put(MEMO_CONTENT, content);
long id =db.insert(TABLE_NAME, MEMO_CONTENT, values);
if(id < 0){
return "";
}
return Long.toString(id);
}
//지정된 ID의 행삭제
public void deleteMemo(String id){
db.delete(TABLE_NAME, //테이블명
MEMO_ID + " = ?", //where절
new String[] { id } //where절 ? 에 전달될 데이터
);
}
/*=-=-=--=-=-=-=-=-=SQLiteOPenHelper를 상속받아 구현한 클래스=-=-=-=-=-=-=-=-*/
public class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context context){
super(context, DB_NAME, null, 1);
}
//데이터 베이스를 새로 만든 다음 호출
public void onCreate(SQLiteDatabase db){
//내부에 테이블 만들기
db.execSQL(CREATE_TABLE);
}
//존재하는 데이터 베이스로 정의하고 있는 버전이 다를때 super(context, DB_NAME, null, 1); -> 2
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion){
Log.w(TAG,"Version mismatch : "+oldVersion+" to "+newVersion);
//여기에서는 테이블을 삭제하고 새로 작성함
//일반적으로 테이블의 데이터 변환을 수행
db.execSQL(DROP_TABLE);
onCreate(db);
}
}
}
SQLiteDemo
package kr.android.sqlite;
import android.app.ListActivity;
import android.os.Bundle;
import android.database.Cursor;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class SQLiteDemo extends ListActivity implements OnClickListener {
static final String TAG = "SQLiteDemo";
private TextView mCurrentId;
private EditText mEdit;
private SimpleCursorAdapter mAdapter;
private DatabaseAdapter dbHandler;
Cursor c;
// 작업의 시작 버튼 등록
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mCurrentId = (TextView) findViewById(R.id.view_id);
mEdit = (EditText) findViewById(R.id.edit_memo);
// 버튼 등록
int buttons[] = { R.id.delete_button, R.id.modify_button,
R.id.add_button };
for (int id : buttons) {
Button button = (Button) findViewById(id);
button.setOnClickListener(this);
}
setEnabled(false);
}
// 작업이 포그라운드 상태가 아닌경우, DB를 Close하기
@Override
protected void onPause() {
super.onPause();
c.close(); // Cursor close
dbHandler.Close();// SQLiteDatabase close
}
// 작업이 포그라운드 된 시간에 데이터를 표시
@Override
protected void onResume() {
super.onResume();
// DatabaseHandler 호출
dbHandler = new DatabaseAdapter(this);
// SQLiteDatabase 생성
dbHandler.open();
// 커서를 가져갈 경우
c = dbHandler.fetchAllMemo();
// 데이터 베이스 칼럼과 뷰를 연결
String[] from = new String[] { DatabaseAdapter.MEMO_ID,
DatabaseAdapter.MEMO_CONTENT };
int[] to = new int[] { R.id._id, R.id.memo_text };
mAdapter = new SimpleCursorAdapter(this, R.layout.memo_row, c, from, to);
setListAdapter(mAdapter);
}
// 버튼을 눌렀을때의 동작
public void onClick(View view) {
String id = mCurrentId.getText().toString();
String str = mEdit.getText().toString();
if (view.getId() == R.id.add_button) {
if (str.length() != 0) {
dbHandler.addMemo(str);
toastMemo(str);
}
}else if(view.getId() == R.id.delete_button){
dbHandler.deleteMemo(id);
}else if(view.getId() == R.id.modify_button){
dbHandler.setMemo(id,str);
toastMemo(str);
}
//커서를 다시 꺼내고 뷰를 다시 그리기
mCurrentId.setText("");
mEdit.setText("");
setEnabled(false);
//테이블에 select 문장을 다시 수행해서 변경된 정보를 재탐색
//Cursor가 SimpleCursorAdapter에 등록되어 있고
//SimpleCursorAdapter는 ListView에 연결되어 있어서
//requery()메소드가 동작하고 연속으로 데이터 갱신 작업 및 화면 갱신작업이 일어남
c.requery();
}
// 목록 탭 되었을때 처리
@Override
protected void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
//탭된 행의 ID와 메모의 내용을 텍스트 편집 화면으로 설정
LinearLayout layout = (LinearLayout)v;
TextView t = (TextView)layout.findViewById(R.id.memo_text);
mEdit.setText(t.getText());
mCurrentId.setText(Long.toString(id));
setEnabled(true);
//탭된 행의 내용검색
toastMemo(t.getText().toString());
}
//삭제 , 수정 버튼 상태 변경
private void setEnabled(boolean enabled){
int buttons[] = {R.id.delete_button,R.id.modify_button};
for(int id: buttons){
Button button =(Button)findViewById(id);
button.setEnabled(enabled);
}
}
//검색된 내용 표시
private void toastMemo(String str){
if(str.length() == 0){
//문서가 없을 때는 아무것도 하지 않는다.
return;
}
String memo = dbHandler.searchMemo(str);
Toast toast = Toast.makeText(getApplicationContext(), memo, Toast.LENGTH_LONG);
toast.show();
}
}
'Android > 기본' 카테고리의 다른 글
안드로이드 프로세스 말끔히 죽이기 (0) | 2012.01.28 |
---|---|
Xml 가져오기 (날씨) (0) | 2012.01.19 |
터치해서 화면 전환 Flipper Touch (0) | 2012.01.18 |
ListIcon (ListView에 아이콘,버튼) (0) | 2012.01.18 |
News Service 주기적으로 데이터 가지고 오기 (0) | 2012.01.18 |