이 글에서는 Android에서 SharedPreferences(공유 환경설정)를 활용하여 서로 다른 액티비티(Activity) 사이에 데이터를 저장하고 전달하는 방법을 단계별로 살펴봅니다.
SharedPreferences는 간단한 키-값(key-value) 형태의 데이터를 앱 내부에 영구적으로 저장할 수 있는 가장 손쉬운 방법입니다. 인텐트(Intent)로 값을 직접 넘기는 대신 SharedPreferences에 데이터를 저장해 두면, 어떤 액티비티에서든 언제든지 해당 값에 접근할 수 있습니다.
여기서는 첫 번째 화면에서 EditText에 입력한 문자열을 SharedPreferences에 저장한 뒤, 버튼을 눌러 두 번째 화면으로 이동하면 저장된 값을 TextView에 표시하는 예제를 만들어 보겠습니다.
구현 단계
1단계 – 새 프로젝트 생성
Android Studio에서 File ⇒ New Project를 선택하고, 새 프로젝트 생성에 필요한 모든 정보를 입력하여 프로젝트를 만듭니다.
2단계 – activity_main.xml 레이아웃 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
<?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android" xmlns:tools = "https://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_margin = "16dp" android:orientation = "vertical" tools:context = ".MainActivity"> <EditText android:id = "@+id/edit_text" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" android:hint = "Enter something to pass" android:inputType = "text" /> <Button android:id = "@+id/button" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_gravity = "center" android:layout_marginTop = "16dp" android:text = "Next" /> </LinearLayout>
이 레이아웃에는 사용자가 전달할 값을 입력하는 EditText와, 다음 화면으로 이동하는 Button이 세로 방향으로 배치되어 있습니다.
3단계 – MainActivity.java 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다.
package com.example.myapplication;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText = findViewById(R.id.edit_text);
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String value = editText.getText().toString().trim();
SharedPreferences sharedPref = getSharedPreferences("myKey", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("value", value);
editor.apply();
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
}
}버튼이 클릭되면 EditText에 입력된 값을 읽어 들인 후, getSharedPreferences("myKey", MODE_PRIVATE)로 SharedPreferences 인스턴스를 얻고, Editor 객체를 통해 "value"라는 키로 문자열을 저장합니다. 이후 SecondActivity로 이동하는 인텐트를 실행합니다.
4단계 – activity_second.xml 레이아웃 작성
res/layout/activity_second.xml 파일에 아래 코드를 추가합니다.
<?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android" xmlns:tools = "https://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_margin = "16dp" android:orientation = "vertical" tools:context = ".SecondActivity"> <TextView android:id = "@+id/text_view" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" /> </LinearLayout>
두 번째 화면에는 전달받은 값을 표시할 TextView 하나만 배치되어 있습니다.
5단계 – SecondActivity.java 작성
src/SecondActivity.java 파일에 아래 코드를 추가합니다.
package com.example.myapplication;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
TextView textView = findViewById(R.id.text_view);
SharedPreferences sharedPreferences = getSharedPreferences("myKey", MODE_PRIVATE);
String value = sharedPreferences.getString("value","");
textView.setText(value);
}
}SecondActivity에서는 MainActivity와 동일한 이름("myKey")의 SharedPreferences를 열어 "value" 키에 저장된 문자열을 읽어 온 뒤, TextView에 설정합니다. 이렇게 하면 별도의 인텐트 추가 데이터 없이도 두 액티비티 간에 데이터가 공유됩니다.
6단계 – AndroidManifest.xml 수정
androidManifest.xml 파일에 아래 코드를 추가합니다.
<?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "https://schemas.android.com/apk/res/android" package = "com.example.myapplication"> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name = ".SecondActivity"></activity> </application> </manifest>
반드시 SecondActivity를 매니페스트에 등록해야 합니다. 등록하지 않으면 액티비티를 실행할 때 ActivityNotFoundException이 발생합니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서
Run 아이콘을 클릭하세요. 실행 옵션 목록에서 자신의 모바일 기기를 선택하면, 모바일 화면에 아래와 같은 기본 화면이 표시됩니다.

첫 번째 화면에 원하는 문구를 입력하고 Next 버튼을 누르면, 두 번째 화면에서 SharedPreferences에 저장된 값이 그대로 출력되는 것을 확인할 수 있습니다.