펌 OK (출처 표시), 상업적 이용 NO, 컨텐츠 변경 NO

안드로이드에서 데이터 관리를 할 수 있는 방법에는 여러가지가 있다.

SQLite DB를 이용한 데이터 관리, 서버를 거친 DB에 의한 관리, Input,OutputStreamReader를 이용한 관리,

SharedPreferences를 이용한 관리 등이 있으며, 여기서는 SharedPreferences를 이용한 방법에 대해

알아보겠다.


SharedPreferences키와 벨류로 이루어진 파일 형식으로 데이터를 저장하는 방법으로,

Boolean, Float, Int, Long, String 형태로 데이터를 저장할 수 있다.

어플의 설정값, 사용자 설정 정보등을 저장하는데 적합하며 사용법은 다음과 같다.


선언

SharedPreferences mPref = PreferenceManager.getDefaultSharedPreferences(context);


데이터 저장

SharedPreferences.Editor editor = mPref.edit();

editor.putString("key", "value");

editor.commit();


데이터 호출

String callValue = mPref.getString("key", "default value");

*호출하는 키에 대응하는 값이 없을 경우 디폴트로 설정한 데이터가 출력된다.


데이터 삭제

SharedPreferences.Editor editor = mPref.edit();

editor.remove("key"); or editor.clear();

editor.commit();



주의할점은 만약 기존 데이터의 형을 변경시키고싶다면

반드시 클리어를 한 다음 변경사항을 적용시킨다. 그렇지않으면 예외가 발생하게된다.


SharedPreferences의 장점은 심플한 사용과 관리가 아닐까 한다.



'Android > 입/출력' 카테고리의 다른 글

기본적인 JSONObject, JSONArray 사용법  (3) 2014.03.21

펌 OK (출처 표시), 상업적 이용 NO, 컨텐츠 변경 NO


timer3.zip


따로 주석은 없으니 궁금한점은 댓글 남겨주세요



숫자를 초단위로 입력받아 계산버튼을 누르면 자동으로 시간,분,초로 반환해주고 시작버튼을 누르면

카운트다운이 시작됩니다.


쉐어드프레퍼런스를 이용해 시간값을 저장했기때문에 종료했다가 켜도 마지막 시간이 그대로 남아있습니다.


공부용으로 만드느라 타이머를 구현해주는 API등은 사용하지 않았기때문에 많이 미흡합니다.



MainActivity.java


package com.example.timer3;


import android.app.Activity;

import android.content.SharedPreferences;

import android.content.SharedPreferences.Editor;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;


public class MainActivity extends Activity {

SharedPreferences prefs;

Editor ePref;

Button start,go,stop,allstop;

Boolean bool = true;

EditText in;

TextView tv;

String text,Str;

int t,hour,minute,second;


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

start = (Button)findViewById(R.id.start);

go = (Button)findViewById(R.id.go);

stop = (Button)findViewById(R.id.stop);

allstop = (Button)findViewById(R.id.allstop);

in = (EditText)findViewById(R.id.in);

tv = (TextView)findViewById(R.id.tv);


prefs = getSharedPreferences("Save",Activity.MODE_PRIVATE);

t = prefs.getInt("t",t);

sum();

Str = String.format("%02d시간 %02d분 %02d초",hour,minute,second);

tv.setText(Str);

in.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

in.setText("");

}

});

start.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {  

try{

text = in.getText().toString();

t = Integer.parseInt(text);

sum();

Str = String.format("%02d시간 %02d분 %02d초",hour,minute,second);

tv.setText(Str);

}catch(Exception e){}

}

});

go.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

bool = true;

thread threadTest = new thread();

threadTest.setDaemon(true);

   threadTest.start();

}

});

stop.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

bool = false;

}

});

allstop.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

bool = false;

t = 0;

sum();

Str = String.format("%02d시간 %02d분 %02d초",hour,minute,second);

tv.setText(Str);

}

});

}


public class thread extends Thread{

public void run(){

while(bool){

handler.sendEmptyMessage(0);

try{

Thread.sleep(1000);

}catch (Exception e){}

}

}

}

Handler handler = new Handler(){

public void handleMessage(Message msg){

if(msg.what ==0){

if(t>0){

Log.d("fureun","XD");

t--;

sum();

Str = String.format("%02d시간 %02d분 %02d초",hour,minute,second);

tv.setText(Str);

}

}

}

};

public void sum(){

hour =  t/3600;

minute = (t%3600)/60;

second = (t%3600)%60;

}

@Override

protected void onDestroy() {

// TODO Auto-generated method stub

super.onDestroy();

bool = false;

ePref = prefs.edit();

ePref.putInt("t",t);

ePref.commit();

}

}






activity_main.xml




<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
android:gravity="center|top"
android:orientation="vertical"
    tools:context=".Mai`nActivity" >
    <TextView
        android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    android:layout_centerVertical="true"    
        android:textSize="20pt"
android:gravity="center_horizontal"
android:paddingBottom="30pt"
android:paddingTop="30pt"
        android:text="00시간 00분 00초" />
<EditText
   android:id="@+id/in"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:layout_marginBottom="30pt"
   android:text="시간을입력하세요"/>
<LinearLayout
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
  android:orientation="horizontal"
   >
<Button
   android:id="@+id/start"
   android:layout_width="wrap_content"
        android:layout_height="wrap_content"
android:layout_weight="1"
        android:text="계산" />
  <Button
   android:id="@+id/go"
   android:layout_width="wrap_content"
        android:layout_height="wrap_content"
android:layout_weight="1"
        android:text="시작" />
  <Button
   android:id="@+id/stop"
   android:layout_width="wrap_content"
        android:layout_height="wrap_content"
android:layout_weight="1"
        android:text="일시정지" />
<Button
   android:id="@+id/allstop"
   android:layout_width="wrap_content"
        android:layout_height="wrap_content"
android:layout_weight="1"
        android:text="중지" />
   
</LinearLayout>
</LinearLayout>


'Android > 예제' 카테고리의 다른 글

XmlPullParser를 이용한 파싱 예제  (2) 2013.07.24