안드로이드 프로그래밍 이라는 책의
예제중 7-6 을 보니 제가 하고싶은 사항이 딱 있던데요...
그 사항중
외부에서 .sqlite 의 확장자를 갖는 DB파일을 불러오고, 저장하는... 그런 기능을 구현하고자 합니다.
Ex07_06Activity.java
package com.ex0706;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class Ex07_06Activity extends Activity {
ListView listView;
MySQLiteHandler handler;
Cursor c;
SimpleCursorAdapter adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = (ListView)findViewById(R.id.listView1);
handler = MySQLiteHandler.open(getApplicationContext());
c = handler.selectAll();
startManagingCursor(c);
adapter =
new SimpleCursorAdapter(
getApplicationContext(),
R.layout.list_row,
c,
new String[]{"_id","name","address","age"},
new int[]{ R.id.txtId, R.id.txtName, R.id.txtAddress, R.id.txtAge },
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
try{
//데이터 누적용
StringBuffer data = new StringBuffer();
FileInputStream fis = openFileInput("student1.sqlite");
BufferedReader buffer = new BufferedReader(new InputStreamReader(fis));
String str = buffer.readLine();
while( str != null ){
str = buffer.readLine();
data.append(str+"\n");
}
}catch(Exception e){ e.printStackTrace();}
listView.setAdapter(adapter);
// 학생정보 자세히 보기
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
TextView tv = (TextView)v.findViewById(R.id.txtId);
Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
intent.putExtra("_id", tv.getText().toString());
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mymenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch( item.getItemId() ){
case R.id.addMenu:
LayoutInflater inf = getLayoutInflater();
View convertView = inf.inflate(R.layout.studentadd, null);
final EditText editName = (EditText)convertView.findViewById(R.id.editName);
final EditText editAddress = (EditText)convertView.findViewById(R.id.editAddress);
final EditText editAge = (EditText)convertView.findViewById(R.id.editAge);
AlertDialog.Builder builder = new AlertDialog.Builder(Ex07_06Activity.this);
builder.setTitle("품목추가");
builder.setIcon(android.R.drawable.stat_sys_warning);
builder.setView(convertView);
builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String name = editName.getText().toString();
String address = editAddress.getText().toString();
String age =editAge.getText().toString();
handler.insert(name, address ,Integer.parseInt(age) );
//추가 내용 다시 가져오기
c.requery();
adapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("취소", null);
builder.show();
break;
case R.id.loginMenu:
case R.id.preferMenu:
}//end
return super.onOptionsItemSelected(item);
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------
MySQLiteHandler.java
package com.ex0706;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class MySQLiteHandler {
MySQLiteOpenHelper helper;
SQLiteDatabase db;
public MySQLiteHandler(Context ctx){
helper = new MySQLiteOpenHelper(ctx, "student1.sqlite", null, 1);
}
// 데이터베이스 open
public static MySQLiteHandler open(Context ctx){
return new MySQLiteHandler(ctx);
}
//데이터베이스 close
public void close(){
helper.close();
}
//데이터 저장
public void insert( String name,String address , int age){
db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("age", age);
values.put("address", address);
db.insert("student", null, values);
}
//데이터 수정
public void update(String id, String name , String address , String age ){
db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("address", address);
values.put("age", age);
db.update("student", values, "_id = ?", new String[]{ id });
}
//데이터 삭제
public void delete(String id){
db = helper.getWritableDatabase();
db.delete("student", " _id = ? ", new String[]{ id } );
}
//데이터 조회
public Cursor selectAll(){
db = helper.getReadableDatabase();
Cursor c = db.query("student", null, null, null, null, null, null);
return c;
}
//_id 일치 데이터 얻기
public Cursor selectById(String _id){
db = helper.getReadableDatabase();
Cursor c = db.query("student", null, "_id = ?", new String[]{ _id }, null, null, null);
return c;
}//end select
}
------------------------------------------------------------------------------------------------------------------------------------------------------
MySQLiteOpenHelper.java
package com.ex0706;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class MySQLiteOpenHelper extends SQLiteOpenHelper {
public MySQLiteOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
//테이블 생성 코드
String sql = "create table student ( _id integer primary key autoincrement ," +
" name text , address text , age integer)";
db.execSQL(sql);
String sss = "insert into student ( name, age ,address ) values ( '홍길동' , 18,'서울')";
db.execSQL(sss);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//테이블 삭제 코드
String sql = "drop table if exists student";
db.execSQL(sql);
onCreate(db);
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------
java 파일들의 내용은 위와 같습니다...
내용중에 데이터베이스 Open 쪽을 파일불러오는걸로 바꾸면 될듯도 한데.. 그게 않되네요 ㅠㅠ...
하나부터 열까지 배워가면서 하는게 아니라 책의 앞쪽만 슬쩍 읽고 예제만 보고 한거라서 도저히 ㅠㅠ........
알려주십시오... 부탁드립니다