0. Result
1. Update the Adapter
1-1. Update the adapter to take an entire cursor rather than just the count.
1-2. Bind the cursor data with the view in onBindViewHolder.
1-3. Update MainActivity to pass in the cursor from getAllGuests.
GuestListAdapter.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 | package com.tistory.qlyh8.sqlite; /* * Created by YUNHEE on 2018-01-06. */ import android.content.Context; import android.database.Cursor; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.tistory.qlyh8.sqlite.data.WaitlistContract; public class GuestListAdapter extends RecyclerView.Adapter<GuestListAdapter.GuestViewHolder>{ private Context mContext; private Cursor mCursor; public GuestListAdapter(Context context, Cursor cursor) { this.mContext = context; mCursor = cursor; } @Override public GuestViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {...} // 포지션을 입력 받아서 해당 데이터를 UI에 출력 @Override public void onBindViewHolder(GuestViewHolder holder, int position) { // 해당 포지션으로 이동한다. // false 가 리턴되면 데이터가 없거나 혹은 범위를 초과했다는 뜻이다. if(!mCursor.moveToPosition(position)) return; // 열의 이름으로 열의 번호를 넘겨줌 String name = mCursor.getString(mCursor.getColumnIndex(WaitlistContract.WaitlistEntry.COLUMN_GUEST_NAME)); int partySize = mCursor.getInt(mCursor.getColumnIndex(WaitlistContract.WaitlistEntry.COLUMN_PARTY_SIZE)); holder.nameTextView.setText(name); holder.partySizeTextView.setText(String.valueOf(partySize)); } @Override public int getItemCount() { return mCursor.getCount(); } // 리사이클러뷰 내에서 단일의 아이템을 표시하는데 필요한 뷰를 보관 및 유지하는 내부 클래스 class GuestViewHolder extends RecyclerView.ViewHolder {...} } | cs |
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 | 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(this, cursor); // 리사이클러뷰에 어댑터를 연결 waitlistRecyclerView.setAdapter(mAdapter); } // 등록하기 버튼을 눌렀을 때 불리는 메서드 public void addToWaitlist(View view) {} /* * Cursor 는 SQL 쿼리의 결과물이 저장되어 있는 것이다. * 반복문으로 쉽게 확인할 수 있다. * */ // 손님의 목록을 보여주기 위해 시간 순서대로 결과를 보여준다. private Cursor getAllGuests() {...} } | cs |
2. Add Data
2-1. Use findViewById to get the EditTextView.
2-2. Remove the fake data call in onCreate.
2-3. Create addNewGuest to insert into the DB.
2-4. Implement addToWaitlist to read the text and call addNewGuest.
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 | package com.tistory.qlyh8.sqlite; import android.content.ContentValues; 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.util.Log; import android.view.View; import android.widget.EditText; 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; private EditText mNewGuestNameEditText; private EditText mNewPartySizeEditText; private final static String LOG_TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); waitlistRecyclerView = this.findViewById(R.id.all_guests_list_view); mNewGuestNameEditText = this.findViewById(R.id.person_name_edit_text); mNewPartySizeEditText = this.findViewById(R.id.party_count_edit_text); // 리사이클러뷰를 리니어 레이아웃으로 설정 waitlistRecyclerView.setLayoutManager(new LinearLayoutManager(this)); WaitlistDbHelper dbHelper = new WaitlistDbHelper(this); // 데이터를 DB에 채우기 위함 mDb = dbHelper.getWritableDatabase(); //커서에 결과를 저장 Cursor cursor = getAllGuests(); // 데이터를 표시할 커서를 위한 어댑터 생성 mAdapter = new GuestListAdapter(this, cursor); // 리사이클러뷰에 어댑터를 연결 waitlistRecyclerView.setAdapter(mAdapter); } // 등록하기 버튼을 눌렀을 때 불리는 메서드 public void addToWaitlist(View view) { if (mNewGuestNameEditText.getText().length() == 0 || mNewPartySizeEditText.getText().length() == 0) { return; } // 초기화 int partySize = 1; // 예기치 않은 에러 처리 try { partySize = Integer.parseInt(mNewPartySizeEditText.getText().toString()); } catch (NumberFormatException ex) { Log.e(LOG_TAG, "Failed to parse party size text to number: " + ex.getMessage()); } // DB에 데이터 추가 addNewGuest(mNewGuestNameEditText.getText().toString(), partySize); } /* * Cursor 는 SQL 쿼리의 결과물이 저장되어 있는 것이다. * 반복문으로 쉽게 확인할 수 있다. * */ // 손님의 목록을 보여주기 위해 시간 순서대로 결과를 보여준다. private Cursor getAllGuests() {...} // 새 데이터를 추가하는 메서드로, 추가되는 레코드의 아이디를 리턴한다. private long addNewGuest(String name, int partySize) { // DB에 데이터를 추가를 하기 위해선 ContentValue 객체를 사용해야 한다. ContentValues cv = new ContentValues(); /* * 열의 이름을 키로 해서 해당 값을 가리킨다. * 값들을 put 메서드를 사용해 입력한다. * 첫번째 파라미터는 열의 이름으로, Contract 로부터 가져올 수 있다. * 두번째 파라미터는 값이다. */ cv.put(WaitlistContract.WaitlistEntry.COLUMN_GUEST_NAME, name); cv.put(WaitlistContract.WaitlistEntry.COLUMN_PARTY_SIZE, partySize); // cv에 저장된 값을 사용하여 새로운 행을 추가한다. return mDb.insert(WaitlistContract.WaitlistEntry.TABLE_NAME, null, cv); } } | cs |
3. Reflect the added data in RecyclerView
3-1. Create a new function called swapCursor.
3-2. Update the cursor in the adapter to trigger UI.
GuestListAdapter.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 | package com.tistory.qlyh8.sqlite; /* * Created by YUNHEE on 2018-01-06. */ import android.content.Context; import android.database.Cursor; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.tistory.qlyh8.sqlite.data.WaitlistContract; public class GuestListAdapter extends RecyclerView.Adapter<GuestListAdapter.GuestViewHolder>{ private Context mContext; private Cursor mCursor; public GuestListAdapter(Context context, Cursor cursor) {...} @Override public GuestViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {...} // 포지션을 입력 받아서 해당 데이터를 UI에 출력 @Override public void onBindViewHolder(GuestViewHolder holder, int position) {...} @Override public int getItemCount() {...} // 어댑터에 현재 보관되고 있는 커서를 새로운 것으로 바꿔 UI를 갱신한다. public void swapCursor(Cursor newCursor) { // 항상 이전 커서를 닫는다. if (mCursor != null) mCursor.close(); // 새 커서로 업데이트 mCursor = newCursor; // 리사이클러뷰 업데이트 if (newCursor != null) { this.notifyDataSetChanged(); } } // 리사이클러뷰 내에서 단일의 아이템을 표시하는데 필요한 뷰를 보관 및 유지하는 내부 클래스 class GuestViewHolder extends RecyclerView.ViewHolder {...} } | cs |
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 | package com.tistory.qlyh8.sqlite; import android.content.ContentValues; 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.util.Log; import android.view.View; import android.widget.EditText; 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; private EditText mNewGuestNameEditText; private EditText mNewPartySizeEditText; private final static String LOG_TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) {...} // 등록하기 버튼을 눌렀을 때 불리는 메서드 public void addToWaitlist(View view) { if (mNewGuestNameEditText.getText().length() == 0 || mNewPartySizeEditText.getText().length() == 0) { return; } int partySize = 1; // 예기치 않은 에러 처리 try { partySize = Integer.parseInt(mNewPartySizeEditText.getText().toString()); } catch (NumberFormatException ex) { Log.e(LOG_TAG, "Failed to parse party size text to number: " + ex.getMessage()); } // DB에 데이터 추가 addNewGuest(mNewGuestNameEditText.getText().toString(), partySize); // 어댑터에서 커서를 업데이트하여 UI를 트리거하여 새 목록을 표시한다. mAdapter.swapCursor(getAllGuests()); // UI 텍스트 필드를 지운다. mNewPartySizeEditText.clearFocus(); mNewGuestNameEditText.getText().clear(); mNewPartySizeEditText.getText().clear(); } /* * Cursor 는 SQL 쿼리의 결과물이 저장되어 있는 것이다. * 반복문으로 쉽게 확인할 수 있다. * */ // 손님의 목록을 보여주기 위해 시간 순서대로 결과를 보여준다. private Cursor getAllGuests() {...} // 새 데이터를 추가하는 메서드로, 추가되는 레코드의 아이디를 리턴한다. private long addNewGuest(String name, int partySize) {...} } | cs |
Android Course of Udacity - Lesson 7
'Android' 카테고리의 다른 글
Content Provider - (1) 개념 (0) | 2018.01.08 |
---|---|
SQLite - (3) 데이터 삭제하기 (0) | 2018.01.06 |
SQLite - (1) DB 생성 및 데이터 가져오기 (0) | 2018.01.06 |
Preferences - (6) EditText Preference (0) | 2018.01.04 |
Preferences - (5) List Preference (0) | 2018.01.04 |