How to use SharedPreferences on Android to store, read and edit values?

AndroidApps/ApplicationsMobile Development

This example demonstrates how do I use SharedPreferences on Android to store, read, and edit values.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:padding="8dp"
   tools:context=".MainActivity">
   <Button
      android:id="@+id/btnSave"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentStart="true"
      android:layout_centerInParent="true"
      android:onClick="Save"
      android:text="Save" />
   <Button
      android:id="@+id/btnRetrieve"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:layout_centerHorizontal="true"
      android:onClick="Get"
      android:text="Read" />
   <Button
      android:id="@+id/btnClear"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentEnd="true"
      android:layout_centerInParent="true"
      android:onClick="clear"
      android:text="Clear" />
   <EditText
      android:id="@+id/etEmail"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_below="@+id/etName"
      android:layout_alignParentEnd="true"
      android:layout_marginTop="10dp"
      android:ems="10"
      android:hint="Email"
      android:inputType="textEmailAddress" />
   <EditText
      android:id="@+id/etName"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_alignStart="@+id/etEmail"
      android:layout_marginTop="40dp"
      android:ems="10"
      android:hint="Name"
      android:inputType="text" />
</RelativeLayout>

Step 3 − Add the following code to src/MainActivity.java

package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
   EditText editTextName, editTextEmail;
   public static final String mypreference = "mypref";
   public static final String Name = "nameKey";
   public static final String Email = "emailKey";
   SharedPreferences sharedpreferences;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      editTextEmail = findViewById(R.id.etEmail);
      editTextName = findViewById(R.id.etName);
      sharedpreferences = getSharedPreferences(mypreference,
      Context.MODE_PRIVATE);
      if (sharedpreferences.contains(Name)) {
         editTextName.setText(sharedpreferences.getString(Name, ""));
      }
      if (sharedpreferences.contains(Email)) {
         editTextEmail.setText(sharedpreferences.getString(Email, ""));
      }
   }
   public void Save(View view) {
      String strName = editTextName.getText().toString();
      String strEmail = editTextEmail.getText().toString();
      SharedPreferences.Editor editor = sharedpreferences.edit();
      editor.putString(Name, strName);
      editor.putString(Email, strEmail);
      editor.apply();
      Toast.makeText(getApplicationContext(), "Saved", Toast.LENGTH_SHORT).show();
   }
   public void clear(View view) {
      editTextName = findViewById(R.id.etName);
      editTextEmail = findViewById(R.id.etEmail);
      editTextName.setText("");
      editTextEmail.setText("");
      Toast.makeText(getApplicationContext(), "Cleared",
      Toast.LENGTH_SHORT).show();
   }
   public void Get(View view) {
      editTextName = findViewById(R.id.etName);
      editTextEmail = findViewById(R.id.etEmail);
      sharedpreferences = getSharedPreferences(mypreference, Context.MODE_PRIVATE);
      if (sharedpreferences.contains(Name)) {
         editTextName.setText(sharedpreferences.getString(Name, ""));
      }
      if (sharedpreferences.contains(Email)) {
         editTextEmail.setText(sharedpreferences.getString(Email, ""));
      }
      Toast.makeText(getApplicationContext(), "Retrieved", Toast.LENGTH_SHORT).show();
   }
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
}

Step 4 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <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>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

Click here to download the project code.

raja
Published on 22-Nov-2019 17:27:23
Advertisements