예전에 어떤 앱을 만들기 할 때 사용했던 음력 변환 하는 소스를 어딘가에서 찾았던 거 같은데... 다시 한번 기억해 보기 위해서 적어 보기로 했다. 

 

https://billcorea.tistory.com/4

 

구글로간 음력 설명서

새로운 버젼으로 업데이트 해 드립니다. Google Calendar 에서는 아직 음력 관리를 원할하게 해 주지 않는 현상이 있었습니다. 그래서 과거에 만들었던 앱을 다시 만들어 보았습니다. 2020.06.20 구글에

billcorea.tistory.com

 

이건 어딘가에서 퍼왔던 소스인데, 기억이 가물 가물 하다.  

import java.text.SimpleDateFormat;
import java.util.Date;

public class LunarTranser {
    private static final int kk[] = {
        1, 2, 1, 2, 1, 2, 2, 3, 2, 2,
        1, 2, 1, 1, 2, 1, 2, 1, 2, 1,
        2, 2, 1, 2, 2, 0, 1, 1, 2, 1,
        1, 2, 1, 2, 2, 2, 1, 2, 0, 2,
        1, 1, 2, 1, 3, 2, 1, 2, 2, 1,
        2, 2, 2, 1, 1, 2, 1, 1, 2, 1,
        2, 1, 2, 2, 0, 2, 1, 2, 1, 2,
        1, 1, 2, 1, 2, 1, 2, 0, 2, 2,
        1, 2, 3, 2, 1, 1, 2, 1, 2, 1,
        2, 2, 1, 2, 2, 1, 2, 1, 1, 2,
        1, 2, 1, 0, 2, 1, 2, 2, 1, 2,
        1, 2, 1, 2, 1, 2, 0, 1, 2, 3,
        2, 1, 2, 2, 1, 2, 1, 2, 1, 2,
        1, 2, 1, 2, 1, 2, 1, 2, 2, 1,
        2, 2, 0, 1, 1, 2, 1, 1, 2, 3,
        2, 2, 1, 2, 2, 2, 1, 1, 2, 1,
        1, 2, 1, 2, 1, 2, 2, 2, 0, 1,
        2, 1, 2, 1, 1, 2, 1, 2, 1, 2,
        2, 0, 2, 1, 2, 1, 2, 3, 1, 2,
        1, 2, 1, 2, 1, 2, 2, 2, 1, 2,
        1, 1, 2, 1, 2, 1, 2, 0, 1, 2,
        2, 1, 2, 1, 2, 1, 2, 1, 2, 1,
        0, 2, 1, 2, 3, 2, 2, 1, 2, 1,
        2, 1, 2, 1, 2, 1, 2, 1, 2, 1,
        2, 2, 1, 2, 1, 2, 0, 1, 2, 1,
        1, 2, 1, 2, 2, 3, 2, 2, 1, 2,
        1, 2, 1, 1, 2, 1, 2, 1, 2, 2,
        2, 1, 0, 2, 1, 2, 1, 1, 2, 1,
        2, 1, 2, 2, 2, 0, 1, 2, 1, 2,
        1, 3, 2, 1, 1, 2, 2, 1, 2, 2,
        2, 1, 2, 1, 1, 2, 1, 1, 2, 2,
        1, 0, 2, 2, 1, 2, 2, 1, 1, 2,
        1, 2, 1, 2, 0, 1, 2, 2, 1, 4,
        1, 2, 1, 2, 1, 2, 1, 2, 1, 2,
        1, 2, 1, 2, 2, 1, 2, 1, 2, 1,
        0, 2, 1, 1, 2, 2, 1, 2, 1, 2,
        2, 1, 2, 0, 1, 2, 3, 1, 2, 1,
        2, 1, 2, 2, 2, 1, 2, 1, 2, 1,
        1, 2, 1, 2, 1, 2, 2, 2, 1, 0,
        2, 1, 2, 1, 1, 2, 3, 1, 2, 2,
        1, 2, 2, 2, 1, 2, 1, 1, 2, 1,
        1, 2, 2, 1, 2, 0, 2, 2, 1, 2,
        1, 1, 2, 1, 1, 2, 1, 2, 0, 2,
        2, 1, 2, 2, 3, 1, 2, 1, 2, 1,
        1, 2, 2, 1, 2, 2, 1, 2, 1, 2,
        1, 2, 1, 2, 0, 1, 2, 1, 2, 1,
        2, 2, 1, 2, 1, 2, 1, 0, 2, 1,
        3, 2, 1, 2, 2, 1, 2, 2, 1, 2,
        1, 2, 1, 1, 2, 1, 2, 1, 2, 2,
        2, 1, 2, 0, 1, 2, 1, 1, 2, 1,
        2, 3, 2, 2, 1, 2, 2, 1, 2, 1,
        1, 2, 1, 1, 2, 2, 1, 2, 2, 0,
        2, 1, 2, 1, 1, 2, 1, 1, 2, 1,
        2, 2, 0, 2, 1, 2, 2, 1, 3, 2,
        1, 1, 2, 1, 2, 2, 1, 2, 2, 1,
        2, 1, 2, 1, 2, 1, 1, 2, 0, 2,
        1, 2, 1, 2, 2, 1, 2, 1, 2, 1,
        1, 0, 2, 1, 2, 2, 3, 2, 1, 2,
        2, 1, 2, 1, 2, 1, 1, 2, 1, 2,
        1, 2, 2, 1, 2, 2, 1, 0, 2, 1,
        1, 2, 1, 2, 1, 2, 2, 1, 2, 2,
        0, 1, 2, 3, 1, 2, 1, 1, 2, 2,
        1, 2, 2, 2, 1, 2, 1, 1, 2, 1,
        1, 2, 1, 2, 2, 2, 0, 1, 2, 2,
        1, 1, 2, 3, 1, 2, 1, 2, 2, 1,
        2, 2, 2, 1, 1, 2, 1, 1, 2, 1,
        2, 1, 0, 2, 2, 2, 1, 2, 1, 2,
        1, 1, 2, 1, 2, 0, 1, 2, 2, 1,
        2, 4, 1, 2, 1, 2, 1, 1, 2, 1,
        2, 1, 2, 2, 1, 2, 2, 1, 2, 1,
        2, 0, 1, 1, 2, 1, 2, 1, 2, 2,
        1, 2, 2, 1, 0, 2, 1, 1, 4, 1,
        2, 1, 2, 1, 2, 2, 2, 1, 2, 1,
        1, 2, 1, 1, 2, 1, 2, 2, 2, 1,
        0, 2, 2, 1, 1, 2, 1, 1, 4, 1,
        2, 2, 1, 2, 2, 2, 1, 1, 2, 1,
        1, 2, 1, 2, 1, 2, 0, 2, 2, 1,
        2, 1, 2, 1, 1, 2, 1, 2, 1, 0,
        2, 2, 1, 2, 2, 1, 4, 1, 1, 2,
        1, 2, 1, 2, 1, 2, 2, 1, 2, 2,
        1, 2, 1, 1, 2, 0, 1, 2, 1, 2,
        1, 2, 2, 1, 2, 2, 1, 2, 0, 1,
        1, 2, 1, 4, 1, 2, 1, 2, 2, 1,
        2, 2, 1, 1, 2, 1, 1, 2, 1, 2,
        2, 2, 1, 2, 0, 2, 1, 1, 2, 1,
        1, 2, 1, 2, 2, 1, 2, 0, 2, 2,
        3, 1, 2, 1, 1, 2, 1, 2, 1, 2,
        2, 2, 1, 2, 1, 2, 1, 1, 2, 1,
        2, 1, 2, 0, 2, 2, 1, 2, 1, 2,
        1, 3, 2, 1, 2, 1, 2, 2, 1, 2,
        2, 1, 2, 1, 1, 2, 1, 2, 1, 0,
        2, 1, 2, 2, 1, 2, 1, 2, 1, 2,
        1, 2, 0, 1, 2, 1, 2, 1, 4, 2,
        1, 2, 1, 2, 1, 2, 1, 2, 1, 1,
        2, 2, 1, 2, 2, 1, 2, 2, 0, 1,
        1, 2, 1, 1, 2, 1, 2, 2, 1, 2,
        2, 0, 2, 1, 1, 4, 1, 1, 2, 1,
        2, 1, 2, 2, 2, 1, 2, 1, 2, 1,
        1, 2, 1, 2, 1, 2, 2, 0, 2, 1,
        2, 1, 2, 1, 1, 2, 3, 2, 1, 2,
        2, 1, 2, 2, 1, 2, 1, 1, 2, 1,
        2, 1, 2, 0, 1, 2, 2, 1, 2, 1,
        2, 1, 2, 1, 2, 1, 0, 2, 1, 2,
        1, 2, 2, 3, 2, 1, 2, 1, 2, 1,
        2, 1, 2, 1, 2, 1, 2, 2, 1, 2,
        1, 2, 0, 1, 2, 1, 1, 2, 1, 2,
        2, 1, 2, 2, 1, 0, 2, 1, 2, 1,
        3, 2, 1, 2, 1, 2, 2, 2, 1, 2,
        1, 2, 1, 1, 2, 1, 2, 1, 2, 2,
        2, 0, 1, 2, 1, 2, 1, 1, 2, 1,
        1, 2, 2, 1, 0, 2, 2, 2, 3, 2,
        1, 1, 2, 1, 1, 2, 2, 1, 2, 2,
        1, 2, 2, 1, 1, 2, 1, 2, 1, 2,
        0, 1, 2, 2, 1, 2, 1, 2, 3, 2,
        1, 2, 1, 2, 1, 2, 1, 2, 1, 2,
        2, 1, 2, 1, 2, 1, 0, 2, 1, 1,
        2, 2, 1, 2, 1, 2, 2, 1, 2, 0,
        1, 2, 1, 1, 2, 3, 2, 1, 2, 2,
        2, 1, 2, 1, 2, 1, 1, 2, 1, 2,
        1, 2, 2, 2, 1, 0, 2, 1, 2, 1,
        1, 2, 1, 1, 2, 2, 2, 1, 0, 2,
        2, 1, 2, 3, 1, 2, 1, 1, 2, 2,
        1, 2, 2, 2, 1, 2, 1, 1, 2, 1,
        1, 2, 1, 2, 0, 2, 2, 1, 2, 1,
        2, 1, 2, 3, 2, 1, 1, 2, 2, 1,
        2, 2, 1, 2, 1, 2, 1, 2, 1, 1,
        0, 2, 2, 1, 2, 1, 2, 2, 1, 2,
        1, 2, 1, 0, 2, 1, 1, 2, 1, 2,
        4, 1, 2, 2, 1, 2, 1, 2, 1, 1,
        2, 1, 2, 1, 2, 2, 1, 2, 2, 0,
        1, 2, 1, 1, 2, 1, 1, 2, 2, 1,
        2, 2, 0, 2, 1, 2, 1, 3, 2, 1,
        1, 2, 2, 1, 2, 2, 2, 1, 2, 1,
        1, 2, 1, 1, 2, 1, 2, 2, 0, 2,
        1, 2, 2, 1, 1, 2, 1, 1, 2, 3,
        2, 2, 1, 2, 2, 1, 2, 1, 2, 1,
        1, 2, 1, 2, 0, 1, 2, 2, 1, 2,
        2, 1, 2, 1, 2, 1, 1, 0, 2, 1,
        2, 2, 1, 2, 3, 2, 2, 1, 2, 1,
        2, 1, 1, 2, 1, 2, 1, 2, 2, 1,
        2, 2, 1, 0, 2, 1, 1, 2, 1, 2,
        1, 2, 2, 1, 2, 2, 0, 1, 2, 1,
        1, 2, 3, 1, 2, 1, 2, 2, 2, 2,
        1, 2, 1, 1, 2, 1, 1, 2, 1, 2,
        2, 2, 0, 1, 2, 2, 1, 1, 2, 1,
        1, 2, 1, 2, 2, 0, 1, 2, 2, 3,
        2, 1, 2, 1, 1, 2, 1, 2, 1, 2,
        2, 2, 1, 2, 1, 2, 1, 1, 2, 1,
        2, 0, 1, 2, 2, 1, 2, 2, 1, 2,
        3, 2, 1, 1, 2, 1, 2, 1, 2, 2,
        1, 2, 1, 2, 2, 1, 2, 0, 1, 1,
        2, 1, 2, 1, 2, 2, 1, 2, 2, 1,
        0, 2, 1, 1, 2, 1, 3, 2, 2, 1,
        2, 2, 2, 1, 2, 1, 1, 2, 1, 1,
        2, 1, 2, 2, 2, 1, 0, 2, 2, 1,
        1, 2, 1, 1, 2, 1, 2, 2, 1, 0,
        2, 2, 2, 1, 3, 2, 1, 1, 2, 1,
        2, 1, 2, 2, 2, 1, 2, 1, 2, 1,
        1, 2, 1, 2, 1, 0, 2, 2, 1, 2,
        2, 1, 2, 1, 1, 2, 1, 2, 0, 1,
        2, 3, 2, 2, 1, 2, 1, 2, 2, 1,
        1, 2, 1, 2, 1, 2, 1, 2, 2, 1,
        2, 2, 1, 2, 0, 1, 1, 2, 1, 2,
        1, 2, 3, 2, 2, 1, 2, 2, 1, 1,
        2, 1, 1, 2, 1, 2, 2, 2, 1, 2,
        0, 2, 1, 1, 2, 1, 1, 2, 1, 2,
        2, 1, 2, 0, 2, 2, 1, 1, 2, 3,
        1, 2, 1, 2, 1, 2, 2, 2, 1, 2,
        1, 2, 1, 1, 2, 1, 2, 1, 2, 0,
        2, 1, 2, 2, 1, 2, 1, 1, 2, 1,
        2, 1, 0, 2, 1, 2, 4, 2, 1, 2,
        1, 1, 2, 1, 2, 1, 2, 1, 2, 2,
        1, 2, 1, 2, 1, 2, 1, 2, 0, 1,
        2, 1, 2, 1, 2, 1, 2, 2, 3, 2,
        1, 2, 1, 2, 1, 1, 2, 1, 2, 2,
        2, 1, 2, 2, 0, 1, 1, 2, 1, 1,
        2, 1, 2, 2, 1, 2, 2, 0, 2, 1,
        1, 2, 1, 3, 2, 1, 2, 1, 2, 2,
        2, 1, 2, 1, 2, 1, 1, 2, 1, 2,
        1, 2, 2, 0, 2, 1, 2, 1, 2, 1,
        1, 2, 1, 2, 1, 2, 0, 2, 1, 2,
        2, 3, 2, 1, 1, 2, 1, 2, 1, 2,
        1, 2, 2, 1, 2, 1, 2, 1, 2, 1,
        2, 1, 0, 2, 1, 2, 1, 2, 2, 1,
        2, 1, 2, 1, 2, 0, 1, 2, 3, 2,
        1, 2, 1, 2, 2, 1, 2, 1, 2, 1,
        2, 1, 1, 2, 1, 2, 2, 1, 2, 2,
        1, 0, 2, 1, 2, 1, 1, 2, 3, 2,
        1, 2, 2, 2, 1, 2, 1, 2, 1, 1,
        2, 1, 2, 1, 2, 2, 2, 0, 1, 2,
        1, 2, 1, 1, 2, 1, 1, 2, 2, 2,
        0, 1, 2, 2, 1, 2, 3, 1, 2, 1,
        1, 2, 2, 1, 2, 2, 1, 2, 2, 1,
        1, 2, 1, 1, 2, 2, 0, 1, 2, 1,
        2, 2, 1, 2, 1, 2, 1, 2, 1, 0,
        2, 1, 2, 3, 2, 1, 2, 2, 1, 2,
        1, 2, 1, 2, 1, 1, 2, 1, 2, 2,
        1, 2, 2, 1, 2, 0, 1, 2, 1, 1,
        2, 1, 2, 3, 2, 2, 2, 1, 2, 1,
        2, 1, 1, 2, 1, 2, 1, 2, 2, 2,
        1, 0, 2, 1, 2, 1, 1, 2, 1, 1,
        2, 2, 1, 2, 0, 2, 2, 1, 2, 1,
        1, 4, 1, 1, 2, 1, 2, 2, 2, 2,
        1, 2, 1, 1, 2, 1, 1, 2, 1, 2,
        0, 2, 2, 1, 2, 1, 2, 1, 2, 1,
        1, 2, 1, 0, 2, 2, 1, 2, 2, 3,
        2, 1, 2, 1, 2, 1, 1, 2, 1, 2,
        2, 1, 2, 2, 1, 2, 1, 2, 1, 0,
        2, 1, 1, 2, 1, 2, 2, 1, 2, 2,
        1, 2, 0, 1, 2, 3, 1, 2, 1, 2,
        1, 2, 2, 2, 1, 2, 1, 2, 1, 1,
        2, 1, 1, 2, 2, 1, 2, 2, 0
    };
    private final static String yuk[] = {"갑", "을", "병", "정", "무", "기", "경", "신", "임", "계"};
    private final static String gap[] = {"자", "축", "인", "묘", "진", "사", "오", "미", "신", "유", "술", "해"};
    private final static String ddi[] = {"쥐띠", "소띠", "범띠", "토끼띠", "용띠", "뱀띠", "말띠", "양띠", "원숭이띠", "닭띠", "개띠", "돼지띠"};
    private final static String week[] = {"일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"};

    private static final int m[] = {
        31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
        30, 31
    };

    private static Date init_date;

    private static final String errMsg = "입력값 에러";

    /**
     * 음력을 양력으로
     *
     * @param       TranseDay    음력일('yyyyMMdd')
     * @param       leapyes   윤달 여부
     * @return      String    처리결과 양력일 엔티티
     * @throws      java.lang.Exception
     */
    public static String LunarTranse(String TranseDay, boolean leapyes) throws Exception {
        @SuppressWarnings("unused")
		int dt[] = new int[163];
        int lyear = Integer.parseInt(TranseDay.substring(0,4));
        int lmonth = Integer.parseInt(TranseDay.substring(4,6));
        int lday = Integer.parseInt(TranseDay.substring(6,8));

        if(!leapyes && !verifyDate(lyear, lmonth, lday, "solar-"))
        {
            return "";
        }
        if(leapyes && !verifyDate(lyear, lmonth, lday, "solar+"))
        {
            return "";

        }
        int m1 = -1;
        long td = 0L;
        if(lyear != 1881)
        {
            m1 = lyear - 1882;
            for(int i = 0; i <= m1; i++)
            {
                for(int j = 0; j < 13; j++)
                    td = td + (long)kk[i * 13 + j];

                if(kk[i * 13 + 12] == 0)
                    td = td + 336L;
                else
                    td = td + 362L;
            }

        }
        m1++;
        int n2 = lmonth - 1;
        int m2 = -1;
        do
        {
            m2++;
            if(kk[m1 * 13 + m2] > 2)
            {
                td = td + 26L + (long)kk[m1 * 13 + m2];
                n2++;
                continue;
            }
            if(m2 == n2)
                break;
            td = td + 28L + (long)kk[m1 * 13 + m2];
        } while(true);
        if(leapyes)
            td = td + 28L + (long)kk[m1 * 13 + m2];
        td = td + (long)lday + 29L;
        m1 = 1880;
        do
        {
            m1++;
            boolean leap = m1 % 400 == 0 || m1 % 100 != 0 && m1 % 4 == 0;
            if(leap)
                m2 = 366;
            else
                m2 = 365;
            if(td < (long)m2)
                break;
            td = td - (long)m2;
        } while(true);
        int syear = m1;
        m[1] = m2 - 337;
        m1 = 0;
        do
        {
            m1++;
            if(td <= (long)m[m1 - 1])
                break;
            td = td - (long)m[m1 - 1];
        } while(true);
        int smonth = m1;
        int sday = (int)td;
        long y = (long)syear - 1L;
        td = ((y * 365L + y / 4L) - y / 100L) + y / 400L;
        boolean leap = syear % 400 == 0 || syear % 100 != 0 && syear % 4 == 0;
        if(leap)
            m[1] = 29;
        else
            m[1] = 28;
        for(int i = 0; i < smonth - 1; i++)
            td = td + (long)m[i];

        td = td + (long)sday;
        @SuppressWarnings("unused")
		int w = (int)(td % 7L);
        int i = (int)(td % 10L);
        i = (i + 4) % 10;
        int j = (int)(td % 12L);
        j = (j + 2) % 12;
        @SuppressWarnings("unused")
		int k1 = (lyear + 6) % 10;
        @SuppressWarnings("unused")
		int k2 = (lyear + 8) % 12;

        String sValue= String.valueOf(syear);

        if(smonth<10)
            sValue+="0";
         sValue+= String.valueOf(smonth);
         if(sday<10)
            sValue+="0";
         sValue+= String.valueOf(sday);

        String return_value = sValue ;

        return return_value;
    }
    /**
     * 양력을 음력으로
     *
     * @param       TranseDay    양력일('yyyyMMdd')
     * @return      String    처리결과 음력일
     * @throws      java.lang.Exception
     */
    public static String solarTranse(String TranseDay) throws Exception {

        // 2020.04.15 : 음력의 날자도 당해년도 음력 날자를 찾아서 주는 것으로.
        long time = System.currentTimeMillis();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd");
        java.sql.Date dd = new java.sql.Date(time);
        TranseDay = sdf.format(dd).substring(0, 4) + TranseDay.substring(4, 8) ;

        int dt[] = new int[163];
        for(int i = 0; i < 163; i++)
        {
            dt[i] = 0;
            for(int j = 0; j < 12; j++)
                switch(kk[i * 13 + j])
                {
                case 1: // '\001'
                case 3: // '\003'
                    dt[i] = dt[i] + 29;
                    break;

                case 2: // '\002'
                case 4: // '\004'
                    dt[i] = dt[i] + 30;
                    break;
                }

            switch(kk[i * 13 + 12])

            {
            case 1: // '\001'
            case 3: // '\003'
                dt[i] = dt[i] + 29;
                break;

            case 2: // '\002'
            case 4: // '\004'
                dt[i] = dt[i] + 30;
                break;
            }
        }
        int syear = Integer.parseInt(TranseDay.substring(0,4));
        int smonth = Integer.parseInt(TranseDay.substring(4,6));
        int sday = Integer.parseInt(TranseDay.substring(6,8));

        long k11 = syear - 1;
        long td2 = ((k11 * 365L + k11 / 4L) - k11 / 100L) + k11 / 400L;
        boolean ll = syear % 400 == 0 || syear % 100 != 0 && syear % 4 == 0;
        if(ll)
            m[1] = 29;
        else
            m[1] = 28;

        if(!verifyDate(syear, smonth, sday, "lunar"))
        {
            throw new Exception("Date Error [" + syear + smonth + sday + "]");

        }
        
        for(int i = 0; i < smonth - 1; i++)
            td2 = td2 + (long)m[i];

        td2 = td2 + (long)sday;


        long td = (td2 - 0xa7a5eL) + 1L;
        long td0 = dt[0];
        int i=0;
        for(i = 0; i < 163; i++)
        {
            if(td <= td0)
                break;
            td0 = td0 + (long)dt[i + 1];
        }

        int lyear = i + 1881;
        td0 = td0 - (long)dt[i];
        td = td - td0;
        int jcount=0;
        if(kk[i * 13 + 12] != 0)
            jcount = 13;
        else
            jcount = 12;
        int m2 = 0;
        int j=0;
        int m1;
        for(j = 0; j < jcount; j++)
        {
            if(kk[i * 13 + j] <= 2)
                m2++;
            if(kk[i * 13 + j] <= 2)
                m1 = kk[i * 13 + j] + 28;
            else
                m1 = kk[i * 13 + j] + 26;
            if(td <= (long)m1)
                break;
            td = td - (long)m1;
        }

        @SuppressWarnings("unused")
		int m0 = j;
        long lmonth = m2;
        int lday = (int)td;
        @SuppressWarnings("unused")
		int w = (int)(td2 % 7L);
        i = (int)((td2 + 4L) % 10L);
        j = (int)((td2 + 2L) % 12L);
        @SuppressWarnings("unused")
		int i1 = (lyear + 6) % 10;
        @SuppressWarnings("unused")
		int j1 = (lyear + 8) % 12;
        String sValue= String.valueOf(lyear);

        if(lmonth<10)
            sValue+="0";
         sValue+= String.valueOf(lmonth);
         if(lday<10)
            sValue+="0";
         sValue+= String.valueOf(lday);
         
        String return_value = sValue ;

        return return_value;
    }

    private static boolean verifyDate(int k, int l, int l1, String s)
    {
        if(k < 1881 || k > 2043 || l < 1 || l > 12)
            return false;
        if(s.equals("lunar") && l1 > m[l - 1])
            return false;
        if(s.equals("solar+"))
        {
            if(kk[(k - 1881) * 13 + 12] < 1)
                return false;
            if(kk[(k - 1881) * 13 + l] < 3)
                return false;
            if(kk[(k - 1881) * 13 + l] + 26 < l1)
                return false;
        }
        if(s.equals("solar-"))
        {
            int j = l - 1;
            for(int i = 1; i <= 12; i++)
                if(kk[((k - 1881) * 13 + i) - 1] > 2)
                    j++;

            if(l1 > kk[(k - 1881) * 13 + j] + 28)
                return false;
        }
        return true;
    }
	public static String[] getYuk() {
		return yuk;
	}
	public static String[] getGap() {
		return gap;
	}
	public static String[] getDdi() {
		return ddi;
	}
	public static String[] getWeek() {
		return week;
	}
	public static void setInit_date(Date init_date) {
		LunarTranser.init_date = init_date;
	}
	public static Date getInit_date() {
		return init_date;
	}
	public static String getErrmsg() {
		return errMsg;
	}   
}

그 예전 부터 지금까지 잘 사용하고 있으니, 소스의 변환 능력은 검증이 되었다고 볼 수 있을 것 같다.

 

사용하는 부분은 다음과 같다.   먼저 음력을 양력으로 변환 하기

LunarTranse(String TranseDay, boolean leapyes)

기준일자(yyyyMMdd : 8자리 숫자) 와 윤달 여부만 전달 하면  양력 으로 변환된 날자가 돌아온다.

 

다음은 양력을 음력으로 변환하기

solarTranse(String TranseDay)

기준일자(yyyyMMdd : 8자리 숫자)을 전달하면 음력으로 변환된 날자가 돌아온다.

 

이런 기능의 사용예시는 앞에서 기술한 바와 같이 앱으로 활용하고 있다.

 

https://play.google.com/store/apps/details?id=com.nari.lunar3google 

 

음력달력, 일정관리 - Google Play 앱

음력을 양력으로 변환하여 관리 합니다. 양력은 음력으로 관리 합니다.

play.google.com

 

반응형

이전 포스팅에서 제주버스의 정보를 수집했다. 

https://billcorea.tistory.com/111

 

이제 그 정보를 나의 앱에 넣는 작업을 해 봐야겠다.  일단은 데이터를 저장할 table 을 구성해 보았다.  뭐 말그대로 앞전 포스팅에서 작성한 class 중에서 item 이 들어 있는 class 구조를 그대로 적용해 보면 될 것 같다.

 

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DBHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "opdGangDB";
    private static final int DB_Ver = 4;
    private static final String TAG = "DBHelper";

    public DBHelper(Context context) {
        super(context, DB_NAME, null, DB_Ver);
    }

    /**
     * aClassCode, bClassCode, cClassCode : 코드 분류 1,2,3 차
     * cntData : 위치별-상호별 중복 건수
     * infoData : 상세 정보 y,x,place_name 으로 cntData 와 연계
     * @param db
     */
    @Override
    public void onCreate(SQLiteDatabase db) {

        StringBuffer sb = new StringBuffer();
        sb.append("create table ClassCode");
        sb.append("( _id integer primary key autoincrement, ");
        sb.append("  classNameA text, ");
        sb.append("  classNameB text, ");
        sb.append("  classNameC text  ");
        sb.append(" ) ");
        db.execSQL(sb.toString());

        sb = new StringBuffer();
        sb.append("create table cntData");
        sb.append("( _id integer primary key autoincrement, ");
        sb.append("  y text, ");
        sb.append("  x text, ");
        sb.append("  place_name text, ");
        sb.append("  atCnt number ");
        sb.append(" ) ");
        db.execSQL(sb.toString());

        sb = new StringBuffer();
        sb.append("create table infoData");
        sb.append("( _id integer primary key autoincrement, ");
        sb.append("  y text, ");
        sb.append("  x text, ");
        sb.append("  address_name text, ");
        sb.append("  category_group_code text, ");
        sb.append("  category_group_name text, ");
        sb.append("  category_name text, ");
        sb.append("  distance text, ");
        sb.append("  id text, ");
        sb.append("  phone text, ");
        sb.append("  place_name text, ");
        sb.append("  place_url text, ");
        sb.append("  road_address_name text, ");
        sb.append("  url text, ");
        sb.append("  regTime text, ");
        sb.append("  likeCnt text, ");
        sb.append("  unlikeCnt text ");
        sb.append(" ) ");
        db.execSQL(sb.toString());

        /**
         *   제주 버스 정류소 정보 수집 2021.12.20 ~
         */
        sb = new StringBuffer();
        sb.append("create table stationItem ");
        sb.append("( _id integer primary key autoincrement, ");
        sb.append(" dirTp text, ");
        sb.append(" govNm text, ");
        sb.append(" localX real, ");
        sb.append(" localY real, ");
        sb.append(" mobiNum text, ");
        sb.append(" stationId text, ");
        sb.append(" stationNm text, ");
        sb.append(" upd text, ");
        sb.append(" useYn text ");
        sb.append(" ) ");
        db.execSQL(sb.toString());
    }

    /**
     * @param db
     * @param oldVersion
     * @param newVersion
     */

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        StringBuffer sb = new StringBuffer();

        Log.e(TAG, "newVersion=" + newVersion) ;
        switch (newVersion) {
            case 4:

                sb = new StringBuffer();
                sb.append("create table stationItem ");
                sb.append("( _id integer primary key autoincrement, ");
                sb.append(" dirTp text, ");
                sb.append(" govNm text, ");
                sb.append(" localX real, ");
                sb.append(" localY real, ");
                sb.append(" mobiNum text, ");
                sb.append(" stationId text, ");
                sb.append(" stationNm text, ");
                sb.append(" upd text, ");
                sb.append(" useYn text ");
                sb.append(" ) ");
                db.execSQL(sb.toString());

                break;
            case 3:
                db.execSQL("alter table infoData add column likeCnt text ");
                db.execSQL("alter table infoData add column unlikeCnt text ");
                break;
        }

    }
}

sqlite 에서 데이터를 구성해 앱을 만들다 보면 나중에 추가 하거나 구조를 변경 하게 되는 경우가 있는데,  그 때 마다 data을 다 지우고 다시 만들면 사용자도 힘들고, 개발자도 힘들고 ... 그래서 db을 생성할 때 버전에 따라서 변하게 하는 것이 좋을 듯 하다.  그러면 이전 앱을 설치한 사용자도 upgrade 되면 새로 데이터를 넣지 않아도 되기 때문이다. 

 

이 앱은 벌써 데이터 구조를 3, 4 버전까지 늘렸다. 2 버전은 어디 갔는 지 모르겠지만... (사실은 한번 잘못 빌드를 했다가.. 실폐를 해서 ) 아무튼 새로 버전을 받더라도 사용자는 아무런 의심 없이 사용하게 될 것이다.

 

이번에는 이 데이터를 불러서 사용할 것들을 정리해 봐야겠다.

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.billcoreatech.opdgang1127.JejuBusInfo.StationItemBean;
import com.billcoreatech.opdgang1127.JejuFD6.JejuFD6infoBean;
import com.billcoreatech.opdgang1127.Utils.StringUtils;

public class DBHandler extends RuntimeException {

    DBHelper helper ;
    SQLiteDatabase db ;
    String TAG = "DBHandler";

    public DBHandler(Context context) {
        helper = new DBHelper(context) ;
        db = helper.getWritableDatabase() ;
    }

    public static DBHandler open (Context ctx) throws SQLException {
        DBHandler handler = new DBHandler(ctx) ;
        return handler ;
    }

    public void close() {
        helper.close();
    }

   ...

    /**
     * 제주 버스 정류소 정보 2021.12.20 ~
     * @param station
     * @return
     */
    public long appendBusStation(StationItemBean station) {
        long result = 0 ;
        Cursor rs = selectBusStation(station.getStationId());
        if (rs.moveToNext()) {
            result = updateBusStation(station);
        } else {
            result = insertBusStation(station);
        }
        rs.close();
        return result ;
    }

    /**
     * 제주 버스 정류소 정보 2021.12.20 ~
     * @param busStation
     * @return
     */
    public Cursor selectBusStation(String busStation) {
        StringBuffer sb = new StringBuffer();
        sb.append("select * from stationItem ");
        if (!"".equals(busStation)) {
            sb.append(" where stationId = '" + busStation.trim() + "' ");
        }
        return  db.rawQuery(sb.toString(), null);
    }

    /**
     * 주변 정류소 찾기
     * @param x : 경도
     * @param y : 위도
     * @param roundValue : 주변범위 m
     * @return
     */
    public Cursor selectBusStationArea(double x, double y, int roundValue) {
        double x1 = x - StringUtils.LongitudeInDifference(y, roundValue);
        double x2 = x + StringUtils.LongitudeInDifference(y, roundValue);
        double y1 = y - StringUtils.LatitudeInDifference(roundValue) ;
        double y2 = y + StringUtils.LatitudeInDifference(roundValue) ;
        StringBuffer sb = new StringBuffer();
        sb.append("select * from stationItem ");
        sb.append(" where (localX >= " + x1 + " and localX <= " + x2 + ") ");
        sb.append("   and (localY >= " + y1 + " and localY <= " + y2 + ") ");
        sb.append("   and useYn = 'Y' ");
        Log.e(TAG, sb.toString());
        return  db.rawQuery(sb.toString(), null);
    }

    /**
     * 제주 버스 정류소 정보 2021.12.20 ~
     * @param station
     * @return
     */
    public long insertBusStation(StationItemBean station) {
        ContentValues values = new ContentValues();
        values.put("dirTp", station.getDirTp());
        values.put("govNm", station.getGovNm());
        values.put("localX", station.getLocalX());
        values.put("localY", station.getLocalY());
        values.put("mobiNum", station.getMobiNum());
        values.put("stationId", station.getStationId());
        values.put("stationNM", station.getStationNm());
        values.put("upd", station.getUpd()) ;
        values.put("useYn", station.getUseYn()) ;

        return db.insert("stationItem", null, values) ;
    }

    /**
     * 제주 버스 정류소 정보 2021.12.20 ~
     * @param station
     * @return
     */
    public long updateBusStation(StationItemBean station) {
        ContentValues values = new ContentValues();
        values.put("dirTp", station.getDirTp());
        values.put("govNm", station.getGovNm());
        values.put("localX", station.getLocalX());
        values.put("localY", station.getLocalY());
        values.put("mobiNum", station.getMobiNum());
        values.put("stationNM", station.getStationNm());
        values.put("upd", station.getUpd()) ;
        values.put("useYn", station.getUseYn()) ;

        return db.update("stationItem", values, "stationId = '" + station.getStationId() + "' ", null) ;
    }

}

이렇게 insert, update, select 을 구성했고, append 도 추가 했다. append 는 새로 데이터를 받아온 다음 그것을 저장하기 위해서, 

 

이제 데이터를 받아와서 저장하는 구현을 해 봐야지.

 

   @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {

            case R.id.actionGetBusStation:

                fd6Binding = Updatejejufd6infoViewBinding.inflate(getLayoutInflater());
                fd6Binding.adView.loadAd(adRequest);
                AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this, R.style.ThemeDialog)
                        .setTitle(getString(R.string.titleUpdateBusStation) + "(last:" + sp.getString("lastUpdateBusStation", "1970-01-01") + ")")
                        .setView(fd6Binding.getRoot())
                        .setPositiveButton(getString(R.string.OK), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                doGetBusStation();
                            }
                        })
                        .setNegativeButton(getString(R.string.CLOSE), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        });
                AlertDialog dialog1 = builder1.create();
                dialog1.show();

                break;


        }
        return super.onOptionsItemSelected(item);
    }

option menu 를 선택 하면 아래 처럼 데이터를 수신 받고 그것을 이용해서 저장하는 for 문을 구성 하였다.

 

   /**
     * 2021.12.20 제주 버스 정류소 정보 수집 기능 추가
     */
    private void doGetBusStation() {

        binding.baseProgressBar.setVisibility(View.VISIBLE);
        retrofit = new Retrofit.Builder()
                .baseUrl(RetrofitApi.baseURL)
                .client(new OkHttpClient())
                .addConverterFactory(SimpleXmlConverterFactory.create())
                .build();
        service = retrofit.create(RetrofitApi.class);
        String lastUpdateDate = sp.getString("lastUpdateBusStation", "1970-01-01");
        service.getStationInfo(lastUpdateDate).enqueue(new Callback<StationBean>() {
            @Override
            public void onResponse(Call<StationBean> call, Response<StationBean> response) {
                Log.e(TAG, "response=" + response.code() + " Total="  + response.body().getBodyClass().getTotalCount()
                          + "\n" + response.message());
                if (!"0".equals(response.body().getBodyClass().getTotalCount())) {
                    dbHandler = DBHandler.open(getApplicationContext());
                    for (StationItemBean item : response.body().getBodyClass().getItems()) {
                        Log.e(TAG, item.getStationNm());
                        long cnt = dbHandler.appendBusStation(item);
                        Log.e(TAG, cnt + " " + item.getStationNm());
                    }
                    dbHandler.close();
                    editor = sp.edit();
                    editor.putString("lastUpdateBusStation", StringUtils.getToday());
                    editor.commit();
                }
                binding.baseProgressBar.setVisibility(View.GONE);
            }

            @Override
            public void onFailure(Call<StationBean> call, Throwable t) {
                Log.e(TAG, "ERROR=" + t.toString()) ;
            }
        });

    }

 저번과 달라진 부분은 service 호출할 때 최종 변경일자를 구해서 전달하도록 수정한 부분이다. 그래서 retrofit api 에서도 다음과 같이 날자를 받아서 파라미터로 전달 하도록 구성을 변경 하였다. 

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface RetrofitApi {
    String baseURL = "http://busopen.jeju.go.kr";
    String getStation = "/OpenAPI/service/bis/Station";

    @GET(getStation)
    Call<StationBean> getStationInfo(@Query(value="last") String lastUpdate);
}

이렇게 하면 저번 포스팅에서 보았던 제주버스api 에 최종 변경된 정보만 수집하는 모양으로 작업을 할 수 있다. 

이제 가져온 데이터가 앱에서 어떻게 활용이 되는 지 잠시 보도록 하겠다. 

 

버스 정류소가 표시된 지도

이렇게 앱에 버스 정류소를 표시할 수 있는 자료가 만들어 졌다.  다음은 뭐 해야하지 ?  내가 있는 위치에서 저 버스 정류소까지 가는 방법을 연구해 보아야 겠다.

 

그럼 오늘도 즐~ 코딩...

반응형

앱에서 지원하고 싶은 것중 우선 나의 주변에 버스 정류소를 찾는다. 어떻게 찾을까 ?   모든 데이터는 data.go.kr 공공데이터 포털을 중심으로 ... 찾아보니 제주도에서 제공하는 버스 정보가 있다.

 

http://www.jeju.go.kr/help/open.htm?page=3&act=view&seq=967654 

다만, 가이드의 정보를 기준으로 보면 http:// 으로 시작하는 기본url 과 xml 형식으로 자료를 전송한다는 것이 조금 예전 방식인 것 같은 생각이 들었다.  

 

이제 앱에 retrofit 통신을 하기 위한 준비를 해 보자.  gradle 파일에 수정을 

    // 데이터 주고 받기
    implementation 'com.squareup.retrofit2:retrofit:2.7.2'
    implementation 'com.squareup.retrofit2:converter-simplexml:2.1.0'

retrofit 과 xml 파싱을 위해서 추가 했다.

 

다음은 manifest 에 internet 접속을 위한 권한 등록

 

    <uses-permission android:name="android.permission.INTERNET" />

이제 준비는 되었고.  그럼 데이터를 가져오기 위해서 일단 open api 가 제공하는 데이터 구조를 확인해 보아야겠다.

 

xml 샘플
xml 마지막 부분

데이터는 이렇게 조회가 되고 있고, open api 가이드의 내용도 이와 같다.  그래서 일단은 데이터를 받아올 class 을 만들어 보았다. 

 

맨 먼저 제일 바깥쪽에 구성되는 class 부터

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;


@Root(name="response", strict = false)
public class StationBean {
    @Element(name="header")
    HeaderClass headerClass;
    @Element(name="body")
    BodyClass bodyClass ;

    public HeaderClass getHeaderClass() {
        return headerClass;
    }

    public BodyClass getBodyClass() {
        return bodyClass;
    }

    public void setHeaderClass(HeaderClass headerClass) {
        this.headerClass = headerClass;
    }

    public void setBodyClass(BodyClass bodyClass) {
        this.bodyClass = bodyClass;
    }
}

Root 는 response 로 구성 되며, 그 안에는 header 와 body 가 들어간다. 

다음은 header class

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name="header", strict = false)
public class HeaderClass {
    @Element(name="resultCode")
    String resultCode;
    @Element(name="resultMsg")
    String resultMsg ;

    public String getResultCode() {
        return resultCode;
    }

    public String getResultMsg() {
        return resultMsg;
    }

    public void setResultCode(String resultCode) {
        this.resultCode = resultCode;
    }

    public void setResultMsg(String resultMsg) {
        this.resultMsg = resultMsg;
    }
}

header 에는 resultCode, 와 resultMsg 만 들어 있고, 실제 데이터는 body 에 들어간다.  다음은 body class

import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;
import org.simpleframework.xml.Root;

import java.util.ArrayList;

@Root(name="body", strict = false)
public class BodyClass {
    @ElementList(entry = "items")
    ArrayList<ItemClass> items ;
    @Element(name="numOfRows")
    String numOfRows ;
    @Element(name="pageNo")
    String pageNo ;
    @Element(name="totalCount")
    String totalCount ;

    public ArrayList<ItemClass> getItems() {
        return items;
    }

    public String getNumOfRows() {
        return numOfRows;
    }

    public String getPageNo() {
        return pageNo;
    }

    public String getTotalCount() {
        return totalCount;
    }

    public void setItems(ArrayList<ItemClass> items) {
        this.items = items;
    }

    public void setNumOfRows(String numOfRows) {
        this.numOfRows = numOfRows;
    }

    public void setPageNo(String pageNo) {
        this.pageNo = pageNo;
    }

    public void setTotalCount(String totalCount) {
        this.totalCount = totalCount;
    }
}

body 에는 데이터가 들어가는 items 와 건수등을 표시하는 데이터 들이 들어 있는데, 구현하면서 조금 방황(?)한 부분은 ArrayList 로 표시하는 items 에 대한 구현을 어떻게 해야 하는 가에 대한 부분 이었다.  gson 으로 파싱을 할 때는 그런거 없이 수월했는데, xml 형식에서는 EntryList 가 표현이 되도록 구현을 해야 되는 것이었다.

 

다음은 item이 들어가는 item class 

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

@Root(name="item", strict = false)
public class ItemClass {
    @Element(name="dirTp")
    String dirTp ;
    @Element(name="govNm")
    String govNm;
    @Element(name="localX")
    double localX ;
    @Element(name="localY")
    double localY ;
    @Element(name="mobiNum")
    String mobiNum ;
    @Element(name="stationId")
    String stationId ;
    @Element(name="stationNm")
    String stationNm ;
    @Element(name="upd")
    String upd ;
    @Element(name="useYn")
    String useYn ;

    public double getLocalX() {
        return localX;
    }

    public double getLocalY() {
        return localY;
    }

    public String getMobiNum() {
        return mobiNum;
    }

    public String getDirTp() {
        return dirTp;
    }

    public String getGovNm() {
        return govNm;
    }

    public String getStationId() {
        return stationId;
    }

    public String getStationNm() {
        return stationNm;
    }

    public String getUpd() {
        return upd;
    }

    public String getUseYn() {
        return useYn;
    }

    public void setDirTp(String dirTp) {
        this.dirTp = dirTp;
    }

    public void setGovNm(String govNm) {
        this.govNm = govNm;
    }

    public void setLocalX(double localX) {
        this.localX = localX;
    }

    public void setLocalY(double localY) {
        this.localY = localY;
    }

    public void setMobiNum(String mobiNum) {
        this.mobiNum = mobiNum;
    }

    public void setStationId(String stationId) {
        this.stationId = stationId;
    }

    public void setStationNm(String stationNm) {
        this.stationNm = stationNm;
    }

    public void setUpd(String upd) {
        this.upd = upd;
    }

    public void setUseYn(String useYn) {
        this.useYn = useYn;
    }
}

이렇게 구현 하면 데이터를 받아올 준비는 되었다.  이제 interface 을 구현해 볼 차례 인데,    openapi 에는 호출시 파라미터를 last 와 serviceKey 를 받는다고 되어 있지만, 현재( 2021.12.19 )에는 아무것도 전달하지 않아도 되고, last 뒤에 날자만 전달해도 된다. last 을 넣어보내면 최근 업데이트 된 정보만 받아오는 것으로 확인이 되었다.  다만, 나의 앱에서는 정보가 처음이라, 전체 데이터를 받기 위해서 아무것도 파라미터로 사용하지 않다. 

 

import retrofit2.Call;
import retrofit2.http.GET;

public interface RetrofitApi {
    String baseURL = "http://busopen.jeju.go.kr";
    String getStation = "/OpenAPI/service/bis/Station";

    @GET(getStation)
    Call<StationBean> getStationInfo();
}

 interface class 는 이렇게 구성을 했다. query 가 없어서 아무것도 전달하지는 않았다.

이번에는 activity 에서 호출을 해 보도록 하겠다.

 

public class MainActivity extends AppCompatActivity {

   ...
   
    Retrofit retrofit ;
    RetrofitApi service ;
    
    ...
    
    
	private void doGetBusStation() {

        retrofit = new Retrofit.Builder()
                .baseUrl(RetrofitApi.baseURL)
                .client(new OkHttpClient())
                .addConverterFactory(SimpleXmlConverterFactory.create())
                .build();
        service = retrofit.create(RetrofitApi.class);

        service.getStationInfo().enqueue(new Callback<StationBean>() {
            @Override
            public void onResponse(Call<StationBean> call, Response<StationBean> response) {
                Log.e(TAG, "response=" + response.code() + " Total="  + response.body().getBodyClass().getTotalCount());
                for(ItemClass item : response.body().getBodyClass().getItems()) {
                    Log.e(TAG, item.getStationNm());
                }
            }

            @Override
            public void onFailure(Call<StationBean> call, Throwable t) {
                Log.e(TAG, "ERROR=" + t.toString()) ;
            }
        });

    }
    
    
    ...
    
    
}

아직 데이터를 받아와서 어떻게 하고자 하는 지 결정을 하지 못했다. 일단, 데이터가 들어 오는 것은 확인을 하였다.  이 구현을 하는데,  CLEARTEXT communication to XXXX not permitted by network security policy 을 만나게 되면, 어떻게 할 것인가를 고민하지 말고 다음을 따라해 보면 된다. 이유는 http:// 으로 된 주소에 통신을 시도하기 때문에 발생하는 보안 문제인데,  나 앱이 모든 호출에서 http:// 로 할 것이 아니기 때문에 특정 url 만 http 로 호출할 것이라고 등록을 해 주면 된다. 

 

먼저 xml 파일을 하나 만든다.  res/xml/network_config.xml 이라고 .. 그안에는 다음과 같이 넣어 준다. 

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">busopen.jeju.go.kr</domain>
    </domain-config>
</network-security-config>

특정 주소는 http 로 통신을 하겠다는 것이다.  보안정책 때문에 누군가 싫어할지 모르지만.

그리고 다음은 manifest 에 다음을 추가해 준다. 

 

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_info_logo"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_info_logo_round"
        android:supportsRtl="true"
        android:networkSecurityConfig="@xml/network_config"

networkSecurityConfig 을 추가해 주면 끝.

 

응답 로그

제주도에는 4358개이 정류소 정보가 있나 보다.  다음엔 이것을 저장해서 데이터로 활용해 보도록 하겠다.

 

반응형

앱을 하나 만들다 보니 별점 주기를 해 보고 싶은 생각이 들었다.  그래서 찾아보니 이렇게 있네 ?

Ratingbar ... 화면에 배치를 해 보자.

 

RatingBar 이미지

이제 설정을 해 보자 먼저 몇점까지를 주게 할 것인가 ? 나는 5점 만점으로 정했다. 

 

numStars : 몇점 만점으로 할 것인지 

stepSize : 몇점 단위로 할 것인지 

rating : 선택하기전 처음 점수는 

 

한가지 주의하고 가야할 것이 있다면 layout_width 을 wrap_content 로 해 주어야 한다는 것이다 .

match_parent 을 했을 때는 화면에 표시가능한 만큼 별이 늘어나는 현상이 발생하기 떄문이다. 난 분명 5점 만점으로 하고 싶었지만, 화면이 크기에 따라 별이 늘어나 보인다. step 도 적용이 잘 되지 않는 현상이 생기게 된다.

 

 

 

 

그럼 이제 실제로 적용 되어 움직이는 모양을 확인해 보기로 하겠다.

 

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

실행을 해 보면 이렇게 선택하는 바에 따라서 동작을 하게 되는 것이였다.  그런데, 난 이걸 사용할 수 가 없다. 데이터를 실시간으로 동기화를 해야 하기 때문에...

 

오늘은 동작이 어떻게 되는지만, 알아 보는 것으로 만족하기로 했다.

 

반응형

앱을 구현 하다 보면 알림을 보여 주어야 하는 경우가 있게 된다. 그럴때 마다 쉽게 했던 방식은 Toast 알림을 이용하는 방식으로 구현하는 것이였다.

 

 

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

Toast 의 경우의 위 영상에서 20초 이후 구간에 보이는 화면 하단에 잠시 나오는 알림창이다.  코드 구현은 다음과 같이...

                Toast.makeText(context.getApplicationContext(), context.getString(R.string.msgUpdateCompleted), Toast.LENGTH_SHORT).show();

파라미터로 넣어주어야 하는 것은 context, 문자열, Toast의 길이 이렇게 3가지가 전달 되면 구현이 가능 하다. 

 

 

다음은 Snackbar 인데, 이것은 알림 나왔다가 사라는지는 구현도 가능하겠지만, action 을 넣어 주면 버튼 클릭이 끝나면 동작을 마무리 하도록 구현해 볼 수 있다.

 

 

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

위 영상의 예시처럼 화면에 알림을 띄워주고 사용자가 click 을 할 때 까지 기다리는 동작을 구현해 볼 수 있다.

코드 구현은 다음과 같이 해 볼 수 있다.

        Snackbar.make(
                ((Activity) context).findViewById(android.R.id.content),
                context.getString(mainTextStringId),
                Snackbar.LENGTH_INDEFINITE).setAction(context.getString(actionStringId), listener).show();

첫번째 파라미터는 알림을 담을 content 인데, android.R.id.content 는 안드로이드가 제공하고 있는 일반적인 content 을 담을 수 있는 것이락 생각하면 쉬을 것 같다. 다음은 화면에 보여줄 문자열이고, 그 다음은 action 을 위한 버튼에서 보여줄 문자, 마지막으로는 해당 action 을 클릭했을 때 처리할 action listener 을 넘겨 주면 된다. 

 

이것으로 알림 방법에 대해 간략하게 알아보았다.

 

반응형

앱을 만들다 보면 앱에 광고에 넣고 싶다. 그런데 화면에는 리사이클뷰가 들어있는데 그안에는 어떻게 넣을 것인가 ? 그것을 찾다 보니...

 

https://github.com/googleads/googleads-mobile-android-examples

 

GitHub - googleads/googleads-mobile-android-examples: googleads-mobile-android

googleads-mobile-android. Contribute to googleads/googleads-mobile-android-examples development by creating an account on GitHub.

github.com

 

여기 까지 찾아갔다.  그 안을 찾다보니, BannerRecyclerViewExample 이라는 프로젝트 파일을 찾을 수 있었다. 이 예제의 내용은 menu(식당에서 말하는) item 을 넣은 recycleview 에 banner 광고를 추가하는 식으로 예제를 보여 주고 있다. 

 

물론 나도 recycleview 에 데이터를 넣은 다음 그안에 banner 광고를 추가할 생각이니 대략 다름이 없게 되는 것이다.

admob 광고를 설정하는 것은 이전 포스팅을 참고해서 하고...

 

https://billcorea.tistory.com/57

 

안드로이드 앱 만들기 도전 4일차 admob 달아 보기

오늘은 내가 만든 앱에 광고를 달아보자... admob 으로 다가... 그래서 먼저 할 꺼는 admob 에 로그인하고 앱 만들기를 클릭하기 그럼 다음 그림과 같이 나옴.  나의 앱은 안드로이드 버전이고, 아직

billcorea.tistory.com

 

일단 layout 에 recycleview 을 넣어 보자.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="30"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/base_progressBar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/backgroud_blueline"
        android:clickable="true"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/msgWaitForSecond"/>

        <ProgressBar
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminateDrawable="@drawable/circle_progress"
            android:indeterminateDuration="1000" />
    </LinearLayout>

    <Spinner
        android:id="@+id/spAclass"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:theme="@style/SpinnerTheme" />

    <Spinner
        android:id="@+id/spBclass"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:theme="@style/SpinnerTheme" />

    <Spinner
        android:id="@+id/spCclass"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:theme="@style/SpinnerTheme" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:orientation="horizontal"
        android:weightSum="10">

        <EditText
            android:id="@+id/editSearchKey"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="8"
            android:ems="10"
            android:hint="@string/msgSearchKey"
            android:inputType="textPersonName" />

        <ImageButton
            android:id="@+id/btnSearch"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            app:srcCompat="@drawable/ic_baseline_search_24" />

        <ImageButton
            android:id="@+id/btnMaps"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            app:srcCompat="@drawable/ic_baseline_map_24" />
    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/listData"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="22" />
</LinearLayout>

이렇게 디자인된 화면을 미리 보기를 해 보면

 

layout 미리보기

그 다음은 recycleview 을 그려낼 화면 adapter 을 만들어 보면 다음과 같이 구현이 될 수 있다.

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.billcoreatech.opdgang1127.MainActivity;
import com.billcoreatech.opdgang1127.R;
import com.billcoreatech.opdgang1127.databinding.BannerAdContainerBinding;
import com.billcoreatech.opdgang1127.databinding.Jejufd6infoViewBinding;
import com.google.android.gms.ads.AdView;

import java.util.List;

/**
 * {@link RecyclerAdMobAdapter} 클래스.
 * <p>어댑터는 {@link ViewHolder}의 항목에 대한 액세스를 제공합니다.
 * 또는 {@link AdViewHolder}.</p>
 */
public class RecyclerAdMobAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    // 데이터 항목 보기 유형입니다.
    private static final int DATA_ITEM_VIEW_TYPE = 0;

    // 배너 광고 보기 유형입니다.
    private static final int BANNER_AD_VIEW_TYPE = 1;

    // 활동의 컨텍스트입니다.
    private final Context context;

    // The list of banner ads and menu items.
    private final List<Object> recyclerViewItems;

    // data item layout
    Jejufd6infoViewBinding binding ;
    // banner ad layout
    BannerAdContainerBinding adBinding ;
    String TAG = "RecyclerAdMobAdapter";

    /**
     * 이 예제 앱의 경우 recyclerViewItems 목록에는
     * {@link JejuFD6infoBean} 및 {@link AdView} 유형.
     */
    public RecyclerAdMobAdapter(Context context, List<Object> recyclerViewItems) {
        this.context = context;
        this.recyclerViewItems = recyclerViewItems;
    }

    /**
     * {@link ViewHolder} 클래스.
     * 메뉴 항목 보기의 각 보기에 대한 참조를 제공합니다.
     */
    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView placeName ;
        TextView categoryName ;
        TextView phone ;
        TextView roadAddressName ;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            placeName = binding.placeName ;
            categoryName = binding.categoryName;
            phone = binding.phone;
            roadAddressName = binding.roadAddressName;

            // item click 을 활용 하기 위해서
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override public void onClick(View v) {
                    int pos = getAdapterPosition() ;
                    if (pos != RecyclerView.NO_POSITION) {
                        // 리스너 객체의 메서드 호출.
                        if (mListener != null) {
                            mListener.onItemClick(v, pos) ;
                        }
                    }
                }
            });
        }
    }

    /**
     * {@link AdViewHolder} 클래스입니다.
     */
    public class AdViewHolder extends RecyclerView.ViewHolder {

        AdViewHolder(View view) {
            super(view);
        }
    }

    /**
     * 데이터의 갯수를 구하기
     * @return
     */
    @Override
    public int getItemCount() {
        return recyclerViewItems.size();
    }

    /**
     * 주어진 위치에 대한 보기 유형을 결정합니다.
     *
     */
    @Override
    public int getItemViewType(int position) {
        return (position % MainActivity.ITEMS_PER_AD == 0) ? BANNER_AD_VIEW_TYPE
                : DATA_ITEM_VIEW_TYPE;
    }

    /**
     * 메뉴 항목 보기 또는 배너 광고 보기에 대한 새 보기 만들기
     * viewType을 기반으로 합니다. 이 메소드는 레이아웃 관리자에 의해 호출됩니다.
     */
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        switch (viewType) {
            case DATA_ITEM_VIEW_TYPE:
                RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                binding = Jejufd6infoViewBinding.inflate((LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE));
                View view = binding.getRoot() ;
                view.setLayoutParams(lp);
                return new ViewHolder(view);
            case BANNER_AD_VIEW_TYPE:
                // fall through
            default:
                adBinding = BannerAdContainerBinding.inflate((LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE));
                View bannerLayoutView = adBinding.getRoot();
                return new AdViewHolder(bannerLayoutView);
        }
    }

    /**
     * 메뉴 항목 보기를 구성하는 보기의 내용을 대체하고
     * 배너 광고 보기. 이 메소드는 레이아웃 관리자에 의해 호출됩니다.
     */
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        int viewType = getItemViewType(position);
        switch (viewType) {
            case DATA_ITEM_VIEW_TYPE:
                ViewHolder viewHolder = (ViewHolder) holder;
                JejuFD6infoBean dataBean = (JejuFD6infoBean) recyclerViewItems.get(position);
                viewHolder.categoryName.setText(dataBean.getCategory_name());
                viewHolder.phone.setText(dataBean.getPhone());
                viewHolder.placeName.setText(dataBean.getPlace_name());
                viewHolder.roadAddressName.setText(dataBean.getRoad_address_name());
                break;
            case BANNER_AD_VIEW_TYPE:
                // 실패로 끝나다
            default:
                AdViewHolder bannerHolder = (AdViewHolder) holder;
                AdView adView = (AdView) recyclerViewItems.get(position);
                ViewGroup adCardView = (ViewGroup) bannerHolder.itemView;
//                RecyclerView에 의해 재활용된 AdViewHolder는 다를 수 있습니다.
//                이전에 이 위치에 사용된 것보다 인스턴스입니다. 지우다
//                다른 하위 보기의 AdViewHolder
//                AdView가 연결되어 있고 이 위치에 대한 AdView가
//                이미 다른 재활용 AdViewHolder의 상위 항목이 있습니다.

                if (adCardView.getChildCount() > 0) {
                    adCardView.removeAllViews();
                }
                if (adView.getParent() != null) {
                    ((ViewGroup) adView.getParent()).removeView(adView);
                }

                // Add the banner ad to the ad view.
                adCardView.addView(adView);
        }
    }

    // 리스너 객체 참조를 저장하는 변수
    private RecyclerAdMobAdapter.OnItemClickListener mListener = null ;

    // OnItemClickListener 리스너 객체 참조를 어댑터에 전달하는 메서드
    public void setOnItemClickListener(RecyclerAdMobAdapter.OnItemClickListener listener) {
        this.mListener = listener ;
    }

    public interface OnItemClickListener {
        void onItemClick(View v, int position) ;
    }

}

앞에서 말했던 예제 소스에서 recycleview adapter class 을 복사해서 내가 필요한 부분으로 수정을 진행 했다. 

이제까지 구현했던 adapter class 와 다른 것은 viewHolder 을 2가지로 구성해서 한가지는 화면에 보여줄 데이터가 표시되는 viewHolder 을 만들고, 또 하나는 광고 banner 가 들어가는 adViewHolder 을 구현하는 것이다. 

 

그리고 viewType 을 이용해서 각각 뷰에 필요한 데이터를 넣어주는 방식으로 구현이 되는 것을 볼 수 있었다.  추가적으로 item 을 클릭했을 때 처리를 하기 위해서 onItemClickListener 을 구현해 주는 것이다. listview에서는 item에 onClick 리스너가 들어가서 클릭했을 때 처리를 할 수 있었으나, recycleview 에선 item 의 클릭을 인식을 구현할 수 없으므로 adapter의 onClick 리스너를 구현해서 처리를 하는 것이다. 

 

이제 MainActivity 에서 데이터와 adBanner 을 넣는 것을 구현해 보자.

import android.annotation.SuppressLint;
import android.content.Context;

.....

public class MainActivity extends AppCompatActivity {

    // recycleview 에서 광고가 보여질 간격
    public static final int ITEMS_PER_AD = 8;
    private static final String TAG = "MainActivity";
    ActivityMainBinding binding ;
    Updatejejufd6infoViewBinding fd6Binding ;
    AppsInfoViewBinding infoViewBinding ;
    ArrayList<String> listSpinnerA ;
    ArrayList<String> listSpinnerB;
    ArrayList<String> listSpinnerC;

    DBHandler dbHandler ;
    ArrayList<JejuFD6infoBean> dataBeans ;
    JejuFD6Adapter adapter ;
    // 수정한 recycleview 용 adapter 
    RecyclerAdMobAdapter recyclerAdMobAdapter ;
    // adapter 로 전달할 데이터 구조체 
    //     안에 들어가는 정보가 2가지 형식이라 object 로 선언한 것 같음.
    List<Object> recyclerViewItems ;

    SharedPreferences sp ;
    SharedPreferences.Editor editor ;
    private final long FINISH_INTERVAL_TIME = 2000;
    private long backPressedTime = 0;
    public static Context mContext ;

    // 광고 요청을 위해서
    AdRequest adRequest ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        /**
         * 이건 다른 class 에서 요기 있는 함수를 사용해 보기 위해서
         */
        mContext = this ;

        // 광고 초기화를 꼭 처리 해야 한다.
        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
                Log.e(TAG, "adMob Ready !!!");
            }
        });

        // 광고 요청을 선언 하고.
        adRequest = new AdRequest.Builder().build();

        // adapter 로 보낼 데이터 초기화
        recyclerViewItems = new ArrayList<>();

        // adapter 을 선언
        recyclerAdMobAdapter = new RecyclerAdMobAdapter(MainActivity.this, recyclerViewItems);

        .....

        // item 클릭을 했을 때 처리하기 위한 구현 부분
        recyclerAdMobAdapter.setOnItemClickListener(new RecyclerAdMobAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                Object data = recyclerViewItems.get(position);
                Log.e(TAG, "pos=" + position) ;
                if (!data.equals(JejuFD6infoBean.class)) {
                    JejuFD6infoBean dataBean = (JejuFD6infoBean) data;
                    Intent intent = new Intent(MainActivity.this, MapsActivity.class);
                    Bundle extras = new Bundle();
                    extras.putString("viewOption", "placePoint");
                    extras.putString("placeName", dataBean.getPlace_name());
                    extras.putString("y", dataBean.getY());
                    extras.putString("x", dataBean.getX());
                    intent.putExtras(extras);
                    startActivityIfNeeded( intent, 100) ;
                } else {
                    Log.e(TAG, "" + data.equals(JejuFD6infoBean.class));
                }
            }
        });
        doInfoView();
    }

    '''''

    @SuppressLint("Range")
    public void doInfoDataView(String categoryName) {
        // adapter 로 전달해 구조체를 지운다음.
        recyclerViewItems.clear();
        dbHandler = DBHandler.open(getApplicationContext());
        Cursor rs = dbHandler.selectCategoryName(categoryName);
        while (rs.moveToNext()) {
            JejuFD6infoBean dataBean = new JejuFD6infoBean();
            dataBean.setPlace_name(rs.getString(rs.getColumnIndex("place_name")));
            dataBean.setPhone(rs.getString(rs.getColumnIndex("phone")));
            dataBean.setRoad_address_name(rs.getString(rs.getColumnIndex("road_address_name")));
            dataBean.setCategory_name(rs.getString(rs.getColumnIndex("category_name")));
            dataBean.setUrl(rs.getString(rs.getColumnIndex("url")));
            dataBean.setY(rs.getString(rs.getColumnIndex("y")));
            dataBean.setX(rs.getString(rs.getColumnIndex("x")));
            // 읽어온 데이터를 adapter 용 구조체에 일단 추가 
            recyclerViewItems.add(dataBean);
        }
        // 광고를 추가 하는 부분들
        addBannerAds();
        loadBannerAds();
        // recycleview 에 adapter 을 설정
        binding.listData.setAdapter(recyclerAdMobAdapter);
        // recycleview 의 모양을 리스트형태로 설정
        binding.listData.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
    }

    .....

    // 광고 배너를 추가 하기.
    private void addBannerAds() {
        // ITEMS_PER_AD 는 상수선언을 통해서 광고가 반복될 간격을 정한 값
        for (int i = 0; i <= recyclerViewItems.size(); i += ITEMS_PER_AD) {
            final AdView adView = new AdView(MainActivity.this);
            adView.setAdSize(AdSize.BANNER);
            adView.setAdUnitId(getString(R.string.BANNER_ID));
            recyclerViewItems.add(i, adView);
        }
    }

    /**
     * 광고를 loading
     */
    private void loadBannerAds() {
        // Load the first banner ad in the items list (subsequent ads will be loaded automatically
        // in sequence).
        loadBannerAd(0);
    }

    /**
     * 광고를 loading
     */
    private void loadBannerAd(final int index) {

        if (index >= recyclerViewItems.size()) {
            return;
        }

        Object item = recyclerViewItems.get(index);
        if (!(item instanceof AdView)) {
            throw new ClassCastException("Expected item at index " + index + " to be a banner ad"
                    + " ad.");
        }

        final AdView adView = (AdView) item;

        // Set an AdListener on the AdView to wait for the previous banner ad
        // to finish loading before loading the next ad in the items list.
        adView.setAdListener(
                new AdListener() {
                    @Override
                    public void onAdLoaded() {
                        super.onAdLoaded();
                        // The previous banner ad loaded successfully, call this method again to
                        // load the next ad in the items list.
                        loadBannerAd(index + ITEMS_PER_AD);
                    }

                    @Override
                    public void onAdFailedToLoad(LoadAdError loadAdError) {
                        // The previous banner ad failed to load. Call this method again to load
                        // the next ad in the items list.
                        String error =
                                String.format(
                                        "domain: %s, code: %d, message: %s",
                                        loadAdError.getDomain(), loadAdError.getCode(), loadAdError.getMessage());
                        Log.e(
                                "MainActivity",
                                "The previous banner ad failed to load with error: "
                                        + error
                                        + ". Attempting to"
                                        + " load the next banner ad in the items list.");
                        loadBannerAd(index + ITEMS_PER_AD);
                    }
                });

        // Load the banner ad.
        adView.loadAd(new AdRequest.Builder().build());
    }
}

앞에서 말한 예제 소스에서 필요한 부분만 내가 만든 MainActivity 에 추가해 보았다.  이해를 하면 쉬워 보이기는 하는데,  일단 항목을 넣을 list 을 하다 선언하고 그 안에 데이터를 먼저 채운 다음 광고를 중간에 삽입 하는 그런 형식으로 추가가 되는 것으로 이해가 되었다. 실제 동작을 시켜 봐도 그렇게 이해가 될 수 있을 것 같다. 

 

 

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

 

실행해 보니 대충 이해가 되는 모양이 되었다.    이것으로 또 하나 배움(?)을 전하며...

반응형

스토어에 게시 되었어요.

https://play.google.com/store/apps/details?id=com.billcoreatech.opdgang1127

 

옵디강 (제주맛집 리스트 모아보기) - Google Play 앱

인터넷에 널린(?) 제주 맛집 정보를 모아 봅니다.

play.google.com


이 앱은

1. 자료 수집 :
python 을 이용한 자동화 스크립트를 활용해서 인터넷에 게시된 맞집 리스트를 수집합니다.

 

https://billcorea.tistory.com/110

 

파이썬으로 제주의 맛집을 찾아서 (3)

오늘은 정리되고 있는 자료를 타인(?)들과 공유하기 위해서... Firebase 의 Realtime Database 에 저장을 해 보도록 하겠다. import requests import sqlite3 import firebase_admin from firebase_admin import c..

billcorea.tistory.com

 

firebase realtime database 을 활용해서 수집 되는 정보를 저장해 둡니다.

2. 앱을 구동하면

기본 화면을 조회 합니다. 앞에 알림이 나오기는 하지만,
클릭하면 넘어 갑니다.

사용하시기전에 정보받기를 먼저 한번 해 주세요.

메뉴는

1) 정보갱신(제주 맛집) : 앞에서 설명한 데이터를 온라인으로 받아 옵니다. 데이터 통신을 사용해야 하기 때문에 자주 하지는 않고, 필요시 마다 한번식 내려 받아서 보시면 됩니다.

firebase 의 데이터는 매일 아침 9시에 추가 수집을 하고 있어서
보실때 한번씩 받아오기를 해서 보면 최신 자료를 보실 수 있습니다.
2) 정보갱신(제주버스정류소) : 맛집 인근 1Km 주변에 위치한 버스정류소정보를 수집하기 위해서 사용합니다.
해당 자료는 (http://www.jeju.go.kr/help/open.htm?act=view&seq=967654) 에서 수집된 api 을 활용해서 작성되었습니다.

3) 앱 알림은 처음 시작때 보이는 간단한 알림 정보를 표시 합니다.

4) 이 앱은 : 지금 보시는 페이지를 보여 주도록 되어 있습니다.






3. 찾아보기

찾아보는 방법은

1) 카테고리 선택
3단으로 구성된 카테고리를 선택합니다. 대분류 (한식, 양식 ...) 중분류 (해물,생선, 회 ...) 소분류 를 다 선택할 수 도 있고, 대분류, 중분류만 선택할 수 도 있습니다.

2) 찾는 내용으로 검색
상호를 알고 있거나, 지역명 (한림, 구좌, 성산포 ...) 등으로 입력할 수 도 있습니다. 찾는 내용을 입력하고 돋보기 버튼을 클릭하면 해당 내용과 연관된 자료를 리스트로 보여 줍니다.

3) 지도 버튼
리스트에 나와 있는 것들이 한개 또는 여러개 있을 경우 해당 정보를 지도에 표시해 줍니다.















4. 지도로 보기

지도로 보기는 구글맵 지도를 이용해서 조회된 내용에 해당 하는 위치늘 지도로 볼 수 있습니다.

지도에서 확대/축소를 이용해서 지도의 스케일을 조정할 수 있고, 내 위치 (권한 허용이 된 경우)버튼을 이용해서 지도에 나의 위치를 표시하여 찾는 곳과의 거리를 가늠해 볼 수 있습니다.























5. 상세보기


가고 싶은 곳을 찾았다면, 지도 아래 링클를 클릭해서 해당 맛집에 대한 블로그의 내용을 열어 볼 수 있습니다.

블로그의 내용과 해당 위치가 일치 하지 않을 수 도 있지만, 블로그의 내용을 스크랩 해서 주소 정보를 받아 오고 있어서 잘 찾아 보시면 블로그에서 해당 맛집의 정보를 보실 수 있을 겁니다. (?)

개별 조회를 하는 경우 주변에 나타나는 버스정류소를 클릭하면
버스정류소의 이름과 해당 정류소에 도착예정인 버스 정보를 하단에 보여 줍니다.



















6. 기타
이 앱은 스크랩핑을 이용해서 맛집 정보를 수집하고 있으므로 해당 맛집을 찾아 다니시는 수고를 하시는 분들께, 일종의 링크 공유정도이 기능을 구현하고 있습니다. 네이버나 다음에서 검색해서 찾을 수 있는 정보를 한번에 모아서 보는 정도의 기능입니다.

이런 정도의 기능 제공이 불편하시면 6k2emg@gmail.com 으로 알려 주시면 앱을 내리도록 하겠습니다.

7. 개발과정은
이전 포스팅을 참고해 주세요.
https://billcorea.tistory.com/89

 

안드로이드 앱 만들기 : 구글맵 활용 하기, 제주 맛집 리스트 (2)

앱을 만들면서 지도가 필요한 경우 카카오맵도 해 봤고, 구글맵도 구현해 보기는 했다. 카카오맵을 사용하면 나름 카카오의 지원(?)을 받아 이런 저런 것들을 해 볼 수 있다.  우선 좋은 점은 카

billcorea.tistory.com


p.s 이글은 앱을 게시하기 위한 목적으로 작성하고 있기 때문에 아직은 앱이 playstore 에 게시 되기 전이며, 게시되면 update 할 예정 입니다.

반응형

조금 지나긴 했지만, 이슈가 되었던 요소수, 그걸 판매하는 주유소 정보를 공공데이터 포털에서 제공하기 시작했다.  현재 (2021.12.20 기준)는 111개 주유소의 정보만 제공이 되고 있는 것 같으나, 일단 그걸 이용해서 데이터 제공을 하는 앱을 구성해 보았다.  이번 앱은 이미 만들었던 앱에 retrofit 서비스 호출을 구성하여 데이터를 읽어 오는 부분만 구성해 보았다. 

 

가는길에 앱 메인

 이 앱은 현재 가는길에 들려야 하는 곳을 찾아서 기록해 두기 위해서 만들었던 앱이다.  집 가는 길에,  학교 가는 길에, 어디 가는 길에... 들렸다 오라는 엄마의 , 여보의 말을 기억해야 하나... 깜밖 거리는 나를 위해서...

 

본론으로 와서 공공데이터 포털에서 데이터 활용 신청을 해 보자.

공공데이터 포털

data.go.kr 을 접속해 보면 위와 같이 요소수 중점 유통 주유소 재고현황 API에 대한 활용 정보가 제공되고 있음을 알 수 있다. 저 팝업을 클릭해 들어가 보면 활용에 대한 정보를 볼 수 있다. 

 

api 활용 안내

 

활용신청을 클릭해 보자. 신청 단계는 사용신청 사항을 입력해서 확인을 진행하게 되면 바로 처리가 되고 있어서 자세한 설명을 접어 두고 신청 후 화면을 보면 아래와 같이 일반 인증키가 2개 보이는데,  source 작성 시에는 decoding 된 것을 가져다가 source 작성 시에 encoding 해서 전달하는 방식으로 처리를 하면 좋을 것 같다. 

 

api 활용 승인

 

 

api 호출시 파라미터 설명
api 구조체 설명

아래로 내려보면 데이터 구조를 설명하는 부분들이 나와 있으므로 이것을 근간으로 해서 data 구조 class 을 선언해 보자.

 

import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;

/**
 * 2021.11.26 요소수 주요소 정보
 */
public class AdBlueBean {
    @SerializedName("currentCount")
    int currentCount;
    @SerializedName("data")
    ArrayList<InventoryModelBean> data ;
    @SerializedName("matchCount")
    int matchCount ;
    @SerializedName("page")
    int page ;
    @SerializedName("perPage")
    int perPage;
    @SerializedName("totalCount")
    int totalCount ;

    public void setPage(int page) {
        this.page = page;
    }

    public int getPage() {
        return page;
    }

    public void setPerPage(int perPage) {
        this.perPage = perPage;
    }

    public int getPerPage() {
        return perPage;
    }

    public void setMatchCount(int matchCount) {
        this.matchCount = matchCount;
    }

    public int getMatchCount() {
        return matchCount;
    }

    public void setCurrentCount(int currentCount) {
        this.currentCount = currentCount;
    }

    public int getCurrentCount() {
        return currentCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setData(ArrayList<InventoryModelBean> data) {
        this.data = data;
    }

    public ArrayList<InventoryModelBean> getData() {
        return data;
    }
}

위 그림에 inventory_api 을 보면 위 AdBlueBean과 같이 구조체를 가지고 있고 실제 상세 자료는 inventory_model 형식의 데이터 구조를 가지고 있다. 그래서 일단은 AdBlueBean class을 선언하고 model 데이터는 아래처럼 InventoryBean class을 구성하였다. 

 

import com.google.gson.annotations.SerializedName;

/**
 * 2021.11.26 요소수 재고량 정보
 */
public class InventoryModelBean {
    @SerializedName("addr")
    String addr ; // 주유소 주소
    @SerializedName("code")
    String code ; // 주유소 코드
    @SerializedName("inventory")
    String inventory ; // 재고량
    @SerializedName("lat")
    String lat ; // 위도
    @SerializedName("lng")
    String lng ; // 경도
    @SerializedName("name")
    String name ; // 주유소 이름
    @SerializedName("openTime")
    String openTime ; // 영업 시간
    @SerializedName("price")
    String price ; // 가격
    @SerializedName("regDt")
    String regDt ; // 업데이트 일시
    @SerializedName("tel")
    String tel ; // 전화번호
    @SerializedName("color")
    String color ; // 잔량 수량 구간

    public void setAddr(String addr) {
        this.addr = addr;
    }

    public String getAddr() {
        return addr;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    public void setInventory(String inventory) {
        this.inventory = inventory;
    }

    public String getInventory() {
        return inventory;
    }

    public void setLat(String lat) {
        this.lat = lat;
    }

    public String getLat() {
        return lat;
    }

    public void setLng(String lng) {
        this.lng = lng;
    }

    public String getLng() {
        return lng;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setOpenTime(String openTime) {
        this.openTime = openTime;
    }

    public String getOpenTime() {
        return openTime;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getPrice() {
        return price;
    }

    public void setRegDt(String regDt) {
        this.regDt = regDt;
    }

    public String getRegDt() {
        return regDt;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getTel() {
        return tel;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getColor() {
        return color;
    }

}

@SerializedName는 api로 제공받는 데이터 구조체가 json 형식으로 받게 될 것인데, Gson을 이용해 데이터를 받을 때 연결되는 정보라는 정도로 이해를 하면 될 것 같다.  실제 source 코드에서 사용되는 변수명과 같은 경우가 되더라도 데이터를 연결해 주기 위해서는 api을 제공하는 쪽에서 제시한 이름으로 일치시켜 주어야 한다. 

 

이제 통신을 구성하기 위해서 retrofit 에 대한 설정을 상기해 보자.

 

https://billcorea.tistory.com/26

 

안드로이드 앱 만들기 API 연동을 위한 retrofit 구현 이야기.

안드로이드 폰에서 Restful 호출을 위해서 StringRequest 을 사용해 보기도 했지만, Retrofit 을 알고 나서는 간편하게 잘 쓰게 되었다. data.go.kr 에서 제공하는 공공데이터를 이용해서 앱을 만들어 보고

billcorea.tistory.com

이 글에서도 잠깐 설명을 하기는 했었는데,  지금 보니 조금 허접한 느낌이 드는 건 뭘까?

 

일단, gradle(Module) 파일에서 설정은 

 

    implementation 'com.squareup.retrofit2:retrofit:2.7.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.7.2'
    implementation 'com.squareup.retrofit2:converter-simplexml:2.1.0'

이렇게 3줄이 들어가야 하는 데, gson 은 데이터를 json 형식으로 받을 거라서 필요하고, simplexml 은 데이터를 xml 형식으로 받을 때 필요하나, 이번에는 사용하지 않기 때문에 없어도 뭐... 

 

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.Query;

/**
 * http 호출을 위한 API
 *     앱 등록 및 사용자 설정 필수 category
 *
 */

public interface RetrofitApi {

    /**
     *  2021.11.26 요소수 데이터 수집
     */
    @GET("/api/uws/v1/inventory")
    Call<AdBlueBean> getAdBlueData(@Query(value="serviceKey", encoded = true) String serviceKey,
                                           @Query("page") int iPage,
                                           @Query("perPage") int perPage,
                                           @Query(value="cond[addr::LIKE]", encoded = true) String addressLike
    );

    /**
     * 전체 목록을 수집
     * @param serviceKey
     * @param iPage
     * @param perPage
     * @return
     */
    @GET("/api/uws/v1/inventory")
    Call<AdBlueBean> getAllAdBlueData(@Query(value="serviceKey", encoded = true) String serviceKey,
                                   @Query("page") int iPage,
                                   @Query("perPage") int perPage
    );

}

서비스 호출을 하기 위한 interface을 구현해 보았는데, 실상은 getAllBlueData 함수만 사용하였다. 위에 있는 getAdBlueData 함수는 조회 조건에 addr에 like 검색을 지원하는 호출이 필요할 때 사용해 볼 수 있다. 

 

이제 activity에서 호출을 해 보자.


....

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MapsFragment extends Fragment implements OnCompleteListener<Void>,
        OnBackPressedListener,
        OnMapReadyCallback,
        GoogleMap.OnMapLongClickListener,
        GoogleMap.OnMarkerClickListener {

    GoogleMap mMap;

....

    RetrofitApi service;
    
....

    Context context;

    public static MapsFragment newInstance(String keyWord, float latitude, float longitude) {
        MapsFragment fragment = new MapsFragment();
        Bundle args = new Bundle();
        ...
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        context = container.getContext();
        ...

        binding = FragmentMapsBinding.inflate(getLayoutInflater());

       ...

        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        SupportMapFragment mapFragment =
                (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);

        ...

        // 사용을 위해서 선언
        retrofitBlue = new Retrofit.Builder()
                .baseUrl(serviceURL)  // 기본 url 은 공공데이터 포털에서 확인 가능
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        // interface 와 연결하기 위해서 선언        
        serviceBlue = retrofitBlue.create(RetrofitApi.class);

        ...

    }

    private void doFindAllAdBlue(GoogleMap googleMap) {

        infoBinding = AdblueInfoBinding.inflate(getLayoutInflater());

        for(int i=1 ; i < 13 ; i++) {
            // 서비스 호출을 통해서 데이터을 구해옴 현재는 페이지다 10건씩 수신 하도록 선언
            serviceBlue.getAllAdBlueData(serviceKey, i, 10)
                    .enqueue(new Callback<AdBlueBean>() {
                        @Override
                        public void onResponse(Call<AdBlueBean> call, Response<AdBlueBean> response) {
                            Log.e(TAG, "Total=" + response.body().getTotalCount());
                            Log.e(TAG, "Current=" + response.body().getCurrentCount());
                            for (InventoryModelBean inventoryModelBean : response.body().getData()) {
                                ... 
                                // 가져온 데이터를 화면에 보여 주도록 설정
                                infoBinding.textName.setText(inventoryModelBean.getName());
                                infoBinding.textPhone.setText(inventoryModelBean.getTel());
                                infoBinding.textPrice.setText(inventoryModelBean.getPrice()+"원");
                                infoBinding.textInventory.setText(inventoryModelBean.getInventory()+"L");
                                LatLng sydney = new LatLng(Double.parseDouble(inventoryModelBean.getLat()), Double.parseDouble(inventoryModelBean.getLng()));
                                googleMap.addMarker(new MarkerOptions().position(sydney).title(inventoryModelBean.getName())
                                        .icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(context, infoBinding.getRoot()))));
                            }
                        }

                        @Override
                        public void onFailure(Call<AdBlueBean> call, Throwable t) {
                            Log.e(TAG, "error=" + t.toString());
                        }
                    });
        }
    }

   ...

}

source에 필요해 보이는 부분들만 발췌를 했는데, retrofitBlue라는 설정을 통해서 retrofit 사용을 위한 기본 설정을 하고 service을 호출해서 앞에서 구현한 interface을 호출해서 서비스 호출을 통해서 데이터를 가져오면 된다. 

response 가 json으로 오기 때문에 앞에서 선언했던 AdBlueBean을 이용해서 데이터를 받아서 분석해서 사용하면 된다.  어ㅣ예시에서는 for 구문을 통해서 12번 데이터를 받아오는 것처럼 되어 있는데. 현재까지 알려진 것으로는 api 가 제공하는 데이터가 110개 정도 되고 한 번에 10개의 데이터를 제공하고 있기 때문에 반복해서 전제 자료를 받아오기 위함이다. 

 

이렇게 해서 데이터가 오는 걸 보면 다음과 같이 구현이 되었다. 

 

 

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

map에 custom marker을 구현해서 표시가 되고 있지만, 아직은 모양이 이쁘지는 않은 것 같다. 이 부분은 좀 더 고민을 해 볼 필요가 있을 것 같다.

 

이 걸로 오늘 앱 만들기...

 

 

 

반응형

앱을 만들면서 지도가 필요한 경우 카카오맵도 해 봤고, 구글맵도 구현해 보기는 했다. 카카오맵을 사용하면 나름 카카오의 지원(?)을 받아 이런 저런 것들을 해 볼 수 있다.  

 

우선 좋은 점은 카카오가 지원하는 다른 서비스들과 연동이 수월하다. 하다 못해 카카오 내비를 호출해서 바로 길찾기를 지원받을 수 있으니... 다만, onestore 에 앱을 등록하는 것이 번거롭다(?) 여러번 시도를 했는데, 어떤 방법으로 앱을 검증 하는 지는 모르겠으나, 번번히 실패 ... 그래서 구글맵으로 수정앱을 등록해보니, 한번에 패스~

 

그래서 일단 구글맵에 지도를 표현해 보도록 하겠다. 

일단 기본적으로 구현이 수월한 방법... android studio 에서 new - acitivity - gallery 를 선택하면 ...

 

액티비티 선택

여러 종류의 activity 가 있는데, 그 중에서 지도가 들어있는 maps 을 선택하면 기본적인 설정은 android studio 가 해 준다.

 

그 다음은 manifest 파일에 meta 정보를 설정하는 것이 나온다. meta에 google-api-key 을 설정해 주어야 하는데, 

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_info_logo"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_info_logo_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.OpdGang1127">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/API_KEY" />

api-key 는 그럼 어디서 받아오는 가 ?

https://console.cloud.google.com 

 

Google Cloud Platform

하나의 계정으로 모든 Google 서비스를 Google Cloud Platform을 사용하려면 로그인하세요.

accounts.google.com

cloud platform 의 console 화면에서 사용자 인증 정보에 들어가서 api 키를 추가 하거나 기존에 등록했던 것에서 가져 오면 된다.

 

google dash board

이미 등록해 놓은 것이 있으니 그걸 하나 선택해서 상세 내용을 볼껀데,

api 세부 설정

이 내용에서 한가지 생각해 볼 것은 android 앱을 만들고 있기 때문에  애플리케이션 제한사항을 선택할 때 꼭 안드로이드를 선택해야만 할 것 같은 생각이 들었던 경험이 있는 데,  그 때는 주의해야할 부분이 인증서 해쉬값을 등록해 줄 때 debug 용 release 용 두개를 각각 설정해 주어야 하고, 그것들을 다 project에  찾아서 설정해 주어야 했던 것 같은 기억이 있다.

 

그래서 이번에는 애플리케이션 제한사항은 설정하지 않았다. 다만, api 제한 사항을 선택해서 maps sdk 와 firebase 부분만 선택해서 사용하는 것으로 설정하고,  api key는 오른쪽 상단에 있는 apikey을 복사해서 manifest 파일에 등록해 주었다.

 

저 제한사항 둘 중 하나를 선택해 주지 않으면 메일이 자주 온다. google 에서 궁시렁 궁시렁...

아무튼 이렇게 설정이 끝나고 나면 이제 activity 를 구성해 볼 차례 인데, 기본적으로 maps activity 을 선택 했기 때문에 기본 code 작업은 되어 있게 된다. 

 

그래서 그 안에 필요한 코드등을 추가해 보면 된다.  다음과 같이...

import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.billcoreatech.opdgang1127.DataBase.DBHandler;
import com.billcoreatech.opdgang1127.JejuFD6.JejuFD6Adapter;
import com.billcoreatech.opdgang1127.JejuFD6.JejuFD6infoBean;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.billcoreatech.opdgang1127.databinding.ActivityMapsBinding;

import java.util.ArrayList;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private static final String TAG = "MapsActivity";
    private GoogleMap mMap;
    private ActivityMapsBinding binding;
    ArrayList<JejuFD6infoBean> dataBeans ;
    JejuFD6Adapter adapter ;
    DBHandler dbHandler ;
    UiSettings mUiSettings;
    String placeName;
    double lat;
    double lon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMapsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        placeName = extras.getString("placeName");
        Log.e(TAG, "y=" + extras.getString("y").trim());
        Log.e(TAG, "x=" + extras.getString("x").trim());
        lat = Double.parseDouble(extras.getString("y").trim());
        lon = Double.parseDouble(extras.getString("x").trim());
    }

    @SuppressLint("Range")
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mUiSettings = googleMap.getUiSettings();
        mUiSettings.setZoomControlsEnabled(true);
        mUiSettings.setMyLocationButtonEnabled(true);

        LatLng sydney = new LatLng(lat, lon);
        mMap.addMarker(new MarkerOptions().position(sydney).title(placeName));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 15));
        dataBeans = new ArrayList<>();
        adapter = new JejuFD6Adapter(MapsActivity.this, dataBeans, "url");
        dbHandler = DBHandler.open(MapsActivity.this);
        Cursor rs = dbHandler.selectInfo(placeName);
        while (rs.moveToNext()) {
            JejuFD6infoBean dataBean = new JejuFD6infoBean();
            dataBean.setPlace_name(rs.getString(rs.getColumnIndex("place_name")));
            dataBean.setPhone(rs.getString(rs.getColumnIndex("phone")));
            dataBean.setRoad_address_name(rs.getString(rs.getColumnIndex("road_address_name")));
            dataBean.setCategory_name(rs.getString(rs.getColumnIndex("category_name")));
            dataBean.setUrl(rs.getString(rs.getColumnIndex("url")));
            dataBean.setY(rs.getString(rs.getColumnIndex("y")));
            dataBean.setX(rs.getString(rs.getColumnIndex("x")));
            Log.e(TAG, dataBean.getUrl() == null ? "null" : dataBean.getUrl()) ;
            dataBeans.add(dataBean);
        }
        binding.listPlace.setAdapter(adapter);
        binding.listPlace.setLayoutManager(new LinearLayoutManager(getApplicationContext()));

        adapter.setOnItemClickListener(new JejuFD6Adapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (dataBeans.get(position) != null){
                    if (dataBeans.get(position).getUrl() != null) {
                        String viewUrl = "" ;
                        if (dataBeans.get(position).getUrl().startsWith("http://") ||
                                dataBeans.get(position).getUrl().startsWith("https://")) {
                            viewUrl = dataBeans.get(position).getUrl();
                        } else {
                            viewUrl = "https://" + dataBeans.get(position).getUrl();
                        }
                        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(viewUrl));
                        startActivity(browserIntent);
                    }
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        setResult(RESULT_OK);
        finish();

    }
}

 onCreate 와 onMapReady 부분을 구현해 주면 된다. 위 예시는 db 에서 데이터를 읽어와서 map 에 marker 을 표시하도록 구현하였다.

 

 

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

 

지도 구현은 이런식으로 구성이 끝~

 

 

반응형

화면을 만들다 보면 간혹 뭔가를 선택해야 하는 경우가 발생하게 된다. 그럴 때 콤보라고 쓰고 스피너라고 읽는 layout item에 대한 이야기를 잠시해 두고 넣어가고자 한다.  이유는 간혹 작업을 하면서 사용하게 되는데, 나도 인간인지라 깜빡깜빡해서 사용할 때마다 찾아봐야 한다는 것이다. ㅋ~

 

일단 화면에 spinner 을 넣는다 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="30"
    tools:context=".MainActivity">

    <Spinner
        android:id="@+id/spAclass"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2" />

    <EditText
        android:id="@+id/editSearchKey"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:ems="10"
        android:hint="@string/msgSearchKey"
        android:inputType="textPersonName" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/listData"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="22" />
</LinearLayout>

화면에 spinner 을 넣는다.  그러면 화면 design 은 다음과 같이 생긴다. 

spinner layout

디자인하는 동안에는 아무것도 들어 있지 않기 때문에... 위 그림과 같이 표현이 될 듯하고. 이제 activity에서 데이터를 넣는 것을 구현해 볼 차례인데, 

 

예시에서는 ArrayString 에 들어 있는 데이터를 가지고 그리는 것을 예시로 할 것이다.  그런 이유는 데이터를 넣는 방법에는 Activity에서 String Array로 지정해서 고정시키는 방법도 있을 테고, 

String[] codeItem = new String{'코드1', '코드2','코드3'};
...

아니면 ArrayList 만 선언해 두고 데이터를 db 에서 읽어오는 방식으로 구현할 수 도 있을 테니...

ArrayList<String> listSpinnerA ;

그렇게 선언하고 나서 onCreate() 에서는 초기화만 한 다음

listSpinnerA = new ArrayList<>();


...


dbHandler = DBHandler.open(getApplicationContext());
Cursor rs = dbHandler.selectClass(listSpinnerA.get(binding.spAclass.getSelectedItemPosition()), "B", "");
listSpinnerA.clear();
while (rs.moveToNext()) {
  listSpinnerA.add(rs.getString(rs.getColumnIndex("classNameB")));
}
ArrayAdapter<String> spAdapter = new ArrayAdapter<>(getApplicationContext(),
		android.R.layout.simple_spinner_dropdown_item, listSpinnerA);
binding.spBclass.setAdapter(spAdapter);
rs.close();
dbHandler.close();

...

db에서 데이터를 읽어서 ArrayList에 넣고 그 값을 이용해서 spinner을 위한 adapter을 선언해 주는 것이다.  여기서 또 보고 가야 할 것은 simple_spinner_dropdown_item을 선언하는 것인데, 이건 spinner을 모양을 선택해 주는 것이니, 참고하고, 다른 선언을 하고 싶은 경우는 찾아보고 변경해 주면 될 것 같다.

 

그럼... 선언한 화면이 어떻게 움직이는 지 봐야 할 듯...

 

 

동영상 서비스가 종료되어 해당 콘텐츠를 재생할 수 없습니다.

 

실제로 구동하는 예시는 이런 모습으로 나타난다... 화면에는 spinner 가 3개가 있는데, 첫 번째 spinner 가 변할 때마다, 2번쨰을 다시 읽어오고, 2번째를 선택하면 3번쨰을 다시 읽어 오는 그런 모습으로 구동하게 된다.

 

이것으로 spinner을 구현해 보았다.

 

반응형

+ Recent posts