본문 바로가기
모바일 앱/Android

[Android] 안드로이드 스튜디오에서 SQLite를 이용한 데이터베이스 구축하기

by 테크케찰 2020. 7. 11.

오늘은 안드로이드 스튜디오에서 SQLite를 이용하여 데이터베이스를 구축하는 법에 대해서 알아보도록 하겠습니다.

현재 제가 하고 있는 프로젝트를 바탕으로 데이터베이스를 만들어 소개해드리도록 하겠습니다. 현재 진행하는 프로젝트는 컴퓨터활용능력시험의 개념 공부 앱으로 컴활 시험의 개념이 랜덤하게 나오도록 하는 앱입니다. 데이터베이스에 여러 개념들을 저장해 랜덤하게 디스플레이할 계획입니다. 

 

데이터베이스의 생성은 먼저 java 파일을 생성해주는 것으로 시작하는데요, SQLiteOpenHelper라는 클래스를 상속받아야 합니다. java 파일을 만들면 onCreate와 onUpgrade 메서드를 오버라이드하실 수 있는데요, 여기서 onCreate 메서드는 데이터베이스를 생성해주고, onUpgrade 메서드는 데어티를 업데이트(갱신)해주는 역할을 합니다.

package com.computerlicense;

import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class DBHelper extends SQLiteOpenHelper {

    private final String ID="id";
    private static final String DATABASE_NAME="Content.db";
    private final String TABLE_NAME="Table_content";
    private final String INFO="info";
    private final String CONTENT="content";
    private final String ISLIKE="islike";
    public static final int DATABASE_VERSION=1;

    private final String createQuery="CREATE TABLE IF NOT EXISTS "+TABLE_NAME+"("+ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "
            +INFO+" TEXT, "
            +CONTENT+" TEXT, "
            +ISLIKE+" INTEGER)";

//생성자
    public DBHelper(Context context){
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


//    데이터 베이스 생성
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(createQuery);
    }

//    데이터베이스 업데이트
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
    
    public Cursor loadSQLiteDBCursor(){
        SQLiteDatabase db=this.getReadableDatabase();
        db.beginTransaction();

		String selectQuery="SELECT "+ID+", "+INFO+", "+CONTENT+", "+ISLIKE+" FROM "+TABLE_NAME+" ORDER BY RANDOM() LIMIT 1";        
        Cursor cursor=null;

        try{
            cursor=db.rawQuery(selectQuery, null);
            db.setTransactionSuccessful();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            db.endTransaction();
        }
        return cursor;
    }
    
    
//데이터베이스에 값 삽입하는 함수
    public void insertContent(int info, String content, int islike){
        ContentValues contentValues=new ContentValues();
        SQLiteDatabase db=getWritableDatabase(); // 데이터베이스를 수정할 때는 getWritableDatabase(), 데이터를 읽을 떄는 getReadableDatabase()를 씁니다
        contentValues.put(INFO, info);
        contentValues.put(CONTENT, content);
        contentValues.put(ISLIKE, islike);
        db.insert(TABLE_NAME, null, contentValues);
    }

// 데이터베이스에 값 일괄적으로 삽입
	public void loadContent(SQLiteDatabase db){
        insertContent(1, "플러그 앤 플레이: 한글 Windows에 하드웨어 장치를 추가할 때 운영체제가 이를 자동으로 인식하여 설치 및 환경설정을 용이하게 해주는 기능", 0);
        insertContent(1, "단축키 F3: 탐색기의 '검색 상자' 선택하기", 0);
        insertContent(1, "단축키 Alt+Esc: 실행 중인 프로그램 사이에 작업 전환을 한다.\n한 번씩 누를 떄마다 열려 있는 프로그램의 창이 바로 바뀐다.", 0);
    }
}

 

코드는 이렇게 짜보았습니다. onCreate 메서드에 있는 execSQL() 메서드는 쿼리문을 실행시켜주는 메서드입니다. id, info, content, islike라는 4개의 요소를 가진 테이블을 생성했습니다.

onUpgrade 메서드 아래에 보시면 loadSQLiteDBCursor라는 메서드가 있습니다. Cursor는 데이터베이스의 값이 저장된 객체라고 생각하시면 될 것 같습니다. loadSQLiteDBCursor에서는 SELECT 문을 이용해 데이터베이스 값을 읽어와 cursor 객체에 저장을 하는 역할을 합니다. 위에 데이터베이스를 생성할 때에는 execSQL이라는 메서드를 이용하여 쿼리문을 실행시켰는데요, SELECT 문을 쓸 때에는 rawQuery 메서드를 이용한다고 합니다.

그 밑에는 insertContent라는 함수를 만들었는데요, 이 메서드를 이용해서 데이터베이스에 값을 넣을 수 있습니다. 그리고 이 insertContent 함수를 이용하여 값을 일괄적으로 데이터베이스에 삽입하는 loadContent라는 함수를 만들었는데요, 이 함수를 이용해서 앱이 최초로 실행될 떄 값을 넣을 계획입니다. 

 

이렇게 DBHelper 클래스를 작성하고, MainActivity에서 최초 실행 시에 loadContent 함수를 이용하여 데이터베이스에 값을 삽입합니다. 이후 MainActivity에서 loadSQLiteCursor() 함수를 이용하여 데이터베이스 값을 읽어오도록 코드를 구현했습니다. 

package com.computerlicense;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements OnBackPressedListener{

    private TextView TextView_main_content, TextView_main_content_info;
    private ImageButton ImageButton_next, ImageButton_like, ImageButton_before, ImageButton_liked_content, ImageButton_setting;
    private DBHelper dbHelper;
    private SQLiteDatabase db;
    private long backKeyPressedTime;

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

        TextView_main_content=findViewById(R.id.TextView_main_content);
        TextView_main_content_info=findViewById(R.id.TextView_main_content_info);
        ImageButton_next=findViewById(R.id.ImageButton_next);
        ImageButton_before=findViewById(R.id.ImageButton_before);
        ImageButton_like=findViewById(R.id.ImageButton_like);
        ImageButton_liked_content=findViewById(R.id.ImageButton_liked_contents);
        ImageButton_setting=findViewById(R.id.ImageButton_setting);

        dbHelper=new DBHelper(this);
        db=dbHelper.getReadableDatabase();

        SharedPreferences sharedPreferences=getSharedPreferences("IsFirst", MODE_PRIVATE);
        boolean isFirst = sharedPreferences.getBoolean("isFirst", false);
        if(!isFirst){ //최초 실행시 true 저장
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("isFirst", true);
            editor.commit();

            dbHelper.loadContent(db);
        }

        final Cursor cursor=dbHelper.loadSQLiteDBCursor();
        try{
            cursor.moveToFirst();
            setContent(cursor.getInt(1), cursor.getString(2));
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    //    두 번 누르면 앱 종료
    @Override
    public void onBackPressed() {
        Toast toast=Toast.makeText(MainActivity.this, "한 번 더 누르면 종료됩니다.", Toast.LENGTH_SHORT);
        if(System.currentTimeMillis() > backKeyPressedTime + 2000){
            backKeyPressedTime = System.currentTimeMillis();
            toast.show();
            return;
        }
        if(System.currentTimeMillis() <= backKeyPressedTime + 2000){
            finish();
            toast.cancel();
        }
    }

    public void setContent(int info, String content){
        String temp="";
        if(info==1) temp="1. 컴퓨터 일반";
        else if(info==2) temp="2. 스프레드시트 일반";
        else if(info==3) temp="3. 데이터베이스 일반";
        TextView_main_content_info.setText(temp);
        TextView_main_content.setText(content);
    }
}

 

보시면 아래 setContent 함수를 작성하여 레이아웃의 객체들에 값을 지정해주어 화면에 데이터베이스 값들을 표시할 수 있도록 했습니다. 앱을 실행시켜보면 아래와 같은 결과가 뜨는 것을 확인할 수 있습니다. 

 

보시면 우리가 삽입했던 데이터베이스 값이 화면에 표시되는 것을 확인하실 수 있습니다.

아직 버튼 구현도 안되어있고, 레이아웃에서 디자인도 안 되어 있어 아직은 많이 허접해 보이죠? ㅎㅎ

앱이 완성되면 개인 프로젝트 페이지에서 완성된 앱에 대한 포스팅을 올려 보여드리도록 하겠습니다 ^~^