onDestroy不工作 [英] onDestroy doesn't work

查看:144
本文介绍了onDestroy不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行我的应用程序,在开始,所有复选框在列表视图中选择 ...所以我必须取消选中所有复选框之前...我不' t知道为什么.....
也许我写错了 onDestroy 方法....

when i run my app,at the start, all checkbox are select in list view...so i must unchecked before all checkbox....i don't know why..... Maybe i wrong to write onDestroy method....

请帮助我!

我给你看看我的代码...
谢谢你的好感!

i show you my code... THANKS IN ADVANCE EVERYBODY!

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


         }

        holder.chkBox.setOnCheckedChangeListener(PlanetAdapter.this);
       // final BirraHolder finalHolder = birraHolder;
        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 states = getContext().getSharedPreferences("states", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = states.edit();
                    editor.putBoolean("holder.chkBox" + finalHolder.planetName.getText().toString(), true);
                    editor.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 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();


                        }
                    });

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



    }

FRAGMENT:

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

    ListView lv;
    ArrayList<Planet> planetList;
    static PlanetAdapter plAdapter;

    BirraAdapter biAdapter;
    PlanetAdapter.PlanetHolder holder;
    private static Context context = null;
    private static FragmentActivity mInstance;





    @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);
        context = getActivity();
        mInstance= getActivity();
        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, 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 static void showResult(View v) {
        String  result = "Selected Product are :";
        int totalAmount=0;
        String  result2 = "";
        int totalAmount2=0;

        String a="";
        String z="";



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


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


            }
            int totale=totalAmount+totalAmount2;
            z=String.valueOf(totale);

        }

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


        Bundle bun2 = new Bundle();
        bun2.putString("scelta", result2);
        ThreeFragment fgsearch2 = new ThreeFragment();
        fgsearch2.setArguments(bun2);
        android.support.v4.app.FragmentTransaction transaction2 = mInstance.getSupportFragmentManager().beginTransaction();
        transaction2.replace(R.id.content_main, fgsearch2);
        transaction2.commit();






*/
/*










    }


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

    String a="";
    //String z="";

    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.getDistance() * quantitaInt;
            //z=String.valueOf(totalAmount2);


        }


    }

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


    Bundle bun2 = new Bundle();
    bun2.putString("scelta3", result);
    TwoFragment fgsearch2 = new TwoFragment();
    fgsearch2.setArguments(bun2);
    android.support.v4.app.FragmentTransaction transaction2 = mInstance.getSupportFragmentManager().beginTransaction();
    transaction2.replace(R.id.content_main3, fgsearch2);
    transaction2.commit();




/*Bundle bun = new Bundle();
    //  bun.putString("totalepizze",z);
    bun.putInt("totalepizze",totalAmount2);
        TwoFragment fgsearch = new TwoFragment();
        fgsearch.setArguments(bun);
        android.support.v4.app.FragmentTransaction transaction = mInstance.getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.content_main2, fgsearch);
        transaction.commit();*/

/*



        Bundle bun = new Bundle();
        bun.putString("scelta", result2);
        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();

*/









}



}

ACTIVITY: / p>

ACTIVITY:

public class Main extends AppCompatActivity{



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        getSupportFragmentManager().beginTransaction().

                replace(R.id.fragmentContainer, new MyListFragment()).commit();




    }

@Override
public void onDestroy()
{
    super.onDestroy();
    SharedPreferences myPrefs = this.getSharedPreferences("states", Context.MODE_PRIVATE);
    myPrefs.edit().remove("states");
    myPrefs.edit().clear();
    myPrefs.edit().commit();
}



}


推荐答案

onDestroy 更改为 onPause()。根据文档 - 您不应该onDestroy方法被调用,如果你想清除/提交的东西,最好的地方是在 onPause() onSaveInstanceState (Bundle)方法。所以你的代码现在变成这样:

Change from onDestroy to onPause(). according to the documentation - you should not count on the onDestroy method being called and that if you want to clear/commit stuff, the best place to do so is in either onPause() or onSaveInstanceState(Bundle) method. So your code now changes into something like this:

public void onPause()
{    
    SharedPreferences myPrefs = this.getSharedPreferences("states", Context.MODE_PRIVATE);
    //get the editor object
    Editor sharedPrefsEditor = myPrefs.edit(); 
    sharedPrefsEditor.remove("states");  
    //I don't think you still need to call "clear" since we removed "states"     
    sharedPrefsEditor.commit();
    //only now do you call super.onDestroy()
    super.onPause();
}

尝试一下,让我们知道问题是否仍然存在。

Give this a try and let us know if the problem persists.

这篇关于onDestroy不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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