save arraylist in shared preference

2019-01-15 11:55发布

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;
        }
    }
}

5条回答
倾城 Initia
2楼-- · 2019-01-15 12:10

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);
            }
        }
查看更多
Bombasti
3楼-- · 2019-01-15 12:11

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.

查看更多
Luminary・发光体
4楼-- · 2019-01-15 12:12

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);
    }
查看更多
甜甜的少女心
5楼-- · 2019-01-15 12:17

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

查看更多
地球回转人心会变
6楼-- · 2019-01-15 12:31

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

查看更多
登录 后发表回答