0. 출처

https://www.edwith.org/boostcourse-android/lecture/17121/


1. 실행 결과 화면

  



2. MainActivity.java

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package com.tistory.qlyh8.practice;
 
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
 
/*
* SQLite 는 오픈소스로, 데이터베이스가 앱에서 하나의 파일로 생성되는 파일 기반의 데이터베이스이다.
* 용량이 적고 가볍게 동작하면서도 관계형 데이터베이스를 위한 SQL 실행이 가능하다.
* PC 에서도 사용할 수 있고, 화면에서 테이블 구조나 데이터를 확인할 수 있는 도구들이 제공된다.
* */
public class MainActivity extends AppCompatActivity {
    EditText editText1, editText2, editText3, editText4, editText5;
    TextView textView;
    SQLiteDatabase database;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        editText1 = findViewById(R.id.edit_text1);
        editText2 = findViewById(R.id.edit_text2);
        editText3 = findViewById(R.id.edit_text3);
        editText4 = findViewById(R.id.edit_text4);
        editText5 = findViewById(R.id.edit_text5);
        textView = findViewById(R.id.text_view);
 
        findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.append("DB OPEN 버튼 클릭함\n");
                String dbName = editText1.getText().toString().trim();
                // openOrCreateDatabase 메소드를 사용하여 데이터베이스를 만들거나 연다.
                // SQLiteDatabase 객체가 반환되며 이 객체를 통해 SQL 을 실행할 수 있다.
                /*database = openOrCreateDatabase(dbName, MODE_PRIVATE, null);
                if(database != null)
                    textView.append("DB 오픈됨\n");*/
                DBHelper helper = new DBHelper(getApplicationContext(), dbName, null3);
                database = helper.getWritableDatabase();
            }
        });
 
        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { ... }
        });
 
        findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { ... }
        });
 
        findViewById(R.id.button4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { ...  }
        });
    }
 
    // 헬퍼 클래스는 데이터베이스 버전을 지정하여 데이터베이스를 업그레이드할 때 알 수 있도록 한다.
    // 또한 현재 단말에 설치된 앱의 테이블이 새로 만들어지는지 아니면 업그레이드되어야 하는지를 알려준다.
    class DBHelper extends SQLiteOpenHelper {
 
        public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }
 
        // 새로 데이터베이스가 만들어지는 경우에 호출되므로 데이터베이스를 초기화(생성) 하는 SQL 를 넣는다.
        @Override
        public void onCreate(SQLiteDatabase db) {
            textView.append("onCreate() 호출됨\n");
            String tableName = editText2.getText().toString().trim();
            String sql = "CREATE TABLE IF NOT EXISTS " + tableName
                    + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phone TEXT)";
 
            try { db.execSQL(sql); } catch(Exception e) {e.printStackTrace();}
            textView.append("테이블 생성됨\n");
        }
 
        // 업그레이드가 필요한 경우나 테이블이 변경되어야 하는 등
        // 단말에 저장된 데이터베이스의 구조가 바뀌어야 하는 경우에 사용
        // 테이블을 변경하기 위한 ALTER 문 등을 넣을 수 있으며
        // 이미 저장되어 있는 데이터를 다른 곳에 복사했다가 새로 테이블을 만들고
        // 그 테이블에 넣어주는 방식으로 처리하기도 한다.
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            textView.append("onUpgrade() 호출됨\nold:" + oldVersion + ", new:" + newVersion + "\n");
            if(newVersion > 1){
                String tableName = editText2.getText().toString().trim();
                db.execSQL("DROP TABLE IF EXISTS "+ tableName);
                textView.append("테이블 삭제됨\n");
 
                String sql = "CREATE TABLE IF NOT EXISTS " + tableName
                        + "(_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phone TEXT)";
                db.execSQL(sql);
                textView.append("테이블 생성됨\n");
            }
        }
    }
}
cs



3. 참고

- 콘텐츠 제공자 생성

https://developer.android.com/guide/topics/providers/content-provider-creating?hl=ko


- 안드로이드 앱 런칭 후 데이터베이스 변경 시 주의할 점

http://gyjmobile.tistory.com/entry/%EC%95%88%EB%93%9C%EB%A1%9C%EC%9D%B4%EB%93%9C-%EC%95%B1-%EB%9F%B0%EC%B9%AD%ED%9B%84-%EB%8D%B0%EC%9D%B4%ED%84%B0%EB%B2%A0%EC%9D%B4%EC%8A%A4-%EB%B3%80%EA%B2%BD%EC%8B%9C-%EC%A3%BC%EC%9D%98%ED%95%A0%EC%A0%90

+ Recent posts