안드로이드 SQLite란 무엇인가?
예제를 살펴보기 전에 안드로이드에서의 SQLite 데이터베이스가 무엇인지 먼저 이해할 필요가 있습니다. SQLite는 기기의 텍스트 파일 형태로 데이터를 저장하는 오픈소스 SQL 데이터베이스입니다. 안드로이드에는 SQLite 데이터베이스 구현체가 기본으로 내장되어 있으며, 관계형 데이터베이스의 모든 핵심 기능을 지원합니다. 또한 JDBC나 ODBC처럼 별도의 연결 설정 없이도 바로 데이터베이스에 접근할 수 있다는 점이 큰 장점입니다.
이 글에서는 안드로이드 SQLite에서 MAX() 함수를 사용해 특정 컬럼의 최댓값(예: 가장 높은 급여)을 조회하는 방법을 단계별로 알아보겠습니다.
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" />
<Button
android:id="@+id/Delete"
android:text="DeleteALL"
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 버튼을 누르면 ListView에 저장된 목록이 표시됩니다. 그 외에 Update와 DeleteAll 버튼도 함께 제공됩니다.
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.Delete).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (helper.delete()) {
Toast.makeText(MainActivity.this, "Deleted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "NOT Deleted", Toast.LENGTH_LONG).show();
}
}
});
findViewById(R.id.udate).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty() && !salary.getText().toString().isEmpty()) {
if (helper.update(name.getText().toString(), salary.getText().toString())) {
Toast.makeText(MainActivity.this, "Updated", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "NOT Updated", Toast.LENGTH_LONG).show();
}
} else {
name.setError("Enter NAME");
salary.setError("Enter Salary");
}
}
});
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 작성 — MAX() 쿼리의 핵심
src/DatabaseHelper.java에 아래 코드를 추가합니다. 여기서 주목해야 할 부분은 getAllCotacts() 메서드 내부의 SQL 쿼리입니다. max(salary) 집계 함수를 사용해 전체 레코드 중 가장 높은 급여 값을 조회합니다.
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 = "salaryDatabase6";
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 int,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 (id ||' : '||name || ' : ' || max(salary) || ' : '|| datetime) as HighestNumber from "+CONTACTS_TABLE_NAME, null );
res.moveToFirst();
while(res.isAfterLast() == false) {
array_list.add(res.getString(res.getColumnIndex("HighestNumber")));
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;
}
}핵심 쿼리 분석
최댓값 조회의 핵심은 다음 SQL 문입니다:
select (id ||' : '||name || ' : ' || max(salary) || ' : '|| datetime) as HighestNumber from SalaryDetails
이 쿼리는 max(salary)를 통해 급여 컬럼의 최대값을 구하고, id·이름·날짜 정보와 함께 하나의 문자열로 결합하여 결과를 반환합니다. 만약 최댓값만 단독으로 얻고 싶다면 SELECT MAX(salary) FROM SalaryDetails처럼 더 간단하게 작성할 수도 있습니다.
애플리케이션 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하고, 옵션에서 자신의 모바일 기기를 선택하면 기기 화면에 기본 화면이 표시됩니다.

실행 결과를 보면 전체 레코드 중 가장 높은 급여(MAX salary)를 가진 레코드가 화면에 표시되는 것을 확인할 수 있습니다. 이처럼 SQLite의 MAX() 집계 함수를 활용하면 안드로이드 앱에서 손쉽게 최댓값 데이터를 조회할 수 있습니다.