如何保存具有共享首选项的复选框值? [英] How to save checkbox value with shared preferences?

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

问题描述

我不知道为什么我的代码不保存checkbox检查值;如果我选中checkbox,然后单击另一个选项卡并返回上一个选项卡,则未选择checkbox ...我希望您在我的代码中找到错误!

I don't know why my code not save checkbox checked value; if I check checkbox and after I click on another tab and comeback to previous tab, checkbox is not selected...I hope that you find the error in my code!

IDE对我说:FATAL EXCEPTION: main java.lang.NullPointerException at line ".onCreateView(holder.chkBox.setChecked(true);"

为什么?

适配器类:

public abstract class PlanetAdapter extends ArrayAdapter<Planet> implements CompoundButton.OnCheckedChangeListener{

    private List<Planet> planetList;
    private Context context;
    ArrayList<Birra> objects;

    public PlanetAdapter(List<Planet> planetList, Context context) {
        super(context, R.layout.single_listview_item, planetList);
        this.planetList = planetList;
        this.context = context;
    }    

    public class PlanetHolder {
        public TextView planetName;
        public TextView distView;
        public TextView valuta;
        public CheckBox chkBox;
        public EditText edit;
        public String quantità;        
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row = convertView;
        PlanetHolder holder = null;
        if (row == null) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(R.layout.single_listview_item, parent, false);
            holder = new PlanetHolder();
            holder.planetName = (TextView) row.findViewById(R.id.name);
            holder.distView = (TextView) row.findViewById(R.id.dist);
            holder.valuta = (TextView) row.findViewById(R.id.valuta);
            holder.chkBox = (CheckBox) row.findViewById(R.id.chk_box);
            holder.edit = (EditText) row.findViewById(R.id.editText);
            holder.edit.setVisibility(View.GONE);
            holder.edit.setEnabled(false);
            row.setTag(holder);
        } else {
            holder = (PlanetHolder) row.getTag();
        }

        final Planet p = planetList.get(position);        
        final PlanetHolder finalHolder = holder;

        holder.chkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (finalHolder.chkBox.isChecked()) {
                    finalHolder.edit.setVisibility(View.VISIBLE);
                    finalHolder.edit.setEnabled(true);
                    SharedPreferences preferences = getContext().getSharedPreferences("MaterialTabs", android.content.Context.MODE_PRIVATE);

                    SharedPreferences.Editor mEditor = preferences.edit();
                    mEditor.putBoolean("CheckBox_Value", finalHolder.chkBox.isChecked());

                    mEditor.commit();

                    finalHolder.edit.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {
                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            p.setQuantità(finalHolder.edit.getText().toString().trim());
                            SharedPreferences preferences = getContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = preferences.edit();
                            editor.putString("KEY", finalHolder.edit.getText().toString().trim());

                            editor.commit();

                        }
                    });
                } else {
                    finalHolder.edit.setVisibility(View.GONE);
                    finalHolder.edit.setEnabled(false);
                    finalHolder.edit.setText(null);

                }

            }
        });
        holder.planetName.setText(p.getName());
        holder.distView.setText("" + p.getDistance());
        holder.valuta.setText("" + p.getValuta());
        holder.chkBox.setChecked(p.isSelected());
        holder.chkBox.setTag(p);
        holder.edit.setEnabled(false);

        return row;
    }

    ArrayList<Planet> getBox() {
        ArrayList<Planet> box = new ArrayList<Planet>();
        for (Planet p : planetList) {
            if (p.selected)
                box.add(p);
        }
        return box;
    }
}

片段:

ListView lv;
ArrayList<Planet> planetList;
PlanetAdapter plAdapter;
BirraAdapter biAdapter;
PlanetAdapter.PlanetHolder holder;

 public class MyListFragment extends Fragment implements
        android.widget.CompoundButton.OnCheckedChangeListener {

    ListView lv;
    ArrayList<Planet> planetList;
    PlanetAdapter plAdapter;
    BirraAdapter biAdapter;
    PlanetAdapter.PlanetHolder holder;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment    
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_list2, container, false);

        Button mButton = (Button) rootView.findViewById(R.id.button);
        mButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            showResult(v);


            }
        });

        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        lv = (ListView)getView().findViewById(R.id.listview);
        displayPlanetList();
    }


    private void displayPlanetList() {

        planetList = new ArrayList<Planet>();
        planetList.add(new Planet("Margherita", 6, "€"));
        planetList.add(new Planet("Diavola", 7,"€"));
        planetList.add(new Planet("Bufalina", 5,"€"));
        planetList.add(new Planet("Marinara", 5,"€"));
        planetList.add(new Planet("Viennese", 4, "€"));

        plAdapter = new PlanetAdapter(planetList, getContext()) {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                int pos = lv.getPositionForView(buttonView);
                if (pos != ListView.INVALID_POSITION) {
                    Planet p = planetList.get(pos);
                    p.setSelected(isChecked);      
                }        
            }
        };
        lv.setAdapter(plAdapter);
    }
    @Override
    public void onPause() {

        //get the instance variables
        SharedPreferences preferences = getContext().getSharedPreferences("MaterialTabs", android.content.Context.MODE_PRIVATE);
        boolean mCheckBoxValue = preferences.getBoolean("CheckBox_Value", false);

        if (mCheckBoxValue) {
            holder.chkBox.setChecked(true);        
        } else {
            holder.chkBox.setChecked(false);            
        }
        super.onPause();   
    }

    public void showResult(View v) {
        String  result2 = "Selected Product are :";
        int totalAmount2=0;

        String a="";
        for (Birra b : biAdapter.getBox()){

            if (b.selected){

                result2 += "\n" + b.name+" "+b.distance+"€"+"q.tà :"+b.getQuantità();
                int quantitaInt= Integer.parseInt(b.getQuantità());
                totalAmount2+=b.distance * quantitaInt;
            }
        }

        Toast.makeText(getActivity(), result2 + "\n" + "Total Amount:=" + totalAmount2 + "€", Toast.LENGTH_LONG).show();                                        
    }                
}

推荐答案

您可以在共享首选项上存储布尔值.这是一个例子.

You can store boolean values on shared preferences. Here's an example.

SharedPreferences myPrefs;
SharedPreferences.Editor myPrefsPrefsEditor;
static final String MY_SHARED_PREF = "name_of_your_shared_pref";

初始化您的共享首选项

myPrefs = this.getSharedPreferences(MY_SHARED_PREF, Context.MODE_PRIVATE);

使用以下命令存储您的值.

Store your values using the following.

myPrefsPrefsEditor = myPrefs.edit();
myPrefsPrefsEditor.putBoolean(key, value);
myPrefsPrefsEditor.commit();

key =用于从共享首选项中查找值

key = use to find the value from shared pref

value =您要存储的值

value = the value you want to store

这就是您读取值的方式

myPrefs.getBoolean(key, defaultValue);

key =您想要获取的值的键

key = the key of the value you want to get

defaultValue =当给定键没有值时的默认值.

defaultValue = the default value when there's no value for the given key.

希望这会有所帮助.

这篇关于如何保存具有共享首选项的复选框值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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