共享首选项和onPause不起作用

时间:2016-05-10 10:28:29

标签: android listview android-fragments android-studio checkbox

如果我选中一个复选框并进入选项卡而不带列表视图的复选框并进入上一个选项卡,我看到之前选中的复选框...但如果我点击带有复选框的列表视图的另一个选项卡,我的程序崩溃...为什么? 现在我发布我的代码...... 我希望你能帮助我!

提前致谢!

ADAPTER CLASS:

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


        final PlanetHolder finalHolder = holder;




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

        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 editor = preferences.edit();
                  editor.putBoolean("showActivity", finalHolder.chkBox.isChecked());
                  editor.commit();*/
                    // boolean value= true;
                    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;
    }
}

带有CHECKBOX LISTVIEW的第一个碎片类:

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

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

没有LISTVIEW的第二个碎片:

public class TwoFragment extends Fragment {

    private View v;
    Intent chooser = null;


    public TwoFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_two, container, false);
        Button mButton = (Button) rootView.findViewById(R.id.newbutton);
        mButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                sendemail();


            }
        });
        TextView titolo3 = (TextView) rootView.findViewById(R.id.result2);
        TextView titolo2 = (TextView) rootView.findViewById(R.id.quantità2);
        //TextView titolo = (TextView)rootView.findViewById(R.id.quantità3);

        Bundle bundle2 = getArguments();
        if (bundle2 != null) {
            String string = bundle2.getString("scelta2", null);
            titolo3.setText(string);
        }
        Bundle bundle = getArguments();
        if (bundle != null) {
            String myInt = bundle.getString("totale2", null);
            titolo2.setText(myInt);

        }
       /*  Bundle bundle3=getArguments();
        if(bundle3 != null){
             String valuta=bundle3.getString("valuta", null);
             titolo.setText(valuta);

        }*/
        return rootView;
    }

    public void sendemail() {

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setData(Uri.parse("mailto:"));
        String[] to = {"marco_marcoletto@hotmail.it"};
        intent.putExtra(Intent.EXTRA_EMAIL, to);
        intent.putExtra(Intent.EXTRA_SUBJECT, "ciao");
        intent.putExtra(Intent.EXTRA_TEXT, "zao");
        intent.setType("message/rfc822");
        chooser = intent.createChooser(intent, "manda email");
        startActivity(chooser);
    }
}

带有CHECKBOX LISTVIEW的第三个片段:

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

    ListView lv2;
    ArrayList<Birra> birraList;
    BirraAdapter biAdapter;
    BirraAdapter.BirraHolder birraHolder;
    BirraAdapter.BirraHolder holderr;


    public ThreeFragment() {
        // Required empty public constructor
    }


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

        Button mButton = (Button) rootView.findViewById(R.id.button2);
        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);

        lv2 = (ListView) getView().findViewById(R.id.listview2);
        displayBirraList();
    }


    private void displayBirraList() {

        birraList = new ArrayList<Birra>();
        birraList.add(new Birra("Paulaner", 6, "€"));
        birraList.add(new Birra("Forst", 7, "€"));
        birraList.add(new Birra("Peroni", 5, "€"));
        birraList.add(new Birra("Corona", 5, "€"));
        birraList.add(new Birra("Nastro Azzurro", 4, "€"));
        biAdapter = new BirraAdapter(birraList, getContext()) {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int pos = lv2.getPositionForView(buttonView);
                if (pos != ListView.INVALID_POSITION) {
                    Birra b = birraList.get(pos);
                    b.setSelected(isChecked);


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


            }
        };
        lv2.setAdapter(biAdapter);
    }

   /* @Override
    public void onPause() {

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

        if (mCheckBoxValuee) {
            holderr.chkBox_birra.setChecked(true);


        } else {
            holderr.chkBox_birra.setChecked(false);



        }
        super.onPause();
    }

*/

    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 result = "Selected Product are :";
        int totalAmount = 0;
        String c = "";

        for (Birra b : biAdapter.getBox()) {
            if (b.selected) {

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


            }
        }
        Toast.makeText(getActivity(), result + "\n" + "Total Amount:=" + totalAmount + "€", Toast.LENGTH_LONG).show();
       /* Bundle bun2 = new Bundle();
        bun2.putString("scelta2", 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("totale2", c);
        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();*/
    }
}

logcat的:

05-10 12:34:17.975 20371-20371/info.androidhive.materialtabs E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at info.androidhive.materialtabs.activity.MyListFragment.onPause(MyListFragment.java:103)
at android.support.v4.app.Fragment.performPause(Fragment.java:2139)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1117)
at android.support.v4.app.FragmentManagerImpl.detachFragment(FragmentManager.java:1408)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:727)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:254)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:0)

您的方法onPause(MyListFragment)中的持有者未实例化。所以当它出现在线上时

holder.chkBox.setChecked(true);

那个例外会出来

答案 1 :(得分:0)

java.lang.NullPointerException 表示您正在尝试使用未初始化的组件。

在这里,您的动机是来自PlanetAdapter回调的onPause()的setChecked / unChecked of复选框。你可以这样做:

  1. 创建一个将片段与适配器通信的接口。
  2. 在适配器的onPause回调发送命令中,选中/取消选中复选框列表。
  3. 实施例: 假设你的界面是这样的:

    public interface AdapterCallback {
        void onCheckboxCallback(boolean isChecked);
    }
    

    在适配器中实现AdapterCallback接口。然后你会得到onCheckboxCallback()方法。

    @Override
        public void onCheckboxCallback(boolean isChecked) {
    //      Do your checkbox check/uncheck here
        }
    

    在此方法中,您可以根据isChecked值检查/取消选中。

    现在,在填充PlanetAdapter的Fragment / Activity中,只需调用此方法

    即可
    if (mCheckBoxValue) {
                plAdapter.onCheckboxCallback(true);
    
    
            } else {
                plAdapter.onCheckboxCallback(false);