How to Save ArrayList to SharedPreferences in Android?
SharedPreferences in Android is local storage that is used to store strings, integers, and variables in phone storage so that we can manage the state of the app. We have seen storing simple variables in shared prefs with key and value pair. In this article, we will see How we can store ArrayList to shared preferences in our Android app.
What we are going to build in this article?
We will be building a simple application in which we will be displaying course names with its description in a simple RecyclerView and we will be storing all this data in our shared preferences. So when we close our app and reopens our app all the data will be saved in shared preferences and the state of our recycler view is maintained. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Adding dependency for gson in build.gradle
Navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section.
implementation ‘com.google.code.gson:gson:2.8.5’
After adding this dependency sync your project.
Step 3: Creating a modal class for storing our data
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name your class as CourseModal and add the below code to it.
Java
public class CourseModal { // variables for our course // name and description. private String courseName; private String courseDescription; // creating constructor for our variables. public CourseModal(String courseName, String courseDescription) { this .courseName = courseName; this .courseDescription = courseDescription; } // creating getter and setter methods. public String getCourseName() { return courseName; } public void setCourseName(String courseName) { this .courseName = courseName; } public String getCourseDescription() { return courseDescription; } public void setCourseDescription(String courseDescription) { this .courseDescription = courseDescription; } } |
Step 4: Creating a layout file for our item of RecyclerView
Navigate to the app > res > layout > Right-click on it > New > layout resource file and name your layout as course_rv_item and add the below code to it.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < androidx.cardview.widget.CardView xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_margin = "8dp" android:elevation = "8dp" app:cardCornerRadius = "8dp" > < RelativeLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" > <!--text view for our course name--> < TextView android:id = "@+id/idTVCourseName" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:padding = "8dp" android:text = "Course Name" android:textColor = "@color/black" android:textSize = "18sp" /> <!--text view for our course description--> < TextView android:id = "@+id/idTVCourseDescription" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_below = "@id/idTVCourseName" android:padding = "5dp" android:text = "COurse Description" android:textColor = "@color/black" /> </ RelativeLayout > </ androidx.cardview.widget.CardView > |
Step 5: Creating an adapter class for setting data to items of our RecyclerView
Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseAdapter and add the below code to it.
Java
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.ViewHolder> { // creating a variable for array list and context. private ArrayList<CourseModal> courseModalArrayList; private Context context; // creating a constructor for our variables. public CourseAdapter(ArrayList<CourseModal> courseModalArrayList, Context context) { this .courseModalArrayList = courseModalArrayList; this .context = context; } @NonNull @Override public CourseAdapter.ViewHolder onCreateViewHolder( @NonNull ViewGroup parent, int viewType) { // below line is to inflate our layout. View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false ); return new ViewHolder(view); } @Override public void onBindViewHolder( @NonNull CourseAdapter.ViewHolder holder, int position) { // setting data to our views of recycler view. CourseModal modal = courseModalArrayList.get(position); holder.courseNameTV.setText(modal.getCourseName()); holder.courseDescTV.setText(modal.getCourseDescription()); } @Override public int getItemCount() { // returning the size of array list. return courseModalArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our views. private TextView courseNameTV, courseDescTV; public ViewHolder( @NonNull View itemView) { super (itemView); // initializing our views with their ids. courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseDescTV = itemView.findViewById(R.id.idTVCourseDescription); } } } |
Step 6: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
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" tools:context = ".MainActivity" > <!--edit text for adding course name--> < EditText android:id = "@+id/idEdtCourseName" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_toStartOf = "@id/idBtnSave" android:layout_toLeftOf = "@id/idBtnSave" android:hint = "Enter course Name" /> <!--edit text for adding course description--> < EditText android:id = "@+id/idEdtCourseDescription" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_below = "@id/idEdtCourseName" android:layout_marginEnd = "4dp" android:layout_marginRight = "4dp" android:layout_toLeftOf = "@id/idBtnAdd" android:hint = "Enter Course Description" /> <!--button for adding data to recycler view--> < Button android:id = "@+id/idBtnAdd" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_below = "@id/idEdtCourseName" android:layout_alignParentEnd = "true" android:layout_alignParentRight = "true" android:layout_margin = "10dp" android:text = "Add " /> <!--button for saving data to shared prefs--> < Button android:id = "@+id/idBtnSave" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignParentEnd = "true" android:layout_alignParentRight = "true" android:layout_margin = "10dp" android:text = "Save " /> <!--recycler view to display our data--> < androidx.recyclerview.widget.RecyclerView android:id = "@+id/idRVCourses" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_below = "@id/idEdtCourseDescription" /> </ RelativeLayout > |
Step 7: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for our ui components. private EditText courseNameEdt, courseDescEdt; private Button addBtn, saveBtn; private RecyclerView courseRV; // variable for our adapter class and array list private CourseAdapter adapter; private ArrayList<CourseModal> courseModalArrayList; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. courseNameEdt = findViewById(R.id.idEdtCourseName); courseDescEdt = findViewById(R.id.idEdtCourseDescription); addBtn = findViewById(R.id.idBtnAdd); saveBtn = findViewById(R.id.idBtnSave); courseRV = findViewById(R.id.idRVCourses); // calling method to load data // from shared prefs. loadData(); // calling method to build // recycler view. buildRecyclerView(); // on click listener for adding data to array list. addBtn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // below line is use to add data to array list. courseModalArrayList.add( new CourseModal(courseNameEdt.getText().toString(), courseDescEdt.getText().toString())); // notifying adapter when new data added. adapter.notifyItemInserted(courseModalArrayList.size()); } }); // on click listener for saving data in shared preferences. saveBtn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // calling method to save data in shared prefs. saveData(); } }); } private void buildRecyclerView() { // initializing our adapter class. adapter = new CourseAdapter(courseModalArrayList, MainActivity. this ); // adding layout manager to our recycler view. LinearLayoutManager manager = new LinearLayoutManager( this ); courseRV.setHasFixedSize( true ); // setting layout manager to our recycler view. courseRV.setLayoutManager(manager); // setting adapter to our recycler view. courseRV.setAdapter(adapter); } private void loadData() { // method to load arraylist from shared prefs // initializing our shared prefs with name as // shared preferences. SharedPreferences sharedPreferences = getSharedPreferences( "shared preferences" , MODE_PRIVATE); // creating a variable for gson. Gson gson = new Gson(); // below line is to get to string present from our // shared prefs if not present setting it as null. String json = sharedPreferences.getString( "courses" , null ); // below line is to get the type of our array list. Type type = new TypeToken<ArrayList<CourseModal>>() {}.getType(); // in below line we are getting data from gson // and saving it to our array list courseModalArrayList = gson.fromJson(json, type); // checking below if the array list is empty or not if (courseModalArrayList == null ) { // if the array list is empty // creating a new array list. courseModalArrayList = new ArrayList<>(); } } private void saveData() { // method for saving the data in array list. // creating a variable for storing data in // shared preferences. SharedPreferences sharedPreferences = getSharedPreferences( "shared preferences" , MODE_PRIVATE); // creating a variable for editor to // store data in shared preferences. SharedPreferences.Editor editor = sharedPreferences.edit(); // creating a new variable for gson. Gson gson = new Gson(); // getting data from gson and storing it in a string. String json = gson.toJson(courseModalArrayList); // below line is to save data in shared // prefs in the form of string. editor.putString( "courses" , json); // below line is to apply changes // and save data in shared prefs. editor.apply(); // after saving data we are displaying a toast message. Toast.makeText( this , "Saved Array List to Shared preferences. " , Toast.LENGTH_SHORT).show(); } } |
Now run your app and see the output of the app.
Contact Us