如何存储在共享preference ArrayList的价值观? [英] How to store arraylist values in shared preference?

查看:184
本文介绍了如何存储在共享preference ArrayList的价值观?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ArrayList中存储的值,并把它传递给使用捆绑到下一个片段,还有我设定值我TextView的,到这里能正常工作,现在当转到另一个页面,进入应用程序,并再次回来了片段,我所有的数据了,所以我试图将其存储在preferences但preference不允许访问数组列表,下面是我的code

 公共类add_to_cart这个扩展片段{

    私人按钮continue_shopping;
    私人按钮结账;
    ListView控件列表;
    私人TextView的_decrease,mBTIncrement,_value;
    私人CustomListAdapter适配器;
    私人的ArrayList<字符串> alst;
    私人的ArrayList<字符串> alstimg;
    私人的ArrayList<字符串> alstprc;
    私人字符串BNAME;
    私人的ArrayList<字符串> alsttitle;
    私人的ArrayList<字符串> alsttype;

    公共静态的ArrayList<字符串> static_Alst;
    公共add_to_cart这个(){}


    @覆盖
    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
                             捆绑savedInstanceState){

        最后查看rootView = inflater.inflate(R.layout.list_view_addtocart,集装箱,假);


        alst =新的ArrayList<字符串>();
        alstimg =新的ArrayList<字符串>();
         捆绑包= this.getArguments();
        alst = bundle.getStringArrayList(prducts_id);
        alsttype = bundle.getStringArrayList(prducts_type);
        alstimg = bundle.getStringArrayList(prducts_imgs);
        alsttitle = bundle.getStringArrayList(prducts_title);

        。StrictMode.ThreadPolicy政策=新StrictMode.ThreadPolicy.Builder()permitAll()建();
        StrictMode.setThreadPolicy(政策);

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



       // Toast.makeText(getActivity(),测试+ alstimg,Toast.LENGTH_LONG).show();
        名单=(ListView控件)rootView.findViewById(R.id.list_addtocart);


        适配器=新CustomListAdapter(getActivity(),alst,alstimg,alsttitle,alsttype);

        list.setAdapter(适配器);
        adapter.notifyDataSetChanged();
        list.setOnItemClickListener(新AdapterView.OnItemClickListener(){

            @覆盖
            公共无效onItemClick(适配器视图<>母公司视图中查看,
                                    INT位置,长的id){
                // TODO自动生成方法存根

            }
        });


        返回rootView;
    }



    公共类CustomListAdapter扩展了BaseAdapter {

        私人上下文的背景下;
        私人的ArrayList<字符串>的ListData;
        私人的ArrayList<字符串> listDataimg;
        私人的ArrayList<字符串> listDatatitle;
        私人的ArrayList<字符串> listDatatype;
       私人AQuery aQuery;

        字符串美元=\ u0024;


        公共CustomListAdapter(上下文的背景下,ArrayList的<字符串>的ListData,ArrayList的<字符串> listDataimg,ArrayList的<字符串> listDatatitle,ArrayList的<字符串> listDatatype){
            this.context =背景;
            this.listData =的ListData;
            this.listDataimg = listDataimg;
            this.listDatatitle = listDatatitle;
            this.listDatatype = listDatatype;
           aQuery =新AQuery(this.context);
        }

        公共无效save_User_To_Shared_ preFS(上下文的背景下){
            共享preferences appShared preFS = preferenceManager
                    .getDefaultShared preferences(context.getApplicationContext());
            共享preferences.Editor prefsEditor = appShared prefs.edit();
            GSON GSON =新GSON();
            JSON字符串= gson.toJson(的ListData);
            Add_to_cart.static_Alst =的ListData;
            prefsEditor.putString(用户,JSON);
            prefsEditor.commit();

        }
        @覆盖
        公众诠释getCount将(){
            返回listData.size();
        }

        @覆盖
        公共对象的getItem(INT位置){
            返回listData.get(位置);
        }

        @覆盖
        众长getItemId(INT位置){
            返回的位置;
        }

        @覆盖
        公共查看getView(最终诠释的立场,观点convertView,ViewGroup中父){
            ViewHolder持有人;
            如果(convertView == NULL){
                持有人=新ViewHolder();
                convertView = LayoutInflater.from(getActivity())膨胀(R.layout.list_item_addtocart,空)。
                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(保持器);
            }其他{
                支架=(ViewHolder)convertView.getTag();
            }


            mBTIncrement.setOnClickListener(新View.OnClickListener(){
                @覆盖
                公共无效的onClick(视图查看){
                    增量();
                }
            });

            _decrease.setOnClickListener(新View.OnClickListener(){
                @覆盖
                公共无效的onClick(视图查看){

                    递减();
                }
            });


            holder.txtprofilecast.setText(元+ listData.get(位置));
            holder.txtproname.setText(listDatatitle.get(位置));
            holder.txtsize.setText(listDatatype.get(位置));
            的System.out.println(图像か阵+ listDataimg.get(位置));

         // Picasso.with(mContext).load(mThumbIds [位置])centerCrop()成(ImageView的)。
          // Picasso.with(上下文).load(listDataimg.get(位置))到(holder.propic)。
          aQuery.id(holder.propic)在图像配(listDataimg.get(位置),真正的,真实的,0,R.drawable.ic_launcher);

            返回convertView;
        }
        类ViewHolder {
            ImageView的propic;
            TextView的txtproname;
            TextView的txtprofilecast;
            TextView的txtsize;
        }
 

解决方案

弗里斯特下载Gson.jar从下面链接,然后将其添加到库项目的文件夹

http://www.java2s.com/$c$ C /罐/ G / Downloadgson17jar.htm

然后把那ArrayList中的类,使该类的对象,那么你可以保存objext共享preFS像下面

 公共静态无效save_User_To_Shared_ preFS(上下文的背景下,用户_user){
    共享preferences appShared preFS = preferenceManager
            .getDefaultShared preferences(context.getApplicationContext());
    共享preferences.Editor prefsEditor = appShared prefs.edit();
    GSON GSON =新GSON();
    JSON字符串= gson.toJson(_user);
    prefsEditor.putString(用户,JSON);
    prefsEditor.commit();

 }
 

以上code是objext包含ArrayList的一个例子_user。

和读取对象看看下面code

 公共静态用户get_User_From_Shared_ preFS(上下文的背景下){

    共享preferences appShared preFS = preferenceManager
            .getDefaultShared preferences(context.getApplicationContext());
    GSON GSON =新GSON();
    JSON字符串= appShared prefs.getString(用户,);


    用户USER = gson.fromJson(JSON,User.class);
    返回用户;
}
 

现在,当你想获得_user对象调用上面的功能和效果,您将拥有的对象,并在你将有数组列表。

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 gone,so i am trying to store it in preferences but preference not 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;
        }

解决方案

Frist 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 objext to shared prefs 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.

这篇关于如何存储在共享preference ArrayList的价值观?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆