< 참고 링크 >
데이터베이스에 있는 테이블들을 리사이클러뷰에 나타내봅시다.
다음 코드를 MainFragment 클래스 안에 작성해줍니다.
테이블에 있는 데이터를 가져오는 selet sql
문을 이용해 String
에 저장 후 이전에 만든 rawQuery
를 이용한 커서를 활용하여 for문 안에서 하나하나 불러와 저장합니다.
for문이 끝난 뒤 어댑터에 바뀐 것들을 적용하여 완성합니다.
Context context; @SuppressLint("Range") public int loadNoteListData() { String loadSql = "select _id, TODO from " + NoteDatabase.TABLE_NOTE + " order by _id desc"; int recordCount = -1; NoteDatabase database = NoteDatabase.getInstance(context); if(database != null) { Cursor outCursor = database.rawQuery(loadSql); recordCount = outCursor.getCount(); ArrayList<Note> items = new ArrayList<>(); for(int i=0; i<recordCount; i++){ outCursor.moveToNext(); int _id = outCursor.getInt(0); String todo = outCursor.getString(1); items.add(new Note(_id, todo)); } outCursor.close(); adapter.setItems(items); adapter.notifyDataSetChanged(); } return recordCount;
그 후 onCreateView
안에 initUI(rootView);
아래에 loadNoteListData();
를 적고
에뮬레이터를 실행시키면
위와 같이 리스트들이 에뮬레이터에서 보여지게됩니다.
에뮬레이터를 보면 앱을 껐다 켜야지만 리스트값들이 수정됩니다.
그래서 새로고침을 이용하여 리스트아이템을 빠르게 적용해보겠습니다.
우선 /Gradle Scripts/build.gradle(:app)에 아래 코드를 작성해줍니다.
dependencies {
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
}
app/res/layout/fragment_main.xml의 코드를 수정해줍니다.
기본 LinearLayout
에만 감싸져있던 recyclerview
를 swipeRefreshLayout
으로 한 번 더 감싸줍니다.
<?xml version="1.0" encoding="utf-8"?> <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"> <androidx.swiperefreshlayout.widget.SwipeRefreshLayout android:id="@+id/refresh_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recylcerView" android:layout_width="match_parent" android:layout_height="wrap_content" tools:layout_editor_absoluteX="1dp" tools:layout_editor_absoluteY="1dp" /> </androidx.swiperefreshlayout.widget.SwipeRefreshLayout> </LinearLayout>
위 작업을 완료한 뒤 MainFragment 클래스가 이 레이아웃을 사용합니다.
클래스 내에서 SwipeRefreshLayout
변수를 정의해주고 다음 코드를 onCreateView
안에 loadNoteListData();
아래 작성합니다.
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.refresh_layout); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { loadNoteListData(); swipeRefreshLayout.setRefreshing(false); } });
를 작성하여 아래 사진과 같게 만들어줍니다.
그럼 이제 리사이클러뷰를 아래로 스와이프하여 새로고침 할 시 리스트 목록들이 바로바로 수정됩니다.
끝.