Aditya Vyas-Lakhan
Aditya Vyas-Lakhan

Reputation: 13555

save arraylist in shared preference

I am storing values in ArrayList and pass it to using bundle to next Fragment, and there I set values to my TextView, till here it works fine, now when go to another page and proceed to app and come back again to that Fragment, my all data goes, so I am trying to store it in preferences but preference don't allow to access ArrayList, following is my code

 public class Add_to_cart extends Fragment {

    private Button continue_shopping;
    private Button checkout;
    ListView list;
    private TextView _decrease,mBTIncrement,_value;
    private CustomListAdapter adapter;
    private ArrayList<String> alst;
    private ArrayList<String> alstimg;
    private ArrayList<String> alstprc;
    private String bname;
    private ArrayList<String> alsttitle;
    private ArrayList<String> alsttype;

    public static ArrayList<String> static_Alst;
    public Add_to_cart(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

        final View rootView = inflater.inflate(R.layout.list_view_addtocart, container, false);

        alst=new ArrayList<String>();
        alstimg=new ArrayList<String>();
        Bundle bundle = this.getArguments();
        alst = bundle.getStringArrayList("prducts_id");
        alsttype = bundle.getStringArrayList("prducts_type");
        alstimg=bundle.getStringArrayList("prducts_imgs");
        alsttitle=bundle.getStringArrayList("prducts_title");

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        System.out.println("TEst--" + alst);

       // Toast.makeText(getActivity(),"Testing"+alstimg,Toast.LENGTH_LONG).show();
        list=(ListView)rootView.findViewById(R.id.list_addtocart);

        adapter = new CustomListAdapter(getActivity(),alst,alstimg,alsttitle,alsttype);

        list.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                // TODO Auto-generated method stub
            }
        });
        return rootView;
    }

    public class CustomListAdapter extends BaseAdapter {

        private Context context;
        private ArrayList<String> listData;
        private ArrayList<String> listDataimg;
        private ArrayList<String> listDatatitle;
        private ArrayList<String> listDatatype;
        private AQuery aQuery;
        String dollars="\u0024";

        public CustomListAdapter(Context context,ArrayList<String> listData,ArrayList<String> listDataimg,ArrayList<String> listDatatitle,ArrayList<String> listDatatype) {
            this.context = context;
            this.listData=listData;
            this.listDataimg=listDataimg;
            this.listDatatitle=listDatatitle;
            this.listDatatype=listDatatype;
           aQuery = new AQuery(this.context);
        }

        public void save_User_To_Shared_Prefs(Context context) {
            SharedPreferences appSharedPrefs = PreferenceManager
                    .getDefaultSharedPreferences(context.getApplicationContext());
            SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
            Gson gson = new Gson();
            String json = gson.toJson(listData);
            Add_to_cart.static_Alst=listData;
            prefsEditor.putString("user", json);
            prefsEditor.commit();
        }

        @Override
        public int getCount() {
            return listData.size();
        }

        @Override
        public Object getItem(int position) {
            return listData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(getActivity()).inflate(R.layout.list_item_addtocart, null);
                holder.propic = (ImageView) convertView.findViewById(R.id.img_addtocart);
                holder.txtproname = (TextView) convertView.findViewById(R.id.proname_addtocart);
                holder.txtprofilecast = (TextView) convertView.findViewById(R.id.proprice_addtocart);
                holder.txtsize = (TextView) convertView.findViewById(R.id.txt_size);
                _decrease = (TextView) convertView.findViewById(R.id.minuss_addtocart);
                mBTIncrement = (TextView) convertView.findViewById(R.id.plus_addtocart);
                _value = (EditText)convertView.findViewById(R.id.edt_procount_addtocart);

                convertView.setTag(holder);
            }else{
                holder = (ViewHolder) convertView.getTag();
            }

            mBTIncrement.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    increment();
                }
            });

            _decrease.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    decrement();
                }
            });

            holder.txtprofilecast.setText(dollars+listData.get(position));
            holder.txtproname.setText(listDatatitle.get(position));
            holder.txtsize.setText(listDatatype.get(position));
            System.out.println("Image ka array " + listDataimg.get(position));

            //Picasso.with(mContext).load(mThumbIds[position]).centerCrop().into(imageView);
            // Picasso.with(context).load(listDataimg.get(position)).into(holder.propic);
            aQuery.id(holder.propic).image(listDataimg.get(position), true, true, 0, R.drawable.ic_launcher);

            return convertView;
        }

        class ViewHolder{
            ImageView propic;
            TextView txtproname;
            TextView txtprofilecast;
            TextView txtsize;
        }
    }
}

Upvotes: 0

Views: 13204

Answers (5)

Moubeen Farooq Khan
Moubeen Farooq Khan

Reputation: 2885

First download Gson.jar from below link and then add it to libs folder of your project

http://www.java2s.com/Code/Jar/g/Downloadgson17jar.htm

then put That ArrayList in the Class and make object of that class then you can save that object to SharedPreferences like below

public static void save_User_To_Shared_Prefs(Context context, User _USER) {
    SharedPreferences appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(context.getApplicationContext());
    SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(_USER);
    prefsEditor.putString("user", json);
    prefsEditor.commit();

 }

above code is an example _USER objext contain ArrayList.

And to read the object have a look at below code

 public static User get_User_From_Shared_Prefs(Context context) {

    SharedPreferences appSharedPrefs = PreferenceManager
            .getDefaultSharedPreferences(context.getApplicationContext());
    Gson gson = new Gson();
    String json = appSharedPrefs.getString("user", "");


    User user = gson.fromJson(json, User.class);
    return user;
} 

now when you want to get the _USER object call the above function and in result you will have the object and in that you will have the ArrayList

Upvotes: 0

nirav kalola
nirav kalola

Reputation: 1220

Complete example of storing and retrieving arraylist in sharedpreference:http://blog.nkdroidsolutions.com/arraylist-in-sharedpreferences/

  public void storeFavorites(Context context, List favorites) {
    // used for store arrayList in json format
            SharedPreferences settings;
            Editor editor;
            settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
            editor = settings.edit();
            Gson gson = new Gson();
            String jsonFavorites = gson.toJson(favorites);
            editor.putString(FAVORITES, jsonFavorites);
            editor.commit();
        }


        public ArrayList loadFavorites(Context context) {
    // used for retrieving arraylist from json formatted string
            SharedPreferences settings;
            List favorites;
            settings = context.getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
            if (settings.contains(FAVORITES)) {
                String jsonFavorites = settings.getString(FAVORITES, null);
                Gson gson = new Gson();
                BeanSampleList[] favoriteItems = gson.fromJson(jsonFavorites,BeanSampleList[].class);
                favorites = Arrays.asList(favoriteItems);
                favorites = new ArrayList(favorites);
            } else
                return null;
            return (ArrayList) favorites;
        }


        public void addFavorite(Context context, BeanSampleList beanSampleList) {
            List favorites = loadFavorites(context);
            if (favorites == null)
                favorites = new ArrayList();
            favorites.add(beanSampleList);
            storeFavorites(context, favorites);
        }


        public void removeFavorite(Context context, BeanSampleList beanSampleList) {
            ArrayList favorites = loadFavorites(context);
            if (favorites != null) {
                favorites.remove(beanSampleList);
                storeFavorites(context, favorites);
            }
        }

Upvotes: 3

sjain
sjain

Reputation: 23344

You can use gson:

To Save Preferences:

 public void save_User_To_Shared_Prefs(Context context, List<User> users) {
        SharedPreferences settings;
        Editor editor;

        settings = context.getSharedPreferences(PREFS_NAME,
                Context.MODE_PRIVATE);
        editor = settings.edit();

        Gson gson = new Gson();
        String jsonUsers = gson.toJson(users);

        editor.putString(USERS, jsonUsers);

        editor.commit();
    }

To get Preferences:

public ArrayList<User> getUsers(Context context) {
        SharedPreferences settings;
        List<User> users;

        settings = context.getSharedPreferences(PREFS_NAME,
                Context.MODE_PRIVATE);

        if (settings.contains(USERS)) {
            String jsonUsers = settings.getString(USERS, null);
            Gson gson = new Gson();
            User[] userItems = gson.fromJson(jsonUsers,
                    User[].class);

            users = Arrays.asList(userItems);
            users= new ArrayList<User>(users);
        } else
            return null;

        return (ArrayList<User>) users;
    }

To add user:

public void addUser(Context context, User user) {
        List<Product> favorites = getUsers(context);
        if (users == null)
            users = new ArrayList<User>();
        users.add(user);
        save_User_To_Shared_Prefs(context, users);
    }

Upvotes: 1

user5132172
user5132172

Reputation:

An alternative solution (just thought of it):

If you have an array called addtos and you want to add the array to shared preferences, since the variable is represented in the dictionary as a String, you could append the array index to the end of that string.

e.g -

Storing

for(int i = 0; i<addtos.size(); i++)
    prefsEditor.putString("addtos"+i, addtos.get(i));

Receiving

int i = 0;
while(true){
    if(prefs.getString("addtos"+i, "")!=""){  // or whatever the default dict value is
        // do something with it
        i++;
    }else{break;}
}

Seems ok to me, if anyone sees a problem with this, let me know.

Also, no need for ArrayLists

Upvotes: 0

Surendar D
Surendar D

Reputation: 5644

Use tinydb. check following link you might get some idea. https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo

using tinydb you can store array in local db.

Upvotes: 2

Related Questions