반응형


간단한 SQLite를 사용하는 예제 입니다.

앱을 시작하면 데이터 베이스를 생성하고  names, phones 두개의 컬럼이 있는 테이블을 생성하고 데이터를 삽입합니다.

그리고 나서 테이블에서 데이터를 가져와 리스트뷰에 보여주는 예제입니다..





activity_main.xml파일입니다. 리스트뷰를 화면에 보여줍니다.


<?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"
   tools:context=".MainActivity">

   <ListView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/listView" />


</LinearLayout>




list_item.xml은 listview 한줄에 여러 개의 항목을 보여주기 위해 필요한 레이아웃입니다.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:orientation="horizontal"
   android:padding="10dp"
   android:paddingLeft="10dp"
   android:paddingRight="10dp" >

   <TextView
       android:id="@+id/name"
       android:layout_width="0dp"
       android:layout_weight="0.5"
       android:layout_height="wrap_content"
       android:textStyle="bold"/>


   <TextView
       android:id="@+id/phone"
       android:layout_width="0dp"
       android:layout_weight="0.5"
       android:layout_height="wrap_content"
       android:textStyle="bold" />

</LinearLayout>




MainActivity.java는 자바 프로그램 코드 입니다.


package com.tistory.webnautes.sqllite_example;


import android.app.Activity;
import android.os.Bundle;

import java.util.ArrayList;
import java.util.HashMap;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;




public class MainActivity  extends Activity {


   private final String dbName = "webnautes";
   private final String tableName = "person";

   private String names[];
   {
       names = new String[]{"Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Ice Cream Sandwich", "Jelly Bean", "Kitkat"};
   }

   private final String phones[];
   {
       phones = new String[]{"Android 1.5", "Android 1.6", "Android 2.0", "Android 2.2", "Android 2.3", "Android  3.0", "Android  4.0", "Android  4.1", "Android  4.4"};
   }


   ArrayList<HashMap<String, String>> personList;
   ListView list;
   private static final String TAG_NAME = "name";
   private static final String TAG_PHONE ="phone";

   SQLiteDatabase sampleDB = null;
   ListAdapter adapter;


   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       list = (ListView) findViewById(R.id.listView);
       personList = new ArrayList<HashMap<String,String>>();


       try {


           sampleDB = this.openOrCreateDatabase(dbName, MODE_PRIVATE, null);

           //테이블이 존재하지 않으면 새로 생성합니다.
           sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " + tableName
                   + " (name VARCHAR(20), phone VARCHAR(20) );");

           //테이블이 존재하는 경우 기존 데이터를 지우기 위해서 사용합니다.
           sampleDB.execSQL("DELETE FROM " + tableName  );

           //새로운 데이터를 테이블에 집어넣습니다..
           for (int i=0; i<names.length; i++ ) {
               sampleDB.execSQL("INSERT INTO " + tableName
                       + " (name, phone)  Values ('" + names[i] + "', '" + phones[i]+"');");
           }

           sampleDB.close();

       } catch (SQLiteException se) {
           Toast.makeText(getApplicationContext(),  se.getMessage(), Toast.LENGTH_LONG).show();
           Log.e("", se.getMessage());


       }

       showList();

   }




   protected void showList(){

       try {

           SQLiteDatabase ReadDB = this.openOrCreateDatabase(dbName, MODE_PRIVATE, null);


           //SELECT문을 사용하여 테이블에 있는 데이터를 가져옵니다..
           Cursor c = ReadDB.rawQuery("SELECT * FROM " + tableName, null);

           if (c != null) {


               if (c.moveToFirst()) {
                   do {

                       //테이블에서 두개의 컬럼값을 가져와서
                       String Name = c.getString(c.getColumnIndex("name"));
                       String Phone = c.getString(c.getColumnIndex("phone"));

                       //HashMap에 넣습니다.
                       HashMap<String,String> persons = new HashMap<String,String>();

                       persons.put(TAG_NAME,Name);
                       persons.put(TAG_PHONE,Phone);

                       //ArrayList에 추가합니다..
                       personList.add(persons);

                   } while (c.moveToNext());
               }
           }

           ReadDB.close();


           //새로운 apapter를 생성하여 데이터를 넣은 후..
           adapter = new SimpleAdapter(
                   this, personList, R.layout.list_item,
                   new String[]{TAG_NAME,TAG_PHONE},
                   new int[]{ R.id.name, R.id.phone}
           );


           //화면에 보여주기 위해 Listview에 연결합니다.
           list.setAdapter(adapter);


       } catch (SQLiteException se) {
           Toast.makeText(getApplicationContext(),  se.getMessage(), Toast.LENGTH_LONG).show();
           Log.e("",  se.getMessage());
       }

   }


}




업데이트  

2015. 11. 22

2019.  2. 12





반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts