Notice
Recent Posts
Recent Comments
Today
Total
05-04 00:14
Archives
관리 메뉴

Jeongchul Kim

안드로이드 환경설정 SharedPreferences 본문

Android

안드로이드 환경설정 SharedPreferences

김 정출 2016. 3. 23. 15:44


안드로이드 환경설정 SharedPreferences


환경 설정 변수를 저장하고 가져오기

SharedPreferences 변수 선언

SharedPreferences 변수와 Editor 변수를 선언하고 초기화한다.

SharedPreferences sp = getSharedPreferences("MYAPP", Context.MODE_PRIVATE);

Editor editor = sp.edit();


SharedPreferences 저장하는 방법  

editor.putXXXX(“Key”,”Value”);

문자열을 저장하고 싶다면 putString

이 후에 키와 값을 지정하면된다.


SharedPreferences 가져오는 방법

SharedPreferences sp = getSharedPreferences("MYAPP", Context.MODE_PRIVATE);

String key = sp.getString("key", null);


sp.getXXX(“Key”,”Default”);

SharedPreferences의 변수에 getXXX의 키값으로 접근한다.



MainActivity.java


package com.example.sharedpreferencestest;

import android.app.Activity;

import android.content.Context;

import android.content.Intent;

import android.content.SharedPreferences;

import android.content.SharedPreferences.Editor;

import android.os.Bundle;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.Toast;

public class MainActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

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

final EditText edt = (EditText)findViewById(R.id.edt);

SharedPreferences sp = getSharedPreferences("MYAPP", Context.MODE_PRIVATE);

String key = sp.getString("key", null);

edt.setText(key);

btn.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

String content = edt.getText().toString();

Toast.makeText(MainActivity.this, content, Toast.LENGTH_LONG).show();

SharedPreferences sp = getSharedPreferences("MYAPP", Context.MODE_PRIVATE);

Editor editor = sp.edit();

editor.putString("key", content);

editor.commit();

}

});

}

}


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="match_parent"

android:orientation="vertical">

  <EditText

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text=""

android:id="@+id/edt"/>

 <Button

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Save"

android:id="@+id/btn"/>

  

</LinearLayout>





앱을 껐다 다시 켜도 세션처럼 값이 남아있다.




Comments