Get and set SharedPreferences

Description

The following code shows how to Get and set SharedPreferences.

Example

Main layout xml file


<?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"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="I'm App1!"
    />
</LinearLayout>

Main Activity Java code


import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
// www  . j  a va 2  s .  c o m
public class MainActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      SharedPreferences prefs = getSharedPreferences("app1prefs", MODE_PRIVATE);
      String value = "Hello from App1 preference file!";
      prefs.edit().putString("shared_value", value).commit();
   }

   @Override
   public String toString() {
      return "Hello from App1 toString()!";
   }
}
Get and set SharedPreferences




















Home »
  Android »
    Android Basics »




Hello Android
Resources
Activity
Calendar
Camera
Contact
Content Provider
Database
Hardware
Intent
Location
Media
Network
Notification
Preference
Sensor
Service
SMS