Category Archives: 허접프로그래머

[Java/Android] SharedPreferences 유틸리티 클래스 만들기

안드로이드상에서는 데이터를 저장하기 위해서 다양한 방법을 사용할 수 있습니다. 그중에서도 가장 손쉽게 데이터를 보관할 수 있는 방법으로는 SharedPreferences를 이용하는 방법이 있습니다.

원래는 어플리케이션의 설정을 저장하고 읽어오기 위해서 태어난것 같지만 이외에도 다양한 방법으로 사용될 수 있습니다. 하지만 퍼포먼스는 그다지 좋지 않은것 같습니다. 퍼포먼스를 따져봐야 하는 경우에는 SQLite를 추천합니다.
[code java]public class SharedPreference

{
/**
* <pre>
* String 데이터를 저장합니다.
* </pre>
*
* @param context 컨텍스트
* @param key 키
* @param value 값
*/
public static void putSharedPreference
(Context context, String key, String value)
{
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(context);

SharedPreferences.Editor editor = prefs.edit();

editor.putString(key, value);
editor.commit();
}

/**
* <pre>
* Boolean 데이터를 저장합니다.
* </pre>
*
* @param context 컨텍스트
* @param key 키
* @param value 값
*/
public static void putSharedPreference
(Context context, String key, boolean value)
{
SharedPreferences prefs =

PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();

editor.putBoolean(key, value);
editor.commit();
}

/**
* <pre>
* Integer 데이터를 저장합니다.
* </pre>
*
* @param context 컨텍스트
* @param key 키
* @param value 값
*/
public static void putSharedPreference
(Context context, String key, int value)
{
SharedPreferences prefs =

PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();

editor.putInt(key, value);
editor.commit();
}

/**
* <pre>
* String 데이터를 읽어옵니다.
* </pre>
*
* @param context 컨텍스트
* @param key 키
* @return 읽어온 값, 값이 없을 경우 null이 반환된다.
*/
public static String getSharedPreference
(Context context, String key)
{
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(context);

return prefs.getString(key, null);
}

/**
* <pre>
* Boolean 데이터를 읽어옵니다.
* </pre>
*
* @param context 컨텍스트
* @param key 키
* @return 읽어온 값, 값이 없을 경우 false가 반환된다.
*/
public static boolean getBooleanSharedPreference
(Context context, String key)
{
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(context);

return prefs.getBoolean(key, false);
}

/**
* <pre>
* Int 데이터를 읽어옵니다.
* </pre>
*
* @param context 컨텍스트
* @param key 키
* @return 읽어온 값, 값이 없을 경우 0이 반환된다.
*/
public static int getIntSharedPreference
(Context context, String key)
{
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(context);

return prefs.getInt(key, 0);
}
}[/code]

데이터를 저장하기 위해서는 putSharedPreference메서드를 사용하면 되고 값을 읽어올때는 get~~~SharedPreference를 이용하여 읽어오면 됩니다.

[Java] 문자열 형태의 날짜(Date)를 원하는 형태로 바꾸기

자바에서는 날짜나 시간을 핸들링 하기 위해 Date라는 훌륭한 클래스를 제공하고 있지만 클라이언트가 서버와 통신할떄 XML/JSON등을 이용한다거나 하면 아무래도 해당 데이터형을 그대로 유지하기가 힘듭니다.

마치 모뎀 시절의 암호화/복호화가 필요하듯이 객체들을 시리얼라이징해서 문자열로 만들어내고 클라이언트에서는 데이터를 받아서 파싱이라는 과정을 거쳐 다시 사용가능한 형태의 데이터로 변환을 해야 합니다.

이때에 넘겨받은 문자열형태의 날짜 혹은 시간을 어떻게 변환할수 있을지 생각하여 만들어본 간단한 메서드입니다.
[code java]/**
 * <pre>
 * 문자열 형태의 날짜를 원하는 형태로 변환합니다.
 *
 * 예시)
 * “yyyy.MM.dd G ‘at’ HH:mm:ss z” 2001.07.04 AD at 12:08:56 PDT
 * “EEE, MMM d, ”yy” Wed, Jul 4, ’01
 * “h:mm a” 12:08 PM
 * “hh ‘o”clock’ a, zzzz” 12 o’clock PM, Pacific Daylight Time
 * “K:mm a, z” 0:08 PM, PDT
 * “yyyyy.MMMMM.dd GGG hh:mm aaa” 02001.July.04 AD 12:08 PM
 * “EEE, d MMM yyyy HH:mm:ss Z” Wed, 4 Jul 2001 12:08:56 -0700
 * “yyMMddHHmmssZ” 010704120856-0700
 * “yyyy-MM-dd’T’HH:mm:ss.SSSZ” 2001-07-04T12:08:56.235-0700
 * </pre>
 *
 * @param date 변환할 날짜
 * @param fromFormatString 변환될 포맷
 * @param toFormatString 변환할 포맷
 * @return 변환된 날짜 문자열
 */
public static String formattedDate
(String date, String fromFormatString, String toFormatString)
{
SimpleDateFormat fromFormat =
new SimpleDateFormat(fromFormatString);
SimpleDateFormat toFormat =
new SimpleDateFormat(toFormatString);
Date fromDate = null;

try
{
fromDate = fromFormat.parse(date);
}
catch(ParseException e)
{
fromDate = new Date();
}

return toFormat.format(fromDate);
}

/**
 * <pre>
 * 날짜를 원하는 형태의 문자열로 반환합니다.
 * </pre>
 *
 * @param date 변환할 Date 인스턴스
 * @param format 변환할 포맷
 * @return 변환된 날짜 문자열
 */
public static String formattedDate(Date date, String format)
{
SimpleDateFormat toFormat = new SimpleDateFormat(format);
return toFormat.format(date);
}[/code]
이제 사용해 봅시다. 다음과 같이 간단하게 출력하고자 하는 형태로 변환하여 사용하시면 됩니다.
[code java]formattedDate(“2010-12-25”, “yyyy-MM-dd”, “yyMMdd”);
formattedDate(new Date(), “yyyy-MM-dd”);[/code]