728x90
반응형

안녕하세요. 로이손입니다.

오늘은 SharedPreferences에 대해서 알아보고자 합니다.

 

 

SharedPreferences는 앱의 데이터를 영속적으로 저장하기 위한 클래스.

DBMS 방식의 데이터 영속화는 테이블 구조로 저장하는 반면, SharedPreferences는 Key-value 형태로 저장하며

SharedPreferences로 저장되는 데이터 역시 XML로 저장되지만 SharedPreferences 객체를 통해 간단히 개발할 수 있다.

 

■ SharedPreferences 객체 획득

  • getPreferences(int mode) : 별도의 파일명을 지정하지 않기 때문에 자동으로 액티비티 이름의 파일 내에 저장되는데, 예를 들어서 TestActivity에서 getPreferences() 함수로 SharedPreferences를 획득하면 TextActivity.xml에 저장된다. 해당 액티비티만의 저장 공간이므로 다른 액티비티에서는 데이터를 이용할 수 없다.

      SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);

 

  • getSharedPreferences(String name, int mode) :파일명에 대한 정보를 매개변수로 지정하기 때문에 해당 이름으로 XML파일을 만든다. 다른 액티비티나 컴포넌트들이 데이터를 공유할 수 있다. 데이터가 많은데 이를 각각의 파일로 나누어 구분하여 저장하고자 할 때 주로 이용된다.

      SharedPreferences sharedPreferences = getSharedPReferences("MyPref", Context.MODE_PRIVATE);

 

  • PreferenceManager.getDefaultSharedPreferences(Context context) :             PreferenceManager.getDefaultSharedPreferences() 함수는 별도의 파일명을 명시하지 않기 때문에 기본으로 앱의 패키지명을 파일명으로 사용하며 다른 컴포넌트에서도 이용 가능하다. 패키지명이 com.android.test이면, 파일명은 "com.android.test_preferences"가 됩니다.

 

 Mode 설명

SharedPreferences 객체를 획득할 때 지정하는 mode는 아래와 같으며, 대부분의 경우 MODE_PRIVATE이다.

참고로 API LEVEL 17부터는 읽기, 쓰기 모드가 deprecation 되었다.

MODE_PRIVATE : 자기 앱 내에서 사용. 외부 앱에서 접근 불가

MODE_WORLD_READABLE : 외부 앱에서 읽기 가능

MODE_WORLD_WRITEABLE : 외부 앱에서 쓰기 가능

 

 SharedPreferences 객체에 데이터 저장

SharedPreferences로 데이터를 저장하려면 Editor 클래스의 함수를 이용한다. 

  • putBoolean(String key, boolean value)

  • putFloat(String key, float value)

  • putInt(String key, int value)

  • putLong(String key, long value)

  • putString(String key, String value)

  • commit() : 데이터를 최종 적용하기 위해 해당 함수를 호출

    SharedPreferences.Editor editor = sharedPreference.edit();

    editor.putString("data","test1");

    edtior.putInt("data1",500);

    editor.commit();

 

 SharedPreferences 객체에서 데이터 불러오기

저장된 데이터를 획득할 때는 SharedPreferences 클래스의 getter 함수를 이용한다.

  • getBoolean(String key, boolean defValue);

  • getFloat(String key, float defValue);

  • getInt(String key, int defValue);

  • getLong(String key, long defValue);

  • getString(String key, String defValue);

    String data = sharedPreference.getString("data","none");

    int data1 = sharedPreference.getInt("data1",0);

 

 

 예제

순서 : XML 파일 생성(settings_alarm.xml) -> PreferenceFragment를 상속받은 클래스 생성 -> SettingActivity.xml에 Fragment 추가 -> SettingActivity클래스 실행

 

1. XML 파일 생성

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
        <PreferenceCategory android:title="알림">
            <SwitchPreference
                android:key="alarmYn"
                android:title="알람 설정">

            </SwitchPreference>
            <SwitchPreference
                android:key="alarmYn2"
                android:title="알람2 설정">

            </SwitchPreference>
        </PreferenceCategory>
</PreferenceScreen>

 

2. PreferenceFragment 를 상속 받은 AlarmPreferenceFragment 생성

public class AlarmPreferenceFragment extends PreferenceFragment {

    @Override
    public void onCreate(final Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings_alarm);
    }
}

 

3. 화면에 보여주기 위한 SettingActivity.xml 에 추가.

<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"
    tools:context=".MainActivity"
    android:orientation="vertical"
    android:gravity="top">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="나만의 알람 설정"
        android:textSize="30dp"
        android:layout_marginBottom="10dp"/>

    <fragment
        android:id="@+id/setting_alarm_fragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:name="패키지명.alarm.AlarmPreferenceFragment" />

</LinearLayout>

4. SettingActivity를 실행하면 됩니다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

끝.

 

728x90
반응형
728x90
반응형

안녕하세요.

오랜만에 안드로이드 내용으로 찾아뵙습니다.

 

 

오늘 알아볼 내용은 안드로이드의 GridLayout(그리드레이아웃)내 뷰를 정렬하는 방법 중에서도 

화면에 꽉차게 뷰를 나열하는 Tip을 알아보려고 합니다.

 

말보다는 그림이겠죠?!

 

기본적인 GridLayout의 사용법은 아래 그림과 같이,

xml 내에서 GridLayout 태그를 주고, orientation, columnCount 또는 rowCount 속성을 설정합니다.

 

저는 여기서 2개의 열에 ImageButton들이 나열되는 모습을 생각했는데,

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

실제로는 이미지 크기가 너무 커서 이미지 하나만 화면에 꽉차게 보였습니다. (아래 그림 참조)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

제가 생각했던 건 이게 아닌데 말이죠..

※ GridLayout에서는 Layout_weight 속성을 지원하지 않습니다!!

그래서 LinearLayout를 이용하여 아래와 같이 바꿔보았습니다.

(※ columnCount는 1로, 그리고 2개의 이미지버튼을 weight 속성을 이용하여 LinearLayout으로 감싸주었습니다.)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

그랬더니, 아래와 같이 제가 생각했던 2개의 열에 이미지가 잘 나열된 모습을 볼 수 있습니다. (이미지 비율 조정 필요)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

앞으로도 도움이 될 만한 정보들은 공유하겠습니다.

 

감사합니다!

 

 

728x90
반응형

+ Recent posts