类适配器不起作用

时间:2016-05-18 16:48:30

标签: android android-studio checkbox sharedpreferences

我有标签;如果我从标签“PIZZA”中选择一个复选框,之后,当我进入第三个标签“BIRRE”时,如果我点击“get_answer”按钮,我希望在第一个标签中选中的复选框位于第二个标签中两个“......但是当我点击按钮时我的代码”get_answer“IDE在三个片段中的”for (Planet p : plAdapter.getBox())“行上说”空指针异常“...我还使用了shared preferences来存储复选框,当我点击另一个选项卡,infact复选框存储....但它不起作用...我不知道为什么....

现在我发布我的代码......

感谢每一个人!

ADAPTER:

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

{

    private List<Planet> planetList = null;
    private Context context = null;
    ArrayList<Birra> objects;
    private HashMap<Integer, Planet> pizzaSelected = new HashMap<>();
    public boolean Checked;

    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à;
        public boolean checked;
        public TextView id;
    }

    @Override
    public int getCount() {
        return planetList.size();
    }

    @Override
    public Planet getItem(int position) {
        return planetList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return planetList.get(position).getId();
    }


    @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);
            // holder.id = (TextView) row.findViewById(R.id.id);


            row.setTag(holder);

        } else {
            holder = (PlanetHolder) row.getTag();
        }
        final Planet p = planetList.get(position);
        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);
        SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
        boolean isChecked = states.getBoolean("holder.chkBox" + holder.planetName.getText().toString(), false);
        System.out.println(isChecked);
        if (isChecked) {
            holder.chkBox.setChecked(true);
            holder.edit.setVisibility(View.VISIBLE);
            holder.edit.setEnabled(true);
            SharedPreferences statess = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
            String string = statess.getString("finalHolder.edit" + holder.planetName.getText().toString(), holder.edit.getText().toString().trim());
            holder.edit.setText(string);


        } else {
            holder.chkBox.setChecked(false);
            holder.edit.setVisibility(View.GONE);
            holder.edit.setEnabled(false);


        }


        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);
                    SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = states.edit();
                    editor.putBoolean("holder.chkBox" + finalHolder.planetName.getText().toString(), true);
                    editor.commit();
                    //Utility.putPizzaItem(p);
                    //Utility.getPizzaItem(p);


                } else {
                    SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor3 = states.edit();
                    finalHolder.edit.setVisibility(View.GONE);
                    finalHolder.edit.setEnabled(false);
                    finalHolder.edit.setText("");
                    editor3.putBoolean("holder.chkBox" + finalHolder.planetName.getText().toString(), false);
                    editor3.commit();


                }
               /* SharedPreferences states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = states.edit();
                editor.apply();*/

            }
        });
        /*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 states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = states.edit();
                    editor.putBoolean("holder.chkBox", true);
                    //pizzaSelected.put(p.getId(), p);
                    System.out.println(p.getId());
                } else {

                    finalHolder.edit.setVisibility(View.GONE);
                    finalHolder.edit.setEnabled(false);
                    finalHolder.edit.setText(null);
                    pizzaSelected.remove(p.getId());

                }

            }
        });
*/


        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 states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = states.edit();
                editor.putString("finalHolder.edit" + finalHolder.planetName.getText().toString(), finalHolder.edit.getText().toString().trim());
                editor.commit();


            }
        });


        //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);
        //  holder.id.setId(p.getId());


        return row;
    }

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



    }

行星适配器的碎片:

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, "€",1));
        planetList.add(new Planet("Diavola", 7,"€",2));
        planetList.add(new Planet("Bufalina", 5,"€",3));
        planetList.add(new Planet("Marinara", 5, "€",4));
        planetList.add(new Planet("Viennese", 4, "€", 5));

        plAdapter = new PlanetAdapter(planetList, getActivity()) {
            @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 class ThreeFragment extends Fragment implements
        android.widget.CompoundButton.OnCheckedChangeListener {

    ListView lv2;
    ArrayList<Birra> birraList;
    BirraAdapter biAdapter;
    PlanetAdapter plAdapter;
    Planet p;


    BirraAdapter.BirraHolder birraHolder;
    PlanetAdapter.PlanetHolder holder;


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


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


            }
        }
        for (Planet p : plAdapter.getBox()) {
            if (p.isSelected()) {


                result += "\n" + p.getName() + " " + p.getDistance() + "€" + "q.tà :" + p.getQuantità();
                int quantitaInt = Integer.parseInt(p.getQuantità());
                //totalAmount2+=p.distance * quantitaInt;
                //z=String.valueOf(totalAmount2);


            }


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

        }


    }
}

这是我的APP:

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

PlAdapter尚未初始化。您必须在此行之前初始化它:for (Planet p : plAdapter.getBox()) {因此空指针异常 最好在OnCreateView()

中初始化