共享首选项和 onPause 不起作用

Posted

技术标签:

【中文标题】共享首选项和 onPause 不起作用【英文标题】:shared preferences and onPause doesn't work 【发布时间】:2016-09-05 06:34:03 【问题描述】:

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

提前致谢!

适配器类:

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;
    

带有列表视图和复选框的第一个片段类:

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

没有列表视图的第二个片段:

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

带有列表视图和复选框的第三个片段:

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)

【问题讨论】:

请附上异常堆栈跟踪。 好的,我刚刚发布了 logcat 在 FirstFragment 中声明您的复选框。我想你还没有宣布它 如果我写“持有人”。 IDE 建议我“chkBox” How to save checkbox value with shared preferences?的可能重复 【参考方案1】:

您在方法 onPause(MyListFragment) 中的持有者未实例化。所以当它来到这条线时

holder.chkBox.setChecked(true);

这个异常会出现

【讨论】:

所以我必须在方法 onPause 中实例化 holder.chkBox.setChecked(false)? 您不必在方法 onPause 中执行此操作。但是您必须在该行之前实例化持有人 我的实例持有者如何?【参考方案2】:

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

在这里,您的动机是从onPause() 回调中将复选框设置为PlanetAdapter。你可以这样做:

    创建一个在片段与适配器之间进行通信的接口。 在您的 onPause 回调中,向您的适配器发送命令以检查/取消选中您的复选框列表。

示例: 假设你的界面是这样的:

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

【讨论】:

以上是关于共享首选项和 onPause 不起作用的主要内容,如果未能解决你的问题,请参考以下文章

保存的首选项在重新启动时不起作用

onPause() 和 onStop() 不起作用

从代码中修改文件权限不起作用

状态栏首选项不起作用:phonegap 版本 3.6.3

Sharedpreferences 删除不起作用

首选项 xml 中的 android:visibility 属性不起作用? (安卓 2.3)