<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<EditText  
	    android:id="@+id/edit"
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    />
	<Button  
	    android:id="@+id/write"
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="프리퍼런스 쓰기"
	    />
	<Button  
	    android:id="@+id/read"
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="프리퍼런스 읽기"
	    />
	<TextView  
	    android:id="@+id/view"
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content"
	    />
</LinearLayout>


package net.npaka.preferencesex;

import android.app.Activity;
import android.os.Bundle;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class PreferencesEx extends Activity implements View.OnClickListener{
	private EditText editText;//텍스트 박스
	private Button btnWrite;//읽기 버튼
	private Button btnRead;//쓰기 버튼
	private TextView view;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		editText = (EditText)findViewById(R.id.edit);
		btnWrite = (Button)findViewById(R.id.write);
		btnRead= (Button)findViewById(R.id.read);
		view= (TextView)findViewById(R.id.view);

		btnWrite.setOnClickListener(this);
		btnRead.setOnClickListener(this);
	}

	public void onClick(View v) {
		if(v==btnWrite){
			//SharedPreferences 객체 구하기(1)
			SharedPreferences pref = getSharedPreferences("PreferencesEx",MODE_PRIVATE);

			//프리퍼런스의 쓰기(2)
			SharedPreferences.Editor editor =pref.edit();
			editor.putString("text", editText.getText().toString());
			//반드시 commit()메소드를 호출해야 저장됨
			editor.commit();
			editText.setText("");
		}else if(v==btnRead){
			//SharedPreferences 객체 구하기(1)
			SharedPreferences pref = getSharedPreferences("PreferencesEx",MODE_PRIVATE);

			//프리퍼런스로부터 읽기(3)
			view.setText(pref.getString("text",""));
		}
	}
}




+ Recent posts