65.9K
CodeProject is changing. Read more.
Home

Shared Preferences (ANDROID)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.17/5 (4 votes)

Jan 20, 2014

CPOL
viewsIcon

14190

Using shared preferences in Android

Introduction

Interface for accessing and modifying preference data is returned by getSharedPreferences(String, int). For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an SharedPreferences.Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage.

Background

Sometimes, you need to keep store the record without saving in sqlite or using any storage element. Shared Preference is used for storing the values even after you close the app.

Using the Code

We are going to make a project that will store the text what you have typed in the editText box and when you close the app and open it again, it will show the text in the editText box that you have written before.

  • Create a project.
  • Add a editText box to the XML file.
  • Open the Java file and type the code...

The code is as follows:

package com.prefe.project;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.EditText;

public class SharedPreferencesActivity<et> extends Activity {

private EditText et;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        et = (EditText) findViewById(R.id.editText1);
       
        SharedPreferences settings = getSharedPreferences("MYPREFS",0);
        et.setText(settings.getString("tvalue", ""));       
    }
   
@Override
protected void onStop() {
super.onStop();
SharedPreferences settings = getSharedPreferences("MYPREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("tvalue", et.getText().toString());
editor.commit();
}
} 

319541/pic0.JPG

References