[android] 안드로이드 SQLite 데이터베이스와 Retrofit

안드로이드 앱을 개발하면서 데이터를 저장하고 관리하며 서버와 통신해야 할 때가 많습니다. 안드로이드에서는 SQLite 데이터베이스를 이용해 로컬에 데이터를 저장하고, Retrofit 라이브러리를 사용하여 서버와 통신하는 방법을 소개하겠습니다.

1. 안드로이드 SQLite 데이터베이스

SQLite는 안드로이드에서 기본으로 제공되는 경량 데이터베이스로, 앱 내부에서 구조화된 데이터를 저장하고 관리할 수 있습니다. 데이터의 CRUD(Create, Read, Update, Delete) 작업을 수행할 수 있어 로컬 데이터를 효율적으로 다룰 때 매우 유용합니다.

코드 예시:

// 데이터베이스 생성 또는 열기
SQLiteDatabase db = dbHelper.getWritableDatabase();

// 데이터 입력
ContentValues values = new ContentValues();
values.put("name", "John Doe");
values.put("age", 25);
long newRowId = db.insert("users", null, values);

// 데이터 조회
Cursor cursor = db.query("users", null, null, null, null, null, null);
while(cursor.moveToNext()) {
    String name = cursor.getString(cursor.getColumnIndex("name"));
    int age = cursor.getInt(cursor.getColumnIndex("age"));
    // 데이터 활용
}

// 데이터 수정
ContentValues newValues = new ContentValues();
newValues.put("age", 26);
String whereClause = "name=?";
String[] whereArgs = {"John Doe"};
db.update("users", newValues, whereClause, whereArgs);

// 데이터 삭제
String deleteWhere = "name=?";
String[] deleteArgs = {"John Doe"};
db.delete("users", deleteWhere, deleteArgs);

// 데이터베이스 닫기
db.close();

2. Retrofit을 통한 네트워크 통신

Retrofit은 안드로이드에서 RESTful 웹 서비스와 통신하기 위한 라이브러리로, 간단한 인터페이스 정의를 통해 서버와 손쉽게 통신할 수 있습니다. JSON 또는 XML과 같은 형식으로 데이터를 주고받을 수 있어, 서버에서 데이터를 가져오거나 업데이트하는 작업에 적합합니다.

코드 예시:

public interface ApiService {
    @GET("users/{id}")
    Call<User> getUser(@Path("id") int userId);

    @POST("users/new")
    Call<User> createUser(@Body User user);
}

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

ApiService service = retrofit.create(ApiService.class);

Call<User> userCall = service.getUser(123);
userCall.enqueue(new Callback<User>() {
    @Override
    public void onResponse(Call<User> call, Response<User> response) {
        // 데이터 활용
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {
        // 오류 처리
    }
});

위 예시 코드에서는 Retrofit을 사용하여 RESTful API에 GET 및 POST 요청을 보내는 방법을 보여줍니다.

앱을 개발하면서 SQLite 데이터베이스를 사용하여 로컬 데이터를 관리하고, Retrofit을 통해 서버와 통신하여 외부 데이터를 쉽게 가져올 수 있습니다. 이러한 기술들을 익힘으로써 안드로이드 앱의 데이터 처리와 네트워킹 기능을 효과적으로 구현할 수 있습니다.

참고 자료:

안드로이드 SQLite 데이터베이스와 Retrofit를 활용하여 데이터 저장 및 네트워크 통신을 효과적으로 다룰 수 있습니다. 이러한 기술들을 조합하여 안정적이고 성능 좋은 안드로이드 앱을 개발할 수 있습니다.