SQLite1.zip


0. Result






1. Create the Contract


1-1. Create an inner class called WaitlistEntry that implements BaseColumns.

1-2. Declare a constant String for the table name.

1-3. Declare constant Strings for each of the table columns.


data/WaitlistContract.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

package com.tistory.qlyh8.sqlite.data;
 
/*
 * Created by YUNHEE on 2018-01-06.
 */
 
import android.provider.BaseColumns;
 
// 데이터베이스 구성 Contract
public class WaitlistContract {
 
    // BaseColumns 인터페이스는 자동적으로 _ID 라는 고유 기본키를 생성
    public static final class WaitlistEntry implements BaseColumns {
        public static final String TABLE_NAME = "waitlist";
        public static final String COLUMN_GUEST_NAME = "guestName";
        public static final String COLUMN_PARTY_SIZE = "partySize";
        public static final String COLUMN_TIMESTAMP = "timestamp";
    }
}
 
cs





2. Create the Database


2-1. Modify WaitlistDbHelper to extend SQLiteOpenHelper.

2-2. Declare members for database name and version number.

2-3. Implement a constructor that takes a context object.

2-4. Implement onCreate by executing a create SQL statement.

2-5. Implement onUpgrade by dropping the DB and recreating it. 


data/WaitlistDbHelper.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
package com.tistory.qlyh8.sqlite.data;
 
/*
 * Created by YUNHEE on 2018-01-06.
 */
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
 
import com.tistory.qlyh8.sqlite.data.WaitlistContract.*;
 
/*
 * 실제 DB 생성을 위해선 DB Helper 라는 클래스가 필요하다.
 * DB Helper 는 DB의 레퍼런스를 통해 생성되며 쿼리를 통해 DB를 접근하게 해준다.
 * DB Helper 를 생성하기 위해서 SQLiterOpenHelper 를 상속 받는다.
 * SQLiterOpenHelper 는 DB를 처음 생성할 때와 DB의 스키마를 변경할 때 도움을 준다.
 * SQLiterOpenHelper 는 onCreate 와 onUpgrade 메서드를 제공한다.
* */
public class WaitlistDbHelper extends SQLiteOpenHelper {
 
    private static final String DATABASE_NAME = "waitlist.db";
    private static final int DATABASE_VERSION = 1;
 
    public WaitlistDbHelper(Context context) {
        super(context,  DATABASE_NAME, null, DATABASE_VERSION);
    }
 
    // 실제 DB가 생성된다.
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        final String SQL_CREATE_WAITLIST_TABLE = "CREATE TABLE " + WaitlistEntry.TABLE_NAME + " (" +
                WaitlistEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                WaitlistEntry.COLUMN_GUEST_NAME + " TEXT NOT NULL, " +
                WaitlistEntry.COLUMN_PARTY_SIZE + " INTEGER NOT NULL, " +
                WaitlistEntry.COLUMN_TIMESTAMP + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP" +
                "); ";
 
        // 쿼리 실행
        sqLiteDatabase.execSQL(SQL_CREATE_WAITLIST_TABLE);
    }
 
    // DB 스키마가 최근 것을 반영하게 해준다.
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        // 버전이 바뀌면 예전 버전의 테이블을 삭제 (나중에 ALTER 문으로 대체)
        sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + WaitlistEntry.TABLE_NAME);
        onCreate(sqLiteDatabase);
    }
}
 
cs





3. Get All the Data


3-1. Create getAllGuests method that returns a cursor.

3-2. Call it onCreate and pass the cursor count to the adapter.


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
package com.tistory.qlyh8.sqlite;
 
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
 
import com.tistory.qlyh8.sqlite.data.TestUtil;
import com.tistory.qlyh8.sqlite.data.WaitlistContract;
import com.tistory.qlyh8.sqlite.data.WaitlistDbHelper;
 
public class MainActivity extends AppCompatActivity {
 
    private GuestListAdapter mAdapter;
    RecyclerView waitlistRecyclerView;
    // SQL DB의 레퍼런스
    private SQLiteDatabase mDb;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        waitlistRecyclerView = this.findViewById(R.id.all_guests_list_view);
        // 리사이클러뷰를 리니어 레이아웃으로 설정
        waitlistRecyclerView.setLayoutManager(new LinearLayoutManager(this));
 
        WaitlistDbHelper dbHelper = new WaitlistDbHelper(this);
        // 데이터를 DB에 채우기 위함
        mDb = dbHelper.getWritableDatabase();
        // 자동적으로 다섯명의 손님을 DB에 추가
        TestUtil.insertFakeData(mDb);
        //커서에 결과를 저장
        Cursor cursor = getAllGuests();
 
        // 데이터를 표시할 커서를 위한 어댑터 생성
        mAdapter = new GuestListAdapter(thiscursor.getCount());
        // 리사이클러뷰에 어댑터를 연결
        waitlistRecyclerView.setAdapter(mAdapter);
    }
 
    // 등록하기 버튼을 눌렀을 때 불리는 메서드
    public void addToWaitlist(View view) {}
 
    /*
    * Cursor 는 SQL 쿼리의 결과물이 저장되어 있는 것이다.
    * 반복문으로 쉽게 확인할 수 있다.
    * */
    // 손님의 목록을 보여주기 위해 시간 순서대로 결과를 보여준다.
    private Cursor getAllGuests() {
        // 두번째 파라미터 (Projection array)는 여러 열들 중에서 출력하고 싶은 것만 선택해서 출력할 수 있게 한다.
        // 모든 열을 출력하고 싶을 때는 null 을 입력한다.
        return mDb.query(
                WaitlistContract.WaitlistEntry.TABLE_NAME,
                null,
                null,
                null,
                null,
                null,
                WaitlistContract.WaitlistEntry.COLUMN_TIMESTAMP
        );
    }
}
 
cs





Android Course of Udacity - Lesson 7

+ Recent posts