본문 바로가기

플밍 is 뭔들/안드로이드_인강

16-1. 데이터 베이스

※ SQLite
 - 안드로이드에서는 SQLite라는 경량급의 DB를 사용한다. 작은 디바이스에 최적회된 RDB로 기본적으로 안드로이드 프레임워크에 포함되어
   있기 때문에 별도의 설치없이 사용할 수 있다.
 - 데이터베이스를 사용할 때 DDMS에서는 에뮬레이터의 데이터만 볼 수 있다. 왜냐하면 핸드폰의 데이터베이스를 쉽게 읽을 수 있는것은 문제가 될 수 있기 때문이다.

※ SQLite 사용법
 - SQLiteOpenHelper 를 상속받아 Helper클래스를 만들면 DB를 이용할 수 있다.
 - 상속받은 Helper클래스에선 Context, DB이름, 버전을 입력 받는다.
 - 상속받은 Helper클래스에서의 핵심 메소드 
  1. onCreate -> DB가 처음 생성 될 때 최초 한번만 실행 된다. 테이블 생성에 주로 이용.
  2. onUpgrade -> DB버전이 변경되었을때 실행 된다.

※ 데이터베이스 값 확인하는법 (에뮬레이터 기준)
  1. DDMS 들어가기
  2. /data/data/해당패키지/databases 폴더에서 확인한다. 
  3. 오른쪽 위에 초록색 + 버튼 옆 pull 버튼을 이용하면 내 PC로 가져올 수 있다. 
  4. http://sqlitebrowser.org/ 여기에서 운영체제에 맞는 시스템을 다운받아 설치하고 실행한다.
  5. 시스템에서 pull한 파일을 가져온다.

※ 소스

MainActivity
public class MainActivity extends Activity {
       
       Button btnInsert, btnDelete, btnUpdate, btnSelect;
       TextView tvResult;
       MemberInfoHelper memberInfoHelper;
       
       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
       
              memberInfoHelper = new MemberInfoHelper(this);
              
              btnInsert = (Button) findViewById(R.id.btn_insert);
              btnDelete = (Button) findViewById(R.id.btn_delete);
              btnUpdate = (Button) findViewById(R.id.btn_update);
              btnSelect = (Button) findViewById(R.id.btn_select);
              tvResult = (TextView) findViewById(R.id.tv_result);
              
              btnInsert.setOnClickListener(listener);
              btnDelete.setOnClickListener(listener);
              btnUpdate.setOnClickListener(listener);
              btnSelect.setOnClickListener(listener);
              
       }
       
       OnClickListener listener = new OnClickListener() {
              
              SQLiteDatabase db;
              ContentValues values;
              
              @Override
              public void onClick(View v) {
                     // TODO Auto-generated method stub
                     switch (v.getId()) {
                     case R.id.btn_insert:
                           try {
                                  
                                  //방법1
                                  //Write할 데이터베이스 연결
                                  db=memberInfoHelper.getWritableDatabase();
                                  values = new ContentValues();
                                  values.put("uname", "홍길동");
                                  values.put("uid", "abc");
                                  values.put("upw",123);
                                  db.insert("member", null, values);
                                  
                                  //방법2, 추천
                                  String query = "INSERT INTO member (_id, uname, uid, upw) VALUES (NULL, '홍길순', 'def', 321);";
                                  db.execSQL(query);
                                  
                                  memberInfoHelper.close();
                                  Toast.makeText(MainActivity.this, "insert success", Toast.LENGTH_SHORT).show();
                                  
                           } catch (Exception e) {
                                  // TODO: handle exception
                                  e.printStackTrace();
                                  Toast.makeText(MainActivity.this, "Insert Fail", Toast.LENGTH_SHORT).show();
                           }
                           break;
                     case R.id.btn_delete :
                           try {
                                  
                                  db = memberInfoHelper.getWritableDatabase();
                                  
                                  //db.delete("member", null,null);
                                  
                                  String query = "DELETE FROM member WHERE uid = 'abc'";
                                  db.execSQL(query);
                                  
                                  memberInfoHelper.close();
                                  Toast.makeText(MainActivity.this, "Delete success" , Toast.LENGTH_SHORT).show();   
                                  
                           } catch (Exception e) {
                                  // TODO: handle exception
                                  e.printStackTrace();
                                  Toast.makeText(MainActivity.this, "Delete Fail", Toast.LENGTH_SHORT).show();
                           }
                           break;
                           
                     case R.id.btn_update :
                           try {
                                  
                                  db = memberInfoHelper.getWritableDatabase();
                                  
                                  String query = "UPDATE member SET uname = '김덕배'";
                                  db.execSQL(query);
                                  
                                  memberInfoHelper.close();
                                  Toast.makeText(MainActivity.this, "Update success" , Toast.LENGTH_SHORT).show();   
                                  
                           } catch (Exception e) {
                                  // TODO: handle exception
                                  e.printStackTrace();
                                  Toast.makeText(MainActivity.this, "Update Fail", Toast.LENGTH_SHORT).show();
                           }
                           break;
                     case R.id.btn_select :
                           try {
                                  db = memberInfoHelper.getReadableDatabase();
                                  String query = "SELECT * FROM member;";
                                  Cursor cursor = db.rawQuery(query,null);
                                  
                                  String result="";
                                  while(cursor.moveToNext()){
                                         String uname = cursor.getString(0);
                                         String uid = cursor.getString(1);
                                         int upw = cursor.getInt(2);
                                         
                                         result = result + "uname : " +uname + " uid : " + uid + " upw : " + upw;
                                  }
                                  
                                  tvResult.setText(result);
                                  
                                  cursor.close();
                                  memberInfoHelper.close();
                                  Toast.makeText(MainActivity.this, "Select success" , Toast.LENGTH_SHORT).show();
                                  
                           } catch (Exception e) {
                                  // TODO: handle exception
                                  e.printStackTrace();
                                  Toast.makeText(MainActivity.this, "Select Fail", Toast.LENGTH_SHORT).show();
                           }
                           
                     default:
                           break;
                     }
              }
       };
}

MemberHelper
public class MemberInfoHelper extends SQLiteOpenHelper {
       
       
       public MemberInfoHelper(Context c) {
              super(c, "MemberInfo.db", null, 1);
       }
       @Override
       public void onCreate(SQLiteDatabase db) {
              String query = "CREATE TABLE member (_id INTEGER PRIMARY KEY AUTOINCREMENT, uname TEXT, uid TAXT, upw INTEGER);";
              db.execSQL(query);
       }
       @Override
       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
              String query = "DROP TABLE IF EXITS member";
              db.execSQL(query);
              onCreate(db);
       }
}

activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.androidex.MainActivity" >
   
    <Button
        android:id="@+id/btn_insert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
              android:text ="INSERT"
        />
    
    <Button
        android:id="@+id/btn_delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text= "DELETE"
        />
  
    <Button
        android:id="@+id/btn_update"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="UPDATE"
        />
   
       <Button
        android:id="@+id/btn_select"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SELECT"
        />
      
        <TextView
        android:id="@+id/tv_result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
 
   
  
   
</LinearLayout>

※ CP(Content Provider)
 - 내가 가지고 있는 데이터베이스를 다른 어플리케이션에 공개하는 방법이 있는데 Content Provider라는 객체를 이용한다.
 - 만약 내가 만든 시스템에 ContentProvider를 상속받은 Provider클래스를 하나 생성해주고 거기에 조건을 설정하면 다른 시스템에서도 내가만든 시스템의 데이터베이스에 접근 할 수 있다.
 - Provider클래스를 생성하면 AndroidMenifest에 등록을 해줘야 다른 시스템에서 DB에 접근한다고 신호를 보냈을때 캐치할 수 있다.


'플밍 is 뭔들 > 안드로이드_인강' 카테고리의 다른 글

18-1. 네트워크  (0) 2016.11.28
17-1. 맵  (0) 2016.11.28
15-1. 데이터  (0) 2016.11.28
14-1. 브로드캐스트 리시버  (0) 2016.11.28
13-2. 스레드  (0) 2016.11.28