0

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??

1

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

7 Comments

How to add the Gson?? Any jar file?
download the library's jar file and put it inside libs folder of your project. If you dont have such folder then create one manually. Afterwards you are ready to go.
@Waqas.. yeah i got it now.. its included..Thanks
@Waqas.. Shared pref is not reliable.. like when i exit the app and reload it and try to save new values then the old values are gone. CAn u suggest me any other way to keep old values in the array and adding new ones ??
which android API version are you using for your app? if its gingerbread or above then please call apply() instead of commit() on your preference editor.
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.