尝试从不同的片段setChecked on Checkbox时收到错误

时间:2017-08-28 12:40:38

标签: android android-fragments

我的应用有一个主要活动,只是由不同的片段组成。在一个片段中,在我从服务器获取JSON值并尝试在复选框上设置复选标记后,应用程序崩溃并且我收到了

  

java.lang.NullPointerException:尝试调用虚方法'void   空对象上的android.widget.CheckBox.setChecked(boolean)'   参考

错误我正在尝试从复选框值所在的不同片段设置复选框值。

主要活动:

if(v == findViewById(R.id.login)){     //between fragments: from login screen to home page

        username_text = (EditText) findViewById(R.id.username_text);
        password_text = (EditText) findViewById(R.id.password_text);
        RequestQueue requestQueue = Volley.newRequestQueue(this);;
        String signin = "http://acarjsystem.herokuapp.com/auth/";
        StringRequest request;

        uname = username_text.getText().toString();
        pword = password_text.getText().toString();

        final ProgressDialog loading = new ProgressDialog(MainActivity.this);
        loading.setTitle("Loading");
        loading.setMessage("Attempting to Log In");
        loading.show();
        ////////////////////
        request = new StringRequest(Request.Method.POST, signin, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                final Fragment nextFrag;
                final CheckBox check_locateCar, check_carOff,check_getImg, check_tase, check_carOn;
                try {
                    check_locateCar = (CheckBox)findViewById(R.id.check_locateCar);
                    check_carOff = (CheckBox)findViewById(R.id.check_carOff);
                    check_getImg = (CheckBox)findViewById(R.id.check_getImg);
                    check_tase = (CheckBox)findViewById(R.id.check_tase);
                    check_carOn = (CheckBox)findViewById(R.id.check_carOn);

                    JSONObject jsonObject = new JSONObject(response);
                    if(jsonObject.getString("user").equals("logined")){
                        Toast.makeText(getApplicationContext(),"SUCCESS "+jsonObject.getString("user"),Toast.LENGTH_SHORT).show();
                        //startActivity(new Intent(getApplicationContext(),Welcome.class));
                        if(!jsonObject.getString("car_plate").equals("0")){
                            loading.hide();

                            if(jsonObject.getString("car_stat").equalsIgnoreCase("true")){
                                //////////////HERE//////////////////////////////////
                                if(jsonObject.getString("loc_stat").equalsIgnoreCase("true")){
                                         /*THE ERROR IS AROUND THIS LINE*/
                                        check_locateCar.setChecked(true);
                                    }else{
                                        check_locateCar.setChecked(false);
                                    }
                                    if(jsonObject.getString("ignition").equalsIgnoreCase("true")){
                                        check_carOff.setChecked(true);
                                    }else{
                                        check_carOff.setChecked(false);
                                    }
                                    if(jsonObject.getString("taser").equalsIgnoreCase("true")){
                                        check_tase.setChecked(true);
                                    }else{
                                        check_tase.setChecked(false);
                                    }
                                    if(jsonObject.getString("photo_stat").equalsIgnoreCase("true")){
                                        check_getImg.setChecked(true);
                                    }else{
                                        check_getImg.setChecked(false);
                                    }

                                    //check_carOn.setChecked(false);
                                    nextFrag = new locate_updatedstatus();


                                    ////////////////////////////////////////////////////
                                }
                                else{

                                    loading.hide();
                                    nextFrag = new locate_before();
                                }
                            }
                            else{
                                loading.hide();
                                nextFrag = new locate_car_reg();
                            }

                            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                            transaction.replace(R.id.fragment_container, nextFrag);
                            transaction.addToBackStack(null);
                            transaction.commit();


                        }else {

                            Toast.makeText(getApplicationContext(), "Error" +jsonObject.getString("user"), Toast.LENGTH_SHORT).show();
                            loading.hide();

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            }){
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    HashMap<String,String> hashMap = new HashMap<String, String>();
                    hashMap.put("username",username_text.getText().toString());
                    hashMap.put("password",password_text.getText().toString());

                    return hashMap;
                }
            };


            requestQueue.add(request);

            ///////////////////////////
            //Toast.makeText(MainActivity.this,uname+"\n"+pword, Toast.LENGTH_LONG).show();
            //newFragment = new locate_login();
        }

fragment_locate_updatedstatus的XML文件:

<CheckBox
        android:id="@+id/check_locateCar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/updates"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="Locate Car using Gmaps" />

    <CheckBox
        android:id="@+id/check_carOff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/check_locateCar"
        android:layout_below="@+id/check_locateCar"
        android:layout_marginTop="10dp"
        android:text="Turn car off" />

    <CheckBox
        android:id="@+id/check_getImg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/check_carOff"
        android:layout_alignStart="@+id/check_carOff"
        android:text="Capture images" />

    <CheckBox
        android:id="@+id/check_tase"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_below="@+id/check_getImg"
        android:layout_alignStart="@+id/check_getImg"
        android:text="Tase Culprit" />

    <CheckBox
        android:id="@+id/check_carOn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/check_tase"
        android:layout_below="@+id/check_tase"
        android:layout_marginTop="10dp"
        android:text="Turn system off" />

错误

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setChecked(boolean)' on a null object reference

2 个答案:

答案 0 :(得分:0)

尝试将片段事务移动到`nextFrag':

if(v == findViewById(R.id.login)){     //between fragments: from login screen to home page

    username_text = (EditText) findViewById(R.id.username_text);
    password_text = (EditText) findViewById(R.id.password_text);
    RequestQueue requestQueue = Volley.newRequestQueue(this);;
    String signin = "http://acarjsystem.herokuapp.com/auth/";
    StringRequest request;

    uname = username_text.getText().toString();
    pword = password_text.getText().toString();

    final ProgressDialog loading = new ProgressDialog(MainActivity.this);
    loading.setTitle("Loading");
    loading.setMessage("Attempting to Log In");
    loading.show();
    ////////////////////
    request = new StringRequest(Request.Method.POST, signin, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            final Fragment nextFrag;
            final CheckBox check_locateCar, check_carOff,check_getImg, check_tase, check_carOn;
            try {

                JSONObject jsonObject = new JSONObject(response);
                if(jsonObject.getString("user").equals("logined")){
                    Toast.makeText(getApplicationContext(),"SUCCESS "+jsonObject.getString("user"),Toast.LENGTH_SHORT).show();
                    //startActivity(new Intent(getApplicationContext(),Welcome.class));
                    if(!jsonObject.getString("car_plate").equals("0")){
                        loading.hide();

                        if(jsonObject.getString("car_stat").equalsIgnoreCase("true")){
                            //////////////HERE//////////////////////////////////

                                //check_carOn.setChecked(false);
                                nextFrag = new locate_updatedstatus();

                                ////////////////////////////////////////////////////
                            }
                            else{

                                loading.hide();
                                nextFrag = new locate_before();
                            }
                        }
                        else{
                            loading.hide();
                            nextFrag = new locate_car_reg();
                        }

                        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                        transaction.replace(R.id.fragment_container, nextFrag);
                        transaction.addToBackStack(null);
                        transaction.commit();

                        check_locateCar = (CheckBox)findViewById(R.id.check_locateCar);
                        check_carOff = (CheckBox)findViewById(R.id.check_carOff);
                        check_getImg = (CheckBox)findViewById(R.id.check_getImg);
                        check_tase = (CheckBox)findViewById(R.id.check_tase);
                        check_carOn = (CheckBox)findViewById(R.id.check_carOn);

                        if(jsonObject.getString("loc_stat").equalsIgnoreCase("true")){
                             /*THE ERROR IS AROUND THIS LINE*/
                            check_locateCar.setChecked(true);
                        }else{
                            check_locateCar.setChecked(false);
                        }
                        if(jsonObject.getString("ignition").equalsIgnoreCase("true")){
                            check_carOff.setChecked(true);
                        }else{
                            check_carOff.setChecked(false);
                        }
                        if(jsonObject.getString("taser").equalsIgnoreCase("true")){
                            check_tase.setChecked(true);
                        }else{
                            check_tase.setChecked(false);
                        }
                        if(jsonObject.getString("photo_stat").equalsIgnoreCase("true")){
                            check_getImg.setChecked(true);
                        }else{
                            check_getImg.setChecked(false);
                        }                           

                    }else {

                        Toast.makeText(getApplicationContext(), "Error" +jsonObject.getString("user"), Toast.LENGTH_SHORT).show();
                        loading.hide();

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String,String> hashMap = new HashMap<String, String>();
                hashMap.put("username",username_text.getText().toString());
                hashMap.put("password",password_text.getText().toString());

                return hashMap;
            }
        };


        requestQueue.add(request);

        ///////////////////////////
        //Toast.makeText(MainActivity.this,uname+"\n"+pword, Toast.LENGTH_LONG).show();
        //newFragment = new locate_login();
    }

答案 1 :(得分:0)

  

我正在尝试从复选框值所在的不同片段设置复选框值。

片段需要通过代理通过主/父Activity进行通信。要做到这一点

  1. 为所需的侦听器方法定义接口(在您的情况下为OnCheckBoxSelectedListener侦听器)。
  2. 让主Activity实现OnCheckBoxSelectedListener
  3. 在片段中声明OnCheckBoxSelectedListener的私有成员
  4. 在Fragment的onAttach覆盖中,将OnCheckBoxSelectedListener成员设置为Activity参数。
  5. 1)为所需的侦听器方法定义一个接口(在你的情况下是一个OnCheckBoxSelectedListener监听器)。

    interface OnCheckBoxSelectedListener
    {
        public void SetChecked(bool checked);
    }
    

    2)让主Activity实现OnCheckBoxSelectedListener

    public class Activity implements OnCheckBoxSelectedListener
    {
        public void SetCheck(bool checked)
        {
            check_locateCar = (CheckBox)findViewById(R.id.check_locateCar);
            check_locateCar.setChecked(true);
        }
    } 
    

    3)在片段中声明OnCheckBoxSelectedListener的私有成员 4)在Fragment的onAttach覆盖中,将OnCheckBoxSelectedListener成员设置为Activity参数。

    public static class FragmentA extends ListFragment {
        OnCheckBoxSelectedListener mListener;
        ...
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            try {
                mListener = (OnArticleSelectedListener) activity;
            } catch (ClassCastException e) {
                throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
            }
        }
        ...
    }
    

    然后从onResponse调用监听器

          @Override
            public void onResponse(String response) {
                final Fragment nextFrag;
                final CheckBox check_locateCar, check_carOff,check_getImg, check_tase, check_carOn;
                try {
                    check_locateCar = (CheckBox)findViewById(R.id.check_locateCar);
                    check_carOff = (CheckBox)findViewById(R.id.check_carOff);
                    check_getImg = (CheckBox)findViewById(R.id.check_getImg);
                    check_tase = (CheckBox)findViewById(R.id.check_tase);
                    check_carOn = (CheckBox)findViewById(R.id.check_carOn);
    
                    JSONObject jsonObject = new JSONObject(response);
                    if(jsonObject.getString("user").equals("logined")){
                        Toast.makeText(getApplicationContext(),"SUCCESS "+jsonObject.getString("user"),Toast.LENGTH_SHORT).show();
                        //startActivity(new Intent(getApplicationContext(),Welcome.class));
                        if(!jsonObject.getString("car_plate").equals("0")){
                            loading.hide();
    
                            if(jsonObject.getString("car_stat").equalsIgnoreCase("true")){
                                //////////////HERE//////////////////////////////////
                                if(jsonObject.getString("loc_stat").equalsIgnoreCase("true")){
                                         /*THE ERROR IS AROUND THIS LINE*/
                                        //check_locateCar.setChecked(true);
                                        mListener.SetChecked(true)
                                    }else{
                                        check_locateCar.setChecked(false);
                                    }
                                    // ...
                                }
                            }
                        }
                    }
                }
            }
    

    注意:以上建立了Fragment to Activity方向的沟通。换句话说(来自监听器的“回调”),我定义了一个回调接口,在Fragment中实现它,并使用对作为参数传入的Fragment的引用从监听器中调用它(通过{{1指针)。例如

    this

    然后从onRequest调用它如下(在这种情况下你可能不需要回调,但在某些时候你可能会,例如从主活动调用startActivityForRequest / onActivityRequest时,因为它们在不同的线程上运行)< / p>

    interface OnCheckBoxSelectedListener
    {
        public void SetCheck(OnCheckBoxSelectedCallback callingFragment, attachmentDialog2EventListener, bool checked);
    }
    
    interface OnCheckBoxSelectedCallback
    {
        SetCheckedCallback();
    }
    
    public class Activity implements OnCheckBoxSelectedListener
    {
        public void SetCheck(OnCheckBoxSelectedCallback callingFragment, bool checked)
        {
            check_locateCar = (CheckBox)findViewById(R.id.check_locateCar);
            check_locateCar.setChecked(true);
    
            callingFragment.SetCheckedCallback();
        }
    }
    
    public static class FragmentA extends ListFragment implements OnCheckBoxSelectedCallback {
        OnCheckBoxSelectedListener mListener;
        ...
        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            try {
                mListener = (OnCheckBoxSelectedListener) activity;
            } catch (ClassCastException e) {
                throw new ClassCastException(activity.toString() + " must implement OnCheckBoxSelectedListener");
            }
        }
        ...
    
        public void SetCheckedCallback()
        {
            // ...
        }
    }