Noman
Noman

Reputation: 4109

Store ArrayList of Objects in Android

I have an ArrayList of String objects that is keeping values as needed.
now i want to keep it save either as a FILE or in SharedPreferences or converting it into JSON ARRAY and saving..
My array list is like this:

  ArrayList<Struct_Saved_Domains> arraylist = new ArrayList<Struct_Saved_Domains>();

How can i do this? Any Idea??

Upvotes: 0

Views: 3578

Answers (2)

itsrajesh4uguys
itsrajesh4uguys

Reputation: 4638

You can use the below code for shared preferences.

public class WebService {

    String PREF_NAME = "PREF_NAME";
    public static SharedPreferences sp;
    Editor spEdit;

    public String UserID;
    public String Password;


    public LoginWebService(Context ctx) {
        // TODO Auto-geneated constructor stub
        sp = ctx.getSharedPreferences(PREF_NAME, 0);
        spEdit = sp.edit();
    }

    public void setUserID(String UserID) {
        spEdit.putString("UserID", UserID);
        spEdit.commit();

    }

    public String getUserID() {
        return sp.getString("UserID", "");    
    }

    public String getPassword() {
        return sp.getString("Password", "");
    }

    public void setPassword(String Password) {
        spEdit.putString("Password", Password);
        spEdit.commit();
    }





    public void clear(){
        spEdit.clear();
        spEdit.commit();
    }

}

While saving the data in the shared preferences you can use like below.

WebService objlogin=new WebService(context);
objlogin.clear();

for (int i = 0; i <arraylist.size(); i++) 
{
objlogin.setUserID(arraylist.get(i).something); 
objlogin.setPassword(arraylist.get(i).something); 

}

Then you all the data's will be saved in the shard preferences.

Hope this will help you.

Upvotes: 1

waqaslam
waqaslam

Reputation: 68167

You may use Gson to convert your object into string and then save it in shared preferences:

SharedPreferences prefs = context.getSharedPreferences("prefName", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putStringSet("myList", new Gson().toJson(arraylist).toString());
editor.apply();

Upvotes: 2

Related Questions