안드로이드 스튜디오 리스트뷰 데이터베이스 - andeuloideu seutyudio liseuteubyu deiteobeiseu

[안드로이드] SQLite - DB에서 데이터를 가져와 리스트뷰에 출력 ( SimpleCursorAdapter )

안드로이드 스튜디오 리스트뷰 데이터베이스 - andeuloideu seutyudio liseuteubyu deiteobeiseu
안드로이드
안드로이드 스튜디오 리스트뷰 데이터베이스 - andeuloideu seutyudio liseuteubyu deiteobeiseu
 

2013. 1. 19. 17:33

안드로이드 스튜디오 리스트뷰 데이터베이스 - andeuloideu seutyudio liseuteubyu deiteobeiseu
https://blog.naver.com/javaking75/140178110438

첨부파일 (1)

커서 어댑터 (CursorAdapter)

결과물을 한꺼번에 다 읽어 들여 화면에 보여줄 필요 없이 커서 객체와 UI객체를 함께 바인딩하여 화면에 보여주는과정을 어댑터에서 알아서 처리함

SimpleCursorAdapter

바로 사용할 수 있도록 API에 정의 되어 있는 커서 어댑터 클래스

조회하기 버튼을 눌렀을경우 Listview에 데이터(DB에서 가져온) 를 출력하는 핵심코드.

  1. //테이블만들기 버튼

  2. Button button04 = (Button) findViewById(R.id.button04);

  3. button04.setOnClickListener(new OnClickListener() {

  4. public void onClick(View v) {

  5. Cursor cursor = queryData(); ////Cursor객체를 반환받는다.

  6. //queryDataParam();

  7. if(cursor != null){

  8. startManagingCursor(cursor)//액티비티가 커서를 관리

  9. String[] columns = {"_id","name","age"};

  10. int [] resIds = {R.id.text01,R.id.text02,R.id.text03};

  11. //리턴된 커서의 컬럼과 listitem.xml에서 준비된 리소스아이디와 연결(매칭)                   

  12. //public SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to)

  13. SimpleCursorAdapter adapter

    = new SimpleCursorAdapter(getApplicationContext(),R.layout.listitem,cursor, columns,resIds);

  14. list01.setAdapter(adapter)//리스트에 아답터 부착

  15. //_id 필드명 필요 

  16. }//end if               

  17. }           

  18. });     

  19. }

maina_mydatabse.xml

  1.    android:layout_width="fill_parent"

  2.    android:layout_height="fill_parent"

  3.    android:background="#eeeeee"

  4.    android:orientation="vertical" >

  5. <LinearLayout

  6.        android:id="@+id/buttonLayout"

  7.        android:layout_width="wrap_content"

  8.        android:layout_height="wrap_content"

  9.        android:layout_alignParentTop="true"

  10.        android:layout_gravity="center_horizontal"

  11.        android:orientation="horizontal" >

  12. <Button

  13.            android:id="@+id/button01"

  14.            android:layout_width="120dp"

  15.            android:layout_height="wrap_content"

  16.            android:layout_gravity="center_horizontal"

  17.            android:layout_margin="10dp"

  18.            android:text="DB만들기" />

  19. <Button

  20.            android:id="@+id/button04"

  21.            android:layout_width="120dp"

  22.            android:layout_height="wrap_content"

  23.            android:layout_gravity="center_horizontal"

  24.            android:layout_margin="10dp"

  25.            android:text="데이터 조회" />

  26. </LinearLayout>

  27. <ScrollView

  28.        android:id="@+id/scroll01"

  29.        android:layout_width="fill_parent"

  30.        android:layout_height="80dp"

  31.        android:layout_alignParentBottom="true"

  32.        android:background="#ffffff" >

  33. <TextView

  34.            android:id="@+id/text01"

  35.            android:layout_width="fill_parent"

  36.            android:layout_height="fill_parent"

  37.            android:text=""

  38.            android:textColor="#ff000000"

  39.            android:textSize="14dp" />

  40. </ScrollView>

  41. <ListView

  42.        android:id="@+id/list01"

  43.        android:layout_width="fill_parent"

  44.        android:layout_height="fill_parent"

  45.        android:layout_above="@id/scroll01"

  46.        android:layout_below="@id/buttonLayout"

  47.        android:background="#ffffff" >

  48. </ListView>

  49. </RelativeLayout>

listitem.xml  ( 리스트뷰에 보여질 하나의 항목에 대한 레이아웃 정의)

  1.    android:layout_width="fill_parent"

  2.    android:layout_height="wrap_content"

  3.     android:background="#ffeefaee"

  4.    android:orientation="vertical" >

  5. <TextView

  6.        android:id="@+id/text01"

  7.        android:layout_width="fill_parent"

  8.        android:layout_height="wrap_content"

  9.        android:text=""

  10.        android:textColor="#ff000000"

  11.        android:textSize="16dp" />

  12. <TextView

  13.        android:id="@+id/text02"

  14.        android:layout_width="fill_parent"

  15.        android:layout_height="wrap_content"

  16.        android:text=""

  17.        android:textColor="#ff000000"

  18.        android:textSize="16dp" />

  19. <TextView

  20.        android:id="@+id/text03"

  21.        android:layout_width="fill_parent"

  22.        android:layout_height="wrap_content"

  23.        android:text=""

  24.        android:textColor="#ffff8833"

  25.        android:textSize="12dp"

  26.        />

  27. </LinearLayout>

MyDatabaseCursorActivity.java

  1. package com.example.mydatabase.cursor;

  2. import android.app.Activity;

  3. import android.content.Context;

  4. import android.database.Cursor;

  5. import android.database.sqlite.SQLiteDatabase;

  6. import android.database.sqlite.SQLiteDatabase.CursorFactory;

  7. import android.database.sqlite.SQLiteOpenHelper;

  8. import android.os.Bundle;

  9. import android.view.View;

  10. import android.view.View.OnClickListener;

  11. import android.widget.Button;

  12. import android.widget.ListView;

  13. import android.widget.SimpleCursorAdapter;

  14. import android.widget.TextView;

  15. public class MyDatabaseCursorActivity extends Activity {

  16. TextView text01;

  17. SQLiteDatabase database;

  18. String tableName = "CUSTOMER"; 

  19. DatabaseHelper helper;

  20. @Override

  21. protected void onCreate(Bundle savedInstanceState) {

  22. super.onCreate(savedInstanceState);

  23. setContentView(R.layout.maina_mydatabse);

  24. text01 = (TextView) findViewById(R.id.text01);     

  25. list01 = (ListView) findViewById(R.id.list01);

  26. //DB만들기 버튼

  27. Button button01 = (Button) findViewById(R.id.button01);

  28. button01.setOnClickListener(new OnClickListener() {

  29. public void onClick(View v) {

  30. createDatabase();

  31. }

  32. });

  33. //테이블만들기 버튼

  34. Button button04 = (Button) findViewById(R.id.button04);

  35. button04.setOnClickListener(new OnClickListener() {

  36. public void onClick(View v) {

  37. Cursor cursor = queryData();

  38. //queryDataParam();

  39. if(cursor != null){

  40. startManagingCursor(cursor); //액티비티가 커서를 관리

  41. String[] columns = {"_id","name","age"};

  42. int [] resIds = {R.id.text01,R.id.text02,R.id.text03};

  43. //리턴된 커서의 컬럼과 listitem.xml에서 준비된 리소스아이디와 연결(매칭)

  44. //public SimpleCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to)

  45. SimpleCursorAdapter adapter =new SimpleCursorAdapter(getApplicationContext(),R.layout.listitem,cursor, columns,resIds);

  46. list01.setAdapter(adapter); //리스트에 아답터 부착

  47. //_id 필드명 필요 

  48. }//end if               

  49. }           

  50. });     

  51. }

  52. //DB 생성

  53. private void createDatabase(){

  54. String name = "customer.db";

  55. //database = openOrCreateDatabase(name, MODE_WORLD_WRITEABLE, null); //DB가 존재하면 오픈. 존재하지않은면 생성

  56. //int version = 1;

  57. int version = 2; //Helper의 onUpgrade메소드 호출 확인

  58. helper = new DatabaseHelper(this, name, null, version);

  59. database = helper.getWritableDatabase(); //DB에 참조하여 읽거나 쓸수있다.

  60. }

  61. //데이터 조회

  62. private Cursor queryData(){

  63. String sql = "select _id,name,age from "+ tableName + " where age > 20";

  64. Cursor cursor = database.rawQuery(sql, null);

  65. if(cursor != null){

  66. int count = cursor.getCount(); //조회된 개수얻기

  67. text01.append("헬퍼안에서 데이터를 조회했어요. 레코드 갯수: "+count + "\n");

  68. }

  69. return cursor;       

  70. }

  71. private void queryDataParam(){

  72. //String sql = "select _id,name,age from "+ tableName + " where age > 20";

  73. //Cursor cursor = database.rawQuery(sql, null);

  74. //String sql = "select _id,name,age from "+ tableName + " where age > ?";

  75. //String[] args = {"18"};

  76. //Cursor cursor = database.rawQuery(sql, args);

  77. //내부적으로 args배열에 있는 값들이 sql쿼리문에 있는 ?(물음표) 를 대체한다.

  78. //[파라미터를 처리하는 방법]

  79. //String sql = "select id,name,age from "+ tableName + " where age > 20";

  80. String[] columns = {"_id", "name", "age"}; //추출할 필드명

  81. String selection = "age > ?"; //검색 조건

  82. String[] selectionArgs = {"18"};  //?를 대체할 값

  83. //Cursor cursor = database.query(tableName, columns, selection, selectionArgs, groupBy, having, orderBy)

  84. Cursor cursor = database.query(tableName, columns, selection, selectionArgs, null, null, null);

  85. if(cursor != null){

  86. int count = cursor.getCount(); //조회된 개수얻기

  87. text01.append("헬퍼안에서 데이터를 조회했어요. 레코드 갯수: "+count + "\n");

  88. for(int i = 0; i< count ; i++){

  89. cursor.moveToNext();

  90. String name=cursor.getString(0) + "/" +cursor.getString(1) +"/"+ cursor.getString(2);

  91. text01.append("데이터 #"+i+":"+name+"\n");

  92. }

  93. }  

  94. }//queryDataParam

  95. //SQLiteOpenHelper클래스를 상속받은  DatabaseHelper이너 클래스 작성

  96. class DatabaseHelper extends SQLiteOpenHelper{

  97. //생성자

  98. CursorFactory factory, int version) {

  99. super(context, name, factory, version);

  100. }

  101. @Override //추상클래스 구현

  102. public void onCreate(SQLiteDatabase db) {

  103. text01.append("헬퍼를 이용해서 데이터베이스가 만들어졌어요\n");

  104. createTable(db);

  105. insertData(db);

  106. }

  107. @Override //추상클래스 구현

  108. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

  109. text01.append("헬퍼를 이용해서 데이터베이스를 업그레이드 했어요 -> 이전버전 : "+oldVersion+", 현재버전 : "+newVersion+"\n");

  110. //테이블을 변경하고자할때...

  111. }

  112. @Override

  113. public void onOpen(SQLiteDatabase db) {

  114. text01.append("헬퍼를 이용해서 데이터베이스를 오픈했어요.\n");

  115. super.onOpen(db);

  116. }

  117. //테이블 생성

  118. private void createTable(SQLiteDatabase db) {

  119. String sql = "create table " + tableName + "(_id integer,name text, age integer)";

  120. try {

  121. db.execSQL(sql);//slq문 실행

  122. text01.append("헬퍼안에서 테이블이 만들어졌어요"+tableName+"\n");

  123. text01.append("테이블 만들 때 예외 : "+e.getMessage()+"\n");

  124. e.printStackTrace();

  125. }

  126. }

  127. //데이터넣기

  128. private void insertData(SQLiteDatabase db){

  129. db.beginTransaction(); //sql문을 실행하는 일정구간을 트랜잭션으로 묶어주겠다라는 의미

  130. //트랜잭션 시작을 나타내는 메소드

  131. try{

  132. String sql = "insert into "+ tableName + "(_id, name,age) values(200,'장길산',22)";

  133. db.execSQL(sql);

  134. for(int i=0 ; i<5;i++){

  135. sql = "insert into "+ tableName + "(_id, name,age) values("+(300+i)+",'자바킹"+i+"',23)";

  136. db.execSQL(sql);   

  137. }

  138. text01.append("헬퍼안에서 데이터를 넣었어요\n");

  139. db.setTransactionSuccessful(); //트랜잭션으로 묶어준 일정영역의 SQL문들이 모두 성공적으로 끝났을 지정

  140. //SQL문 실행중 오류가 발생하면 예외처리가 되고..

  141. //트랜잭션에 정의된 SQL쿼리가 성공되지 않았기때문에 finally블록에서

  142. //트랜잭션 종료메서드 실행시(endTransaction()) 롤백이 된다.

  143. text01.append("데이터 추가할때 예외 : "+e.getMessage()+"\n");

  144. e.printStackTrace();

  145. }finally{

  146. db.endTransaction(); //트랜잭션을 끝내는 메소드.

  147. }

  148. }//end insertData  

  149. }//end innerClass DatabaseHelper

  150. }//end