본문 바로가기
안드로이드 자바

[Java][Android] DTO 객체를 사용하여 시간 최신 정렬하기

by teamnova 2024. 7. 24.
728x90

안녕하세요.

안드로이드에서 DTO객체를 사용해서 ArrayList에 저장하고 최신시간으로 정렬하고 텍스트뷰어로 출력해 보겠습니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Sorted Times"
        android:textSize="18sp" />
</RelativeLayout>
public class DTO {
    String Time;

    public String getTime() {
        return Time;
    }

    public void setTime(String time) {
        Time = time;
    }
}
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;

public class DTO_comparator implements Comparator<DTO> {
    @Override
    public int compare(DTO o1, DTO o2) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 비교할 시간들의 패턴과 타임존을 설정합니다.

        Date day1 = null;
        Date day2 = null;

        try {
            day1 = format.parse(o1.getTime());
            day2 = format.parse(o2.getTime());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        return day2.compareTo(day1); // 최근 시간이 먼저 오도록 정렬
    }
}
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;

public class MainActivity extends AppCompatActivity {
    ArrayList<DTO> addTime;
    DTO dto1, dto2, dto3;
    TextView textView;

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

        textView = findViewById(R.id.textView);
        addTime = new ArrayList<>();

        // DTO 객체 생성 및 시간 설정
        dto1 = new DTO();
        dto1.setTime("2024-06-12 12:11:22");
        addTime.add(dto1);

        dto2 = new DTO();
        dto2.setTime("2024-06-13 12:11:22");
        addTime.add(dto2);

        dto3 = new DTO();
        dto3.setTime("2024-06-12 03:15:22");
        addTime.add(dto3);

        // DTO_comparator를 사용하여 정렬
        DTO_comparator tc = new DTO_comparator();
        Collections.sort(addTime, tc);

        //정렬된 시간을 TextView에 표시
        StringBuilder sortedTimes = new StringBuilder();
        for (DTO dto : addTime) {
            sortedTimes.append(dto.getTime()).append("\n");
        }
        textView.setText(sortedTimes.toString());
    }
}

 

시연화면 입니다.