Android 如何仅在选中复选框的情况下对文件进行写入和读取?

Android 如何仅在选中复选框的情况下对文件进行写入和读取?,android,android-studio,checkbox,Android,Android Studio,Checkbox,我有一个问题:如果我选中一个复选框,然后单击另一个选项卡,然后返回到上一个选项卡,那么现在选中之前的复选框不会被选中……因此我认为保存和读取文件时,只需选中复选框。 我使用了共享首选项,但它不起作用。。。。 所以,我的问题是: 如何仅在选中复选框的情况下对文件进行写入和读取 我希望你能帮助我! 提前谢谢大家 这是我的代码: 适配器: public abstract class PlanetAdapter extends ArrayAdapter<Planet> implements

我有一个问题:如果我选中一个复选框,然后单击另一个选项卡,然后返回到上一个选项卡,那么现在选中之前的复选框不会被选中……因此我认为保存和读取文件时,只需选中复选框。 我使用了共享首选项,但它不起作用。。。。 所以,我的问题是:

如何仅在选中复选框的情况下对文件进行写入和读取

我希望你能帮助我! 提前谢谢大家

这是我的代码:

适配器:

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(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);
      SharedPreferences settings = context.getSharedPreferences("data", Context.MODE_PRIVATE);
      boolean Checked = settings.getBoolean("Material", false);
      holder.chkBox.setChecked(Checked);

      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 settings = context.getSharedPreferences("data", Context.MODE_PRIVATE);
                  settings.edit().putBoolean("Material", true).apply();
                  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());


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


    }
公共抽象类PlanetAdapter扩展ArrayAdapter实现CompoundButton.OnCheckedChangeListener
{
私人名单;
私人语境;
阵列列表对象;
公共平面捕捉器(列表平面列表、上下文){
超级(上下文、右布局、单个列表视图、平面列表);
this.planetList=planetList;
this.context=上下文;
}
公共级刨床{
公共文本视图平面名称;
公共文本视图;
公共文本视图valuta;
公共复选框chkBox;
公共编辑文本编辑;
公共字符串量化;
}
@凌驾
公共视图getView(最终整数位置、视图转换视图、视图组父视图){
视图行=转换视图;
刨刀夹持器=空;
if(行==null){
LayoutInflater充气器=((活动)上下文)。getLayoutInflater();
行=充气机。充气(R.layout.single\u listview\u项目,父项,false);
支架=新的刨床支架();
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=(复选框)row.findViewById(R.id.chk_框);
holder.edit=(EditText)row.findViewById(R.id.EditText);
holder.edit.setVisibility(View.GONE);
holder.edit.setEnabled(false);
row.setTag(支架);
}否则{
holder=(PlanetHolder)行。getTag();
}
最终行星p=行星列表get(位置);
SharedReferences设置=context.getSharedReferences(“数据”,context.MODE\u PRIVATE);
选中布尔值=设置。getBoolean(“材质”,false);
holder.chkBox.setChecked(已检查);
最终刨床最终刨床=保持架;
holder.chkBox.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
if(finalHolder.chkBox.isChecked()){
finalHolder.edit.setVisibility(View.VISIBLE);
finalHolder.edit.setEnabled(true);
SharedReferences设置=context.getSharedReferences(“数据”,context.MODE\u PRIVATE);
settings.edit().putBoolean(“Material”,true).apply();
finalHolder.edit.addTextChangedListener(新的TextWatcher(){
@凌驾
更改前文本之前的公共void(字符序列s、int start、int count、int after){
}
@凌驾
public void onTextChanged(字符序列、int start、int before、int count){
}
@凌驾
公共无效后文本已更改(可编辑){
p、 setQuantitá(finalHolder.edit.getText().toString().trim());
}
});
}否则{
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);
返回行;
}
ArrayList getBox(){
ArrayList box=新的ArrayList();
用于(行星p:行星列表){
如果(p.selected)
框。添加(p);
}
返回框;
}
}
片段:

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

    ListView lv;
    ArrayList<Planet> planetList;
    PlanetAdapter plAdapter;
    BirraAdapter biAdapter;
    PlanetAdapter.PlanetHolder holder;
    //boolean mCheckBoxValue;
    private CheckBox chkBox;


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





    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();
*/













    }



}
公共类MyListFragment扩展了片段实现
android.widget.CompoundButton.OnCheckedChangeListener{
ListView lv;
ArrayList planetList;
飞机适配器;
双适配器;
刨刀座;
//布尔值;
私有复选框chkBox;
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
//为该碎片膨胀布局
ViewGroup rootView=(ViewGroup)充气器。充气(R.layout.fragment_list2,容器,false);
Button mButton=(Button)rootView.findViewById(R.id.Button);
mButton.setOnClickListener(新视图.OnClickListener(){
公共void onClick(视图v){
展示结果(五);
}
});
//返回充气机。充气(R.layout.fragment_list2,容器,错误);
返回rootView;
}
@凌驾
已创建视图上的公共void(视图,@Nullable Bundle savedInstanceState){
super.onViewCreated(视图,savedInstanceState);
lv=(ListView)getView().findViewById(R.id.ListView);
displayPlanetList();
}
私有void displaytlist(){
planetList=新的ArrayList();
添加(新行星(“玛格丽塔”,6,“€”);
添加(新行星(“迪亚沃拉”,7,“€”);
添加(新行星(“Bufalina”,5,“€”);
添加(新行星(“Marinara”,5,“€”);
添加(新行星(“维也纳”,4“€”);
plAdapter=newplanetdapter(planetList,getContext()){
@凌驾
检查更改后的公共无效(复合按钮视图,布尔值已检查){
int pos=lv.getPositionForView(按钮视图);
    if(isChecked(){
checked = true;
}else{
checked = false;}
saveInFile();
private void loadFile(){
        FileInputStream fis = null;
        ObjectInputStream ois = null;

        if(this.isExternalStorageAvailable()) {
            try {
                fis = new FileInputStream(
                        new File(this.getExternalFilesDir("file"), "file.dat"));
                ois = new ObjectInputStream(fis);

                this.checked = (Boolean)ois.readObject();

            } catch (FileNotFoundException e) {
                //Toast.makeText(main, "File doesn't exist", Toast.LENGTH_SHORT).show();
            } catch (StreamCorruptedException e) {
                //Toast.makeText(main, "Error opening file", Toast.LENGTH_SHORT).show();
            } catch(EOFException e){
                try {
                    if(ois != null)
                        ois.close();

                    if(fis != null)
                        fis.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } catch (IOException e) {
                //Toast.makeText(main, "File read error", Toast.LENGTH_SHORT).show();
            } catch (ClassNotFoundException e) {
                //Toast.makeText(main, "Class Booelan doesn't exist", Toast.LENGTH_SHORT).show();
            }
        }
    }
    private void saveInFile(){
        if(this.isExternalStorageAvailable()){
            if(!this.isExternalStorageReadOnly()){
                try {
                    FileOutputStream fos = new FileOutputStream(
                            new File(this.getExternalFilesDir("file"), "file.dat"));
                    ObjectOutputStream oos = new ObjectOutputStream(fos);

                    oos.writeObject(checked);
                    oos.close();
                    fos.close();

                } catch (FileNotFoundException e) {
                    //Toast.makeText(main, "Error opening File", Toast.LENGTH_SHORT).show();
                } catch (IOException e) {
                    //Toast.makeText(main, "Error saving File", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
    private static boolean isExternalStorageAvailable(){
        String estadoSD = Environment.getExternalStorageState();
        if(Environment.MEDIA_MOUNTED.equals(estadoSD))
            return true;

        return false;
    }
    private static boolean isExternalStorageReadOnly(){
        String estadoSD = Environment.getExternalStorageState();
        if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(estadoSD))
            return true;

        return false;
    }
holder.chkBox.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {

              p.setSelected(finalHolder.chkBox.isChecked()); //add this

              if (finalHolder.chkBox.isChecked()) {
                  ...
              } else {
                  ...
              }

          }
      });
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState); // store value in key , value order
    outState.putInt("curChoice", mCurCheckPosition);
}
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
        }
}