Android/SharedPreferences
Android SharedPreferences example
Soul-Learner
2012. 7. 30. 19:03
Android에서 SharedPreferences 를 이용하여 Activity가 정지되기 전에 상태 값을 저장하고 다시 복원하는 예 애플리케이션 영역에 저장되므로 애플리케이션이 삭제되면 함께 삭제됨
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
tools:context=".MainActivity" />
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go Google"
android:onClick="onBtnGoogle"/>
</LinearLayout>
Activity
package com.example.androidapp;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class TestActivity extends Activity {
TextView tv;
EditText editMsg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.textView1);
editMsg = (EditText) findViewById(R.id.editText1);
}
public void onBtnGoogle(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://google.co.kr"));
startActivity(intent);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Toast.makeText(this, "onSaveInstanceState()...", Toast.LENGTH_SHORT).show();
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Toast.makeText(this, "onRestoreInstanceState...", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPause() {
String msg = editMsg.getText().toString();
SharedPreferences sp = null;
sp = getSharedPreferences("Pref01", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("msg", msg);
editor.commit();
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences sp = null;
sp = getSharedPreferences("Pref01", Activity.MODE_PRIVATE);
if(sp!=null && sp.contains("msg")) {
String msg = sp.getString("msg", "");
tv.setText(tv.getText().toString()+msg);
}
}
}