Saturday, July 3, 2021

How to Save ArrayList to SharedPreferences in Android

How to Save ArrayList to SharedPreferences in Android

SharedPreferences in Android are local storage used to store strings, integers and variables in the phone memory so that we can manage the state of the application. We have seen storing simple variables in prefs shared with key and value pairs. In this article we will see How we can store ArrayList into shared preferences in our android application

Step 1: Create a New Project

Step 2: Adding dependency for gson in build.gradle

implementation ‘com.google.code.gson:gson:2.8.5’

Step 3: Creating a modal class for storing our data

Category.java

public class Category {

    public int id;

    public String title;

    public String label;


    public int getId() {

        return id;

    }


    public void setId(int id) {

        this.id = id;

    }


    public String getTitle() {

        return title;

    }


    public void setTitle(String title) {

        this.title = title;

    }


    public String getLabel() {

        return label;

    }


    public void setLabel(String label) {

        this.label = label;

    }

}

Step 4: Creating a class ShareCategory

ShareCategory.java

public class ShareCategory {

  public static final String MyPREFERENCES = "Category" ;

  public static final String Name = "Category";

  private Context mContext;

  private SharedPreferences sharedpreferences;


  public ShareCategory(Context context) {

    mContext = context;

    sharedpreferences = mContext.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

  }

  public void updateCategory(List<Category> listCategory) {

    Gson gson = new Gson();

    String json = gson.toJson(listCategory);

    SharedPreferences.Editor editor = sharedpreferences.edit();

    editor.putString(Name,json);

    editor.commit();

  }

  public List<Category> getCategory () {

    List<Category> listCategory = new ArrayList<>();

    Gson gson = new Gson();

    String json = sharedpreferences.getString("Category", null);

    Type type = new TypeToken<ArrayList<Category>>() {}.getType();

    listCategory = gson.fromJson(json, type);

    return listCategory;

  }

}

No comments:

Post a Comment