如何将保存复选框签入数据库?

时间:2016-05-14 08:17:09

标签: android sqlite checkbox android-sqlite

我需要将选中的复选框保存到sqlite database,因为如果我选中checkbox并点击其他tab,点击上一个标签后,则不会选中现在选中前的复选框。 ... 我向你求婚! 提前致谢! 这是我的代码:

ADAPTER:

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

{

    private List<Planet> planetList;
    private Context context;
    ArrayList<Birra> objects;
    SharedPreferences settings;
    public boolean Checked;

    public  PlanetAdapter(List<Planet> planetList, Context context) {

        super(context, R.layout.single_listview_item, planetList);
        settings = context.getSharedPreferences("data", Context.MODE_PRIVATE);
        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à;
        public boolean checked;
    }


    @Override
    public View getView(final 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);
        settings = context.getSharedPreferences("data", Context.MODE_PRIVATE);



        Checked= settings.getBoolean("Material", false);
        if(Checked) {
           // System.out.println(Checked);
            holder.chkBox.setChecked(true);
        }else{
            System.out.println(Checked);
        }


        final PlanetHolder finalHolder = holder;


        holder.chkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (finalHolder.chkBox.isChecked()) {
                    finalHolder.edit.setVisibility(View.VISIBLE);
                    finalHolder.edit.setEnabled(true);
                    settings.edit().putBoolean("Material", finalHolder.chkBox.isChecked()).commit();
                    System.out.println("presa");
                } else {
                    finalHolder.edit.setVisibility(View.GONE);
                    finalHolder.edit.setEnabled(false);
                    finalHolder.edit.setText("");
                    settings.edit().putBoolean("Material", finalHolder.chkBox.isChecked()).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());


            }
        });


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

}

FRAGMENT:

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);
        /*mSharedPreferences = getContext().getSharedPreferences("data", Context.MODE_PRIVATE);
        Boolean mIsChecked = mSharedPreferences.getBoolean("zao", false);
        holder.chkBox.setChecked(mIsChecked);*/


    /*  SharedPreferences settings = getContext().getSharedPreferences("data", Context.MODE_PRIVATE);
        boolean Checked = settings.getBoolean("Material", false);
        //holder.chkBox.setChecked(Checked);
        if (Checked == true){ //false is default value
            holder.chkBox.setChecked(true); //it was checked
        } else{
            holder.chkBox.setChecked(false);
        }*/
        Button mButton = (Button) rootView.findViewById(R.id.button);
        mButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showResult(v);


            }
        });
        //return inflater.inflate(R.layout.fragment_list2, container, false);
        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);


            /*Toast.makeText(
                getActivity(),
                "Clicked on Pizza: " + p.getName() + ". State: is "
                        + isChecked, Toast.LENGTH_SHORT).show();*/
                }


            }
        };

        lv.setAdapter(plAdapter);
        //plAdapter.notifyDataSetChanged();
    }



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


            *//*Toast.makeText(
                getActivity(),
                "Clicked on Planet: " + p.getName() + ". State: is "
                        + isChecked, Toast.LENGTH_SHORT).show();*//*
        }*/

    }


    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;
                //a=String.valueOf(totalAmount);


            }
        }
    /*  for (Planet p : plAdapter.getBox()) {
            if (p.selected){

                result += "\n" + p.name+" "+p.distance+"€"+"q.tà :"+p.getQuantità();
                int quantitaInt= Integer.parseInt(p.getQuantità() );
                totalAmount+=p.distance * quantitaInt;
                //a=String.valueOf(totalAmount);


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

        /*Bundle bun2 = new Bundle();
        bun2.putString("scelta", result);
        TwoFragment fgsearch2 = new TwoFragment();
        fgsearch2.setArguments(bun2);
        android.support.v4.app.FragmentTransaction transaction2 = getActivity().getSupportFragmentManager().beginTransaction();
        transaction2.replace(R.id.content_main, fgsearch2);
        transaction2.commit();


        Bundle bun = new Bundle();
        bun.putString("totale", a);
        TwoFragment fgsearch = new TwoFragment();
        fgsearch.setArguments(bun);
        android.support.v4.app.FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.content_main2, fgsearch);
        transaction.commit();
*/













    }



}

2 个答案:

答案 0 :(得分:0)

您想使用sqlite进行保存检查,或者您已经在使用sqlite数据库吗?

首先,当您返回检查页面时,要显示正确的检查项目,您需要将其临时存储在ArrayList中。 您也可以使用HashMap。

HashMap<Integer,boolean> checkMap = new HashMap<>();

现在进行检查时,只需将该值添加到地图中,就像这样

checkmap.put(position,true) or checkmap.put(position,false)// if unchecked.

您可以在MainActivity中将此checkmap设置为静态,当您返回检查页面时,只需检查hashmap值,如果为true,则在适配器中再次检查该项目。

if(checkMap.get(position)){ 
    // check the check box
} else { 
    // else uncheck the box 
}

现在,您将始终在hashmap中拥有已选中和未选中的值。 现在你必须遍历所有值并将它们存储在sqlite中。 对于sqlite,您可以使用以下库:http://satyan.github.io/sugar/

答案 1 :(得分:0)

您仍然可以使用共享偏好设置实现目标,但您需要正确映射keyvalue。我认为planetName在这里是独一无二的。因此,如果planetName是唯一的,则"Material_"+planetName将是唯一的,您可以使用它来保存和检索共享偏好设置中的数据:

变化:

Checked= settings.getBoolean("Material", false);

要:

Checked= settings.getBoolean("Material_"+holder.planetName.getText().toString(), false);

并修改您的点击监听器,如下所示:

holder.chkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (finalHolder.chkBox.isChecked()) {
                    finalHolder.edit.setVisibility(View.VISIBLE);
                    finalHolder.edit.setEnabled(true);
                    settings.edit().putBoolean("Material_"+finalHolder.planetName.getText().toString(), finalHolder.chkBox.isChecked()).commit();
                    System.out.println("presa");
                } else {
                    finalHolder.edit.setVisibility(View.GONE);
                    finalHolder.edit.setEnabled(false);
                    finalHolder.edit.setText("");
                    settings.edit().putBoolean("Material_"+finalHolder.planetName.getText().toString(), finalHolder.chkBox.isChecked()).commit();
                }

            }
        });