Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 SQLite에서 IS NOT NULL 조건으로 데이터 조회하는 방법

안드로이드 SQLite란 무엇인가?

예제를 시작하기 전에 안드로이드의 SQLite 데이터베이스가 무엇인지 간단히 알아보겠습니다. SQLite는 기기 내부의 텍스트 파일 형태로 데이터를 저장하는 오픈소스 SQL 데이터베이스입니다. 안드로이드에는 SQLite 데이터베이스 구현이 기본적으로 내장되어 있어 별도의 설치 없이 바로 사용할 수 있으며, 관계형 데이터베이스의 거의 모든 기능을 지원합니다.

특히 SQLite는 JDBC나 ODBC처럼 별도의 연결(Connection) 설정 과정이 필요 없다는 장점이 있습니다. 데이터베이스 파일에 직접 접근하여 손쉽게 데이터를 읽고 쓸 수 있습니다.

이번 예제에서는 SQLite 쿼리에서 IS NOT NULL 절을 사용하여 NULL 값이 아닌 데이터만 조회하는 방법을 단계별로 알아보겠습니다.

1단계: 새 프로젝트 생성

Android Studio에서 File → New Project로 이동하여 새 프로젝트를 생성하고, 프로젝트 생성에 필요한 모든 정보를 입력합니다.

2단계: 레이아웃 XML 작성

res/layout/activity_main.xml 파일에 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:hint="Enter Name"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/salary"
        android:layout_width="match_parent"
        android:inputType="numberDecimal"
        android:hint="Enter Salary"
        android:layout_height="wrap_content" />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"><Button
        android:id="@+id/save"
        android:text="Save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
        <Button
            android:id="@+id/refresh"
            android:text="Refresh"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/udate"
            android:text="Update"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

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

위 레이아웃에는 이름(name)과 급여(salary)를 입력받는 두 개의 EditText가 배치되어 있습니다. 사용자가 저장(Save) 버튼을 클릭하면 입력된 데이터가 SQLite 데이터베이스에 저장됩니다. 값을 삽입한 후 새로고침(Refresh) 버튼을 클릭하면 IS NOT NULL 절이 적용된 커서(Cursor) 결과로 ListView가 갱신됩니다. 또한 업데이트(Update) 버튼을 누르면 기존 데이터가 수정됩니다.

3단계: MainActivity 작성

src/MainActivity.java 파일에 다음 코드를 추가합니다.

package com.example.andy.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    Button save, refresh;
    EditText name, salary;
    private ListView listView;

    @Override
    protected void onCreate(Bundle readdInstanceState) {
        super.onCreate(readdInstanceState);
        setContentView(R.layout.activity_main);
        final DatabaseHelper helper = new DatabaseHelper(this);
        final ArrayList array_list = helper.getAllCotacts();
        name = findViewById(R.id.name);
        salary = findViewById(R.id.salary);
        listView = findViewById(R.id.listView);
        final ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, array_list);
        listView.setAdapter(arrayAdapter);
        findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                array_list.clear();
                array_list.addAll(helper.getAllCotacts());
                arrayAdapter.notifyDataSetChanged();
                listView.invalidateViews();
                listView.refreshDrawableState();
            }
        });

        findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {
                    if (helper.insert(name.getText().toString(), salary.getText().toString())) {
                        Toast.makeText(MainActivity.this, "Inserted", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(MainActivity.this, "NOT Inserted", Toast.LENGTH_LONG).show();
                    }
                } else {
                    name.setError("Enter NAME");
                    salary.setError("Enter Salary");
                }
            }
        });
    }
}

4단계: DatabaseHelper 작성 — IS NOT NULL 적용

src/DatabaseHelper.java 파일에 다음 코드를 추가합니다. 여기서 getAllCotacts() 메서드의 rawQuery가 핵심입니다.

package com.example.andy.myapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

import java.io.IOException;
import java.util.ArrayList;

class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "salaryDatabase5";
    public static final String CONTACTS_TABLE_NAME = "SalaryDetails";
    public DatabaseHelper(Context context) {
        super(context,DATABASE_NAME,null,1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL(
                "create table "+ CONTACTS_TABLE_NAME +"(id INTEGER PRIMARY KEY, name text,salary text,datetime default current_timestamp )"
            );
        } catch (SQLiteException e) {
            try {
                throw new IOException(e);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+CONTACTS_TABLE_NAME);
        onCreate(db);
    }

    public boolean insert(String s, String s1) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        contentValues.put("name", s);
        contentValues.put("salary", s1);
        db.replace(CONTACTS_TABLE_NAME, null, contentValues);
        return true;
    }

    public ArrayList getAllCotacts() {
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<String> array_list = new ArrayList<String>();
        Cursor res = db.rawQuery( "select * from "+CONTACTS_TABLE_NAME+" WHERE name = 'sairam' AND name is not null ", null );
        res.moveToFirst();

        while(res.isAfterLast() == false) {
            array_list.add(res.getString(res.getColumnIndex("name")));
            res.moveToNext();
        }
        return array_list;
    }

    public boolean update(String s, String s1) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("UPDATE "+CONTACTS_TABLE_NAME+" SET name = "+"'"+s+"', "+ "salary = "+"'"+s1+"'");
        return true;
    }

    public boolean delete() {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("DELETE from "+CONTACTS_TABLE_NAME);
        return true;
    }
}

핵심 포인트: IS NOT NULL 쿼리 분석

위 코드에서 주목할 부분은 다음 쿼리입니다.

select * from SalaryDetails WHERE name = 'sairam' AND name is not null

이 쿼리는 두 가지 조건을 동시에 검사합니다. 첫째, name 컬럼의 값이 'sairam'과 일치해야 하고, 둘째, name 컬럼이 NULL이 아니어야(NOT NULL) 한다는 조건입니다. SQL에서 NULL은 빈 문자열('')과 다른 개념으로, 값 자체가 존재하지 않는 상태를 의미합니다. 따라서 NULL 값이 섞여 있는 데이터에서 정확한 결과만 추출하려면 IS NOT NULL 조건을 함께 사용하는 것이 좋습니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰이 컴퓨터와 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 후 툴바의 실행(Run) 아이콘을 클릭하세요. 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

안드로이드 SQLite에서 IS NOT NULL 조건으로 데이터 조회하는 방법

실행 결과를 보면, name 값이 'sairam'과 일치하면서 동시에 NULL이 아닌 데이터만 조회되어 ListView에 출력된 것을 확인할 수 있습니다. 이처럼 IS NOT NULL 절을 활용하면 NULL 값이 포함된 불완전한 데이터를 걸러내고, 신뢰할 수 있는 데이터만 깔끔하게 조회할 수 있습니다.