How to save ArrayList to SharedPreferences on Android?


Before getting into shared preference to store arraylist example , we should know what is shared preferences in android. Using share preference, we can store or retrieve values as key and value pair. There are five different methods are available in share preference as shown below −

  • Edit() − It going to edit shared preference values

  • commit() − it going to commit shared preference values in xml file

  • apply() − It going to commit back changes from editor to shared preference.

  • remove(String key) − It going to remove key and vales from shared preference use key.

  • Put() − It going to put key and values to shared preference xml.

A sample example syntax of shared preference as shown below −

final SharedPreferences sharedPreferences = getSharedPreferences("USER",MODE_PRIVATE);

In the above syntax we have created a shared preference file as USER.xml and it is private mode means no other applications can access this shared preference.

This below example demonstrate about how to use shared preference in android.

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"?>
<android.support.constraint.ConstraintLayout
   xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   android:orientation = "vertical"
   tools:context = ".MainActivity"
   tools:layout_editor_absoluteY = "81dp">
   <EditText
      android:id = "@+id/name"
      android:layout_width = "match_parent"
      android:layout_height = "60dp"
      android:layout_marginTop = "8dp"
      android:autofillHints = ""
      android:hint = "NAME"
      app:layout_constraintTop_toTopOf = "parent"
      tools:layout_editor_absoluteX = "0dp" />
   <EditText
      android:id = "@+id/address"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:layout_marginTop = "84dp"
      android:hint = "Phone Number"
      android:importantForAutofill = "no"
      android:inputType = ""
      app:layout_constraintTop_toTopOf = "@+id/name"
      tools:layout_editor_absoluteX = "16dp"
      tools:targetApi = "o" />
   <Button
      android:id = "@+id/button"
      android:layout_width = "108dp"
      android:layout_height = "wrap_content"
      android:layout_marginStart = "8dp"
      android:layout_marginLeft = "8dp"
      android:layout_marginTop = "120dp"
      android:layout_marginEnd = "8dp"
      android:layout_marginRight = "8dp"
      android:gravity = "center_horizontal"
      android:text = "Save"
      app:layout_constraintEnd_toEndOf = "parent"
      app:layout_constraintHorizontal_bias = "0.503"
      app:layout_constraintStart_toStartOf = "parent"
      app:layout_constraintTop_toTopOf = "@+id/address" />
   <Button
      android:id = "@+id/read"
      android:layout_width = "wrap_content"
      android:layout_height = "wrap_content"
      android:layout_marginStart = "8dp"
      android:layout_marginLeft = "8dp"
      android:layout_marginTop = "88dp"
      android:layout_marginEnd = "8dp"
      android:layout_marginRight = "8dp"
      android:gravity = "center_horizontal"
      android:text = "read"
      app:layout_constraintEnd_toEndOf = "parent"
      app:layout_constraintStart_toStartOf = "parent"
      app:layout_constraintTop_toBottomOf = "@+id/button" />
   <TextView
      android:id = "@+id/result"
      android:layout_width = "wrap_content"
      android:layout_height = "0dp"
      android:layout_marginStart = "8dp"
      android:layout_marginLeft = "8dp"
      android:layout_marginTop = "184dp"
      android:layout_marginEnd = "8dp"
      android:layout_marginRight = "8dp"
      android:text = "result"
      app:layout_constraintEnd_toEndOf = "parent"
      app:layout_constraintStart_toStartOf = "parent"
      app:layout_constraintTop_toBottomOf = "@+id/button" />
</android.support.constraint.ConstraintLayout>

In the above xml it contains two edit text for name and address, when user click on save button it going to store the values as an array in shared preferences and when user click on read button it going to read the values from array available in shared preferences.

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

package com.example.andy.myapplication;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      final ArrayList<String> arrPackage;
      setContentView(R.layout.activity_main);
      final SharedPreferences sharedPreferences = getSharedPreferences("USER",MODE_PRIVATE);
      final EditText name = findViewById(R.id.name);
      final EditText address = findViewById(R.id.address);
      final TextView result = findViewById(R.id.result);
      Button save = findViewById(R.id.button);
      Button read = findViewById(R.id.read);
      arrPackage = new ArrayList<>();
      read.setOnClickListener(new View.OnClickListener() {
         @SuppressLint("LongLogTag")
         @Override
         public void onClick(View v) {
            Gson gson = new Gson();
            String json = sharedPreferences.getString("Set", "");
            if (json.isEmpty()) {
               Toast.makeText(MainActivity.this,"There is something error",Toast.LENGTH_LONG).show();
            } else {
               Type type = new TypeToken<List<String>>() {
            }.getType();
            List<String> arrPackageData = gson.fromJson(json, type);
            for(String data:arrPackageData) {
               result.setText(data);
            }
         }
      }
   });
   save.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
         if(name.getText().toString().isEmpty() && address.getText().toString().isEmpty()) {
            Toast.makeText(MainActivity.this,"Plz Enter all the data",Toast.LENGTH_LONG).show();
         }else{
            String nameData = name.getText().toString().trim();
            String addressData = address.getText().toString().trim();
            arrPackage.add(nameData);
            arrPackage.add(addressData);
            Gson gson = new Gson();
            String json = gson.toJson(arrPackage);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("Set",json );
            editor.commit();
         }
      }
   });
}

In the above code, we have converted arraylist to GSON and grabbing GSON data as string.

Step 4 − To access GSON we need to add GSON Library in build.gradle as shown below −

apply plugin: 'com.android.application'
android {
   compileSdkVersion 28
   defaultConfig {
      applicationId "com.example.andy.myapplication"
      minSdkVersion 15
      targetSdkVersion 28
      versionCode 1
      versionName "1.0"
      testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
   }
   buildTypes {
      release {
         minifyEnabled false
         proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
      }
   }
}
dependencies {
   implementation fileTree(dir: 'libs', include: ['*.jar'])
   implementation 'com.google.code.gson:gson:2.8.5'
   implementation 'com.android.support:appcompat-v7:28.0.0'
   implementation 'com.android.support.constraint:constraint-layout:1.1.3'
   testImplementation 'junit:junit:4.12'
   androidTestImplementation 'com.android.support.test:runner:1.0.2'
   androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

Step 5 − No need to change manifest.xml 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 Play Icon icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

In the above example we have added name and address and clicked on save button.

In the above example, we have clicked on read button. it will append the text to text view

Updated on: 27-Jun-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements