2011년 4월 20일 수요일

ajax로 XML 만들때 컨텐트 타입 설정...

response.setContentType("text/xml;charset=utf-8");
PrintWriter out = response.getWriter();

만약
response.setContentType("text/xml;charset=utf-8");

out 아래에 위치하면 태국어를 비롯한 UTF로 인코딩 되지 않아서 에러가 난다.
정말 중요함...

2011년 4월 14일 목요일

안드로이드에서 데이터베이스 다루기

원문
http://www.devx.com/wireless/Article/40842/1954

Creating and Using Databases in Android
안드로이드에서 데이터베이스 생성 및 사용하기


Every application uses data, and Android applications are no exception. Android uses the open-source, stand-alone SQL database, SQLite. Learn how to create and manipulate a SQLite database for your Android app.
by Wei-Meng Lee

모든 애플리케이션은 데이터를 사용한다. 안드로이드 애플리케이션 또한 예외는 없다. 안드로이드는 오픈소스, 스탠드얼론 형태의 SQL Database SQLite를 사용한다. 당신의 안드로이드 애플리케이션을 위해서 SQLite 다루는 법을 배워보자.
by Wei-Meng Lee

Database support is the lifeline of every application, big or small. Unless your application deals only with simple data, you need a database system to store your structured data. Android uses the SQLite database system, which is an open-source, stand-alone SQL database, widely used by many popular applications. For example, Mozilla Firefox uses SQLite to store configuration data and iPhone also uses SQLite for database storage.
데이터베이스 지원은
그것이 작던 크던간에 모든 애플리케이션의 생명선이다. 당신이 개발한 애플리케이션이 단순한 데이터만을 다루지 않는다면 구조화된 데이터를 적재할 수 있는 데이터베이스가 필요하다. 안드로이드는 오픈소스, 스탠드얼론이면서 다른 유명한 애플리케이션에의해 널리 사용되는 SQLite 데이터베이스를 사용한다. 예를들면 모질라 파이어폭스는 설정파일을 SQLite에 저장하며 아이폰 또한 데이터베이스 적재목적으로 SQLite를 사용한다.

In Android, the database that you create for an application is only accessible to itself; other applications will not be able to access it. Once created, the SQLite database is stored in the/data/data/e>/databases folder of an Android device. In this article, you will learn how to create and use a SQLite database in Android
안드로이드에서 생성된 데이터베이스는 오직 해당 애플리케이션만 접근이 가능하다. 다른 애플리케이션은 접근이 불가능하다. 일단 생성이 되면 안드로이드 디바이스의 다음 위치에 '패키지이름'으로 저장이된다. /data/data/<패키지이름>/databases . 이 글에서는 안드로이드에서 어떻게 SQLite 데이터베이스를 생성하고 사용하는지 배우게 될 것이다.

-------------------------------------------------------------------------------------------------------------------------------------------------------------------
SQLite Database

Create an Android project using Eclipse and name it Database (see Figure 1).
이클립스를 사용하여 안드로드 프로젝트 생성하고 데이터베이스 이름짓기 (Figure1 참조)



Figure 1. Database: Your new Android project, created using Eclipse.
Creating the DBAdapter Helper Class
Figure 1. 데이터베이스: 이클립스를 사용하여 생성된 신규 안드로이드 프로젝트
DBAdapter Helper 클래스를 생성하자

A good practice for dealing with databases is to create a helper class to encapsulate all the complexities of accessing the database so that it's transparent to the calling code. So, create a helper class called DBAdapter that creates, opens, closes, and uses a SQLite database.
데이터베이스를 다루는 좋은 방법으로는 데이터베이스에 접근하는 모든 복잡한 요소들을 캡슐화해서 언제든지 불러서 사용할 수 있도록 해주는 헬퍼 클래스를 생성하는 것이다.

First, add a DBAdapter.java file to the src/ folder (in this case it is src/net.learn2develop.Database).
먼저
DBAdapter.java 파일을 src/패키지명 경로 아래에 생성하자.

In the DBAdapter.java file, import all the various namespaces that you will need:
DBAdapter.java 파일에서 필요한 모든 클래스를 임포트하자.
(주: 임포트를 해야만 해당클래스 내의 메쏘드를 사용 할 수 있죠)

=========================================================
package net.learn2develop.Databases;

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.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter
{

}

=========================================================

Next, create a database named bookstitles with the fields shown in Figure 2.
다음으로 Figure2에 나온대로 bookstitles라는 데이터베이스를 생성하자


Figure 2. The Database Fields: This shows the titles table you will be building in this article.
Figure2. 데이터베이스 필드 : 이 글에서 생성할 테이블을 보여준다.

In the DBAdapter.java file, define the following constants shown in Listing 1.
DBAdapter.java 파일에서 리스트1과 같이 상수들을 정의한다.

===================================================
package net.learn2develop.Database;

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.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter
{
public static final String KEY_ROWID = "_id";
public static final String KEY_ISBN = "isbn";
public static final String KEY_TITLE = "title";
public static final String KEY_PUBLISHER = "publisher";
private static final String TAG = "DBAdapter";

private static final String DATABASE_NAME = "books";
private static final String DATABASE_TABLE = "titles";
private static final int DATABASE_VERSION = 1;

private static final String DATABASE_CREATE =
"create table titles (_id integer primary key autoincrement, "
+ "isbn text not null, title text not null, "
+ "publisher text not null);";

private final Context context;
}

===================================================

The DATABASE_CREATE constant contains the SQL statement for creating the titles table within the books database.
DATABASE_CREATE 상수에는 books 데이터베이스 내에 titles 테이블을 만들기 위한 SQL 문장이 포함되어있다.

Within the DBAdapter class, you extend the SQLiteOpenHelper class-an Android helper class for database creation and versioning management. In particular, you override the onCreate() and onUpgrade() methods (as shown in Listing 2).
DBAdapter 클래스 내에는 데이터베이스 생성 및 버전 관리를 할 수 있는 SQLiteOpenHelper 클래스를 상속받고 특히 onCreate() 그리고 onUpgrade() 를 오버라이드 한다.

The onCreate() method creates a new database if the required database is not present. The onUpgrade() method is called when the database needs to be upgraded. This is achieved by checking the value defined in the DATABASE_VERSION constant. For this implementation of the onUpgrade() method, you will simply drop the table and create the table again.
onCreate() 메써드는 애플리케이션에서 필요하지만 현재는 존재하지 않는 새로운 데이터베이스를 생성한다. onUpgrade() 메써드는 데이터베이스가 업그레이드가 필요할때 호출된다.(주:업데이트는 인서트,삭제,업데이트를 의미함) DATABASE_VERSION 에 정의되어 있는 상수를 체크함으로 가능하다. onUpgrade() 메써드를 사용함으로 테이블을 드랍하고 새롭게 생성할 수 있다.

You can now define the various methods for opening and closing the database, as well as the methods for adding/editing/deleting rows in the table (see Listing 3).
이제 데이터베이스를 열고 닫기 위한 다양한 메써드를 정의할 수 있고 테이블 내의 열을 추가/편집/삭제할 수 있는 메써드 또한 정의가 가능하다.

===================================================

public class DBAdapter
{
//...
//...

//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}

//---closes the database---
public void close()
{
DBHelper.close();
}

//---insert a title into the database---
public long insertTitle(String isbn, String title, String publisher)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ISBN, isbn);
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_PUBLISHER, publisher);
return db.insert(DATABASE_TABLE, null, initialValues);
}

//---deletes a particular title---
public boolean deleteTitle(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}

//---retrieves all the titles---
public Cursor getAllTitles()
{
return db.query(DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_ISBN,
KEY_TITLE,
KEY_PUBLISHER},
null,
null,
null,
null,
null);
}

//---retrieves a particular title---
public Cursor getTitle(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_ISBN,
KEY_TITLE,
KEY_PUBLISHER
},
KEY_ROWID + "=" + rowId,
null,
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}

//---updates a title---
public boolean updateTitle(long rowId, String isbn,
String title, String publisher)
{
ContentValues args = new ContentValues();
args.put(KEY_ISBN, isbn);
args.put(KEY_TITLE, title);
args.put(KEY_PUBLISHER, publisher);
return db.update(DATABASE_TABLE, args,
KEY_ROWID + "=" + rowId, null) > 0;
}
}

===================================================

Notice that Android uses the Cursor class as a return value for queries. Think of the Cursor as a pointer to the result set from a database query. Using Cursor allows Android to more efficiently manage rows and columns as and when needed. You use a ContentValues object to store key/value pairs. Its put() method allows you to insert keys with values of different data types.
여기서 눈여겨 봐야 할 것은 안드로이드는 커서 클래스를 쿼리에 대한 리턴값으로 사용한다는 것이다. 커서를 데이터베이스 질의에 대한 결과 값이라고 생각하는 것이다. 커서는 안드로이드가 열과 컬럼을 필요로 할때 효율적으로 사용할 수 있도록 도와준다. 또한
ContentValues 오브젝트에 키/값의 짝으로 데이터를 저장할 수 있다. 해당 오브젝트에서 put() 메써드를 사용해서 키와 다른 데이터 타입의 값을 삽입할 수 있다.

The full source listing of DBAdapter.java is shown in Listing 4.
DBAdapter.java 의 풀 소스를 리스트4에서 볼 수 있다.


=============================================
package net.learn2develop.Database;

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.SQLiteOpenHelper;
import android.util.Log;

public class DBAdapter
{
public static final String KEY_ROWID = "_id";
public static final String KEY_ISBN = "isbn";
public static final String KEY_TITLE = "title";
public static final String KEY_PUBLISHER = "publisher";
private static final String TAG = "DBAdapter";

private static final String DATABASE_NAME = "books";
private static final String DATABASE_TABLE = "titles";
private static final int DATABASE_VERSION = 1;

private static final String DATABASE_CREATE =
"create table titles (_id integer primary key autoincrement, "
+ "isbn text not null, title text not null, "
+ "publisher text not null);";

private final Context context;

private DatabaseHelper DBHelper;
private SQLiteDatabase db;

public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}

private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS titles");
onCreate(db);
}
}

//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}

//---closes the database---
public void close()
{
DBHelper.close();
}

//---insert a title into the database---
public long insertTitle(String isbn, String title, String publisher)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ISBN, isbn);
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_PUBLISHER, publisher);
return db.insert(DATABASE_TABLE, null, initialValues);
}

//---deletes a particular title---
public boolean deleteTitle(long rowId)
{
return db.delete(DATABASE_TABLE, KEY_ROWID +
"=" + rowId, null) > 0;
}

//---retrieves all the titles---
public Cursor getAllTitles()
{
return db.query(DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_ISBN,
KEY_TITLE,
KEY_PUBLISHER},
null,
null,
null,
null,
null);
}

//---retrieves a particular title---
public Cursor getTitle(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID,
KEY_ISBN,
KEY_TITLE,
KEY_PUBLISHER
},
KEY_ROWID + "=" + rowId,
null,
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}

//---updates a title---
public boolean updateTitle(long rowId, String isbn,
String title, String publisher)
{
ContentValues args = new ContentValues();
args.put(KEY_ISBN, isbn);
args.put(KEY_TITLE, title);
args.put(KEY_PUBLISHER, publisher);
return db.update(DATABASE_TABLE, args,
KEY_ROWID + "=" + rowId, null) > 0;
}
}
=============================================

Using the Database
데이터베이스 사용하기

You are now ready to use the database along with the helper class you've created. In the DatabaseActivity.java file, create an instance of the DBAdapter class:
이제 직접 작성한 helper 클래스를 따라서 데이터베이스를 사용할 준비가 되었다.
DatabaseActivity.java 파일에서 DBAdapter 클래스의 인스턴스를 생성해 보자

=====================================================
package net.learn2develop.Database;

import android.app.Activity;
import android.os.Bundle;

public class DatabaseActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DBAdapter db = new DBAdapter(this);
}
}
=====================================================

Adding a Title
타이틀 추가하기

To add a title into the titles table, use the insertTitle() method of the DBAdapter class:
타이틀 테이블에 타이틀을 추가하기 위해서는(새로운 열을 추가하기 위해서는)
DBAdapter의 insertTitle() 메써드를 사용한다.

=====================================================
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

DBAdapter db = new DBAdapter(this);

//---add 2 titles---
db.open();
long id;
id = db.insertTitle(
"0470285818",
"C# 2008 Programmer's Reference",
"Wrox");
id = db.insertTitle(
"047017661X",
"Professional Windows Vista Gadgets Programming",
"Wrox");
db.close();
}
=====================================================

The insertTitle() method returns the ID of the inserted row. If an error occurs during the adding, it returns -1.
If you examine the file system of the Android device/emulator, you can observe that the books database is created under the databases folder (see Figure 3).
insertTitle() 메써드는 추가된 열의 ID를 리턴한다. 만약 추가 중에 에러가 발생한다면 -1을 리턴하게 된다.
만약 안드로이드 디바이스/에뮬레이터를 사용하는 경우 데이터베이스 폴더 아래에 books 데이터베이스가 제대로 생성되어 있는지 확인이 필요하다.


Figure 3. The Database Folder: The books database is created in the databases folder.
Figure 3. 데이터베이스 폴더: books 데이터베이스는 데이터베이스 폴더에 위치하고 있다.

Retrieving All the Titles
모든 테이블 가져오기

To retrieve all the titles in the titles table, use the DBAdapter class' getAllTitles() method (see Listing 5).
The result is returned as a Cursor object. To display all the titles, you first need to call the Cursor object's moveToFirst() method. If it succeeds (which means there is at least one row available), display the details of the title using the DisplayTitle() method (defined below). To move to the next title, call the Cursor object's moveToNext() method:
타이틀 테이블의 모든 타이틀을 가져오기 위해서는
DBAdapter 의 getAllTitles() 메써드를 사용해야한다.(리스트 5 참조) 결과는 커서 객체로 리턴된다. 모든 타이틀을 보여주기 위해서는 반드시 커서 객체의 moveToFirst() 메써드를 호출해야 한다. 만약 성공한다면 (이 말은 적어도 한 개 이상의 열이 존재한다는 말이다) DisplayTitle() 메써드를 사용해서 타이틀의 세부를 보여준다. 다음 타이틀로 이동하기 위해서는 moveToNext()를 호출해서 사용한다.

=====================================================
public void DisplayTitle(Cursor c)
{
Toast.makeText(this,
"id: " + c.getString(0) + "\n" +
"ISBN: " + c.getString(1) + "\n" +
"TITLE: " + c.getString(2) + "\n" +
"PUBLISHER: " + c.getString(3),
Toast.LENGTH_LONG).show();
}
=====================================================


Figure 4 shows the Toast class displaying one of the titles retrieved from the database.
FIgure 4는 Toast 클래스가 데이터베이스로 부터 가져온 하나의 타이틀을 가져와 보여주고 있다.

Retrieving a Single Title
하나의 타이틀 가져와서 보여주기

To retrieve a single title using its ID, call the getTitle() method of the DBAdapter class with the ID of the title:
ID를 사용해서 하나의 타이틀을 가져오려면
DBAdapter 클래스에서 타이틀의 ID를 사용해서 getTitle() 메써드를 호출한다.

=====================================================
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DBAdapter db = new DBAdapter(this);

//---get a title---
db.open();
Cursor c = db.getTitle(2);
if (c.moveToFirst())
DisplayTitle(c);
else
Toast.makeText(this, "No title found",
Toast.LENGTH_LONG).show();
db.close();
}
=====================================================

The result is returned as a Cursor object. If a row is returned, display the details of the title using the DisplayTitle() method, else display an error message using the Toast class.
결과는 커서 객체로 리턴된다. 만약 결과가 리턴된다면
DisplayTitle() 메써드를 사용해서 타이틀의 상세를 표시하고 그렇지 않으면 토스트 클래스를 사용해서 에러를 표시한다.


Updating a Title
타이틀 업데이트하기

To update a particular title, call DBAdapter's updateTitle() method by passing the ID of the title you want to update as well as the values of the new fields (Listing 6).
특정한 타이틀을 업데이트하기 위해서는
DBAdapter 클래스의 updateTitle() 메써드를 타이틀의 ID와 업데이트 하기위한 값을 파라미터로 호출한다.

A message is displayed to indicate if the update is successful. At the same time, you retrieve the title that you have just updated to verify that the update is indeed correct.
만약 업데이트가 성공하였으면 메시지가 표시되고 동시에 방금 업데이트 된 값을 가져와서 제대로 반영 되었음을 보여준다.

Deleting a Title
타이틀의 삭제

To delete a title, use the deleteTitle() method in the DBAdapter class by passing the ID of the title you want to delete:
타이틀을 삭제하기 위해서
DBAdapter 클래스에서 deleteTitle() 메써드를 지우고자 하는 ID를 파라미터로 호출한다.

=====================================================
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DBAdapter db = new DBAdapter(this);

//---delete a title---
db.open();
if (db.deleteTitle(1))
Toast.makeText(this, "Delete successful.",
Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Delete failed.",
Toast.LENGTH_LONG).show();
db.close();
}
=====================================================
A message is displayed to indicate if the deletion is successful.
만약 삭제가 성공했다면 성공을 알리는 메시지가 표시된다.

Upgrading the Database
데이터베이스 업그레이드

To upgrade the database, change the DATABASE_VERSION constant in the DBAdapter class to a value higher than the previous one. For example, if its previous value was 1, change it to 2:
데이터베이스를 업그레이드하기 위해서
DBAdapter 클래스의 DATABASE_VERSION 상수를 과거버전보다 높은 숫자로 변경한다.예를들면 지난 값이 1이었다면 2로 변경한다.


Figure 5. The LogCat Window: The message shows that the database has been upgraded.
Figure 5. 로크 캣 윈도 : 데이터베이스가 업그레이드 되어음을 보여주는 메시지

=====================================================
public class DBAdapter
{
public static final String KEY_ROWID = "_id";
public static final String KEY_ISBN = "isbn";
public static final String KEY_TITLE = "title";
public static final String KEY_PUBLISHER = "publisher";
private static final String TAG = "DBAdapter";

private static final String DATABASE_NAME = "books";
private static final String DATABASE_TABLE = "titles";

//---change this to a higher value---
private static final int DATABASE_VERSION = 2;

private static final String DATABASE_CREATE =
"create table titles (_id integer primary key autoincrement, "
+ "isbn text not null, title text not null, "
+ "publisher text not null);";
=====================================================

When you run the application one more time, you will see the message in Eclipse's LogCat window (see Figure 5) indicating that the database has been upgraded.
애플리케이션을 1회이상 실행할때 이클립스의 로그캣 윈도에서 데이터베이스가 업그레이드 되었음을 알리는 메시지를 볼수 있을 것이다.

Easy Database Access
손 쉬운 데이터베이스 접근

Using the DBAdapter class pattern defined in this article, you can easily access database records for your own Android applications. One important thing to note is that all SQLite databases created in Android are visible only to the application that created it. If you need to share common data, you need to use a content provider, a topic that will be covered in a future article.
DBAdapter 클래스를 사용하는 패턴이 이 글에서 정의 되었다. 이제 개발하고있는 안드로이드 애플리케이션에서 데이터베이스 접근이 용이해 졌을 것이다. 한가지 더 중요한 것은 안드로이드 안에서 SQLite 데이터베이스는 오로지 데이터베이스를생성한 애플리케이션에게만 보여진다. 만약 공유하고자 하는 데이터가 있다면 Content Provider를 사용해야한다. 이에 대한 내용은 다음글에서 다뤄질 예정이다.

Wei-Meng Lee is a Microsoft MVP and founder of Developer Learning Solutions, a technology company specializing in hands-on training on the latest Microsoft technologies. He is an established developer and trainer specializing in .NET and wireless technologies. Wei-Meng speaks regularly at international conferences and has authored and coauthored numerous books on .NET, XML, and wireless technologies. He writes extensively on topics ranging from .NET to Mac OS X. He is also the author of the .NET Compact Framework Pocket Guide, ASP.NET 2.0: A Developer's Notebook (both from O'Reilly Media, Inc.), and Programming Sudoku (Apress). Here is Wei-Meng's blog.