Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

android - 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;
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...