我如何膨胀xml文件,以便我的复选框将停止给我这个NullPointerException错误?

时间:2017-11-11 09:44:27

标签: java android checkbox layout-inflater

在logcat中我有错误:

E/AndroidRuntime: FATAL EXCEPTION: main
                  java.lang.NullPointerException
                      at com.example.chris.tutorialspoint.ViewContact$1.onResponse(ViewContact.java:263)
                      at com.example.chris.tutorialspoint.ViewContact$1.onResponse(ViewContact.java:149)
                      at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
                      at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
                      at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                      at android.os.Handler.handleCallback(Handler.java:730)
                      at android.os.Handler.dispatchMessage(Handler.java:92)
                      at android.os.Looper.loop(Looper.java:137)
                      at android.app.ActivityThread.main(ActivityThread.java:5419)
                      at java.lang.reflect.Method.invokeNative(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:525)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
                      at dalvik.system.NativeStart.main(Native Method)

我的代码的相关部分是:

//stuff here

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(activity_view_contact);

    //stuff here....

    StringRequest stringRequest = new StringRequest(Request.Method.POST, ViewContact_URL,
            new Response.Listener<String>() {

        @Override
                public void onResponse(String response) {

                    //toast the response of ViewContact.php, which has been converted to a
                    //JSON object by the Php file with JSON encode
                    Toast.makeText(ViewContact.this, "OnResponse is" + response, Toast.LENGTH_LONG).show();
                    System.out.println("ViewContact: And the response is " + response);


            try {

                //stuff here


                //we are going to loop through the checked contacts and check the boxes
                //(we could just set them as checked without a loop but User Phone Number,
                //which isn't in the Contacts list, is problematic)
                int count = checkedContactsAsArrayList.size();

                for (int i = 0; i < count; i++) {

                    LinearLayout itemLayout = (LinearLayout) listView.getChildAt(i); // Find by under LinearLayout

                    //inflate the layout that contains the checkbox or else we can get errors
                    LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    View view = layoutInflater.inflate(R.layout.phone_inflate_listview, null);
                    //associate it with a checkbox
                    CheckBox checkbox = (CheckBox) itemLayout.findViewById(R.id.checkBoxContact);
                    //get the other data related to that checkbox - name and number of contact
                    SelectPhoneContact data = (SelectPhoneContact) checkbox.getTag();
                    //if the contact is in the checked array
                    if (checkedContactsAsArrayList.contains(data.getPhone())) {
                        //check the box
                        checkbox.setChecked(true);
                    }
                }



                        //System.out.println("heree it is" + jsonResponse);
                        //Toast.makeText(ContactView.this, jsonResponse, Toast.LENGTH_LONG).show();
                        hidePDialog();

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(getApplicationContext(),
                                "Error: " + e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    }



                }


            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(ViewContact.this, error.toString(), Toast.LENGTH_LONG).show();

                }

            }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            //we are posting review_id into our ViewContact.php file, which
            //we get when a row is clicked in populistolistview
            //to get matching details
            params.put("review_id", review_id);
            return params;

        }

    };
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);


     //stuff here

}

Line 263,发生错误的地方是:

 CheckBox checkbox = (CheckBox) itemLayout.findViewById(R.id.checkBoxContact);

checkBoxContact不在我的activity_view_contact中,它在phone_inflate_listview中,所以我认为它是因为我没有充气它正确,因此NulPointerException错误。那么,我怎样才能正确充气呢?那就是问题,对吧?

我按照以下方式尝试了一些事情,但仍然无法正常工作:

                        //inflate the layout that contains the checkbox or else we can get errors
                        LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        View view = layoutInflater.inflate(R.layout.phone_inflate_listview, null);
                        //associate it with a checkbox
                        CheckBox checkbox = (CheckBox) itemLayout.findViewById(R.id.checkBoxContact);

2 个答案:

答案 0 :(得分:1)

你说你试过这段代码:

//inflate the layout that contains the checkbox or else we can get errors
LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.phone_inflate_listview, null);
//associate it with a checkbox
CheckBox checkbox = (CheckBox) itemLayout.findViewById(R.id.checkBoxContact);

充气机像你一样工作。他们将视图作为实例进行膨胀。当你像这样膨胀时的含义:

View /*IMPORTANT*/view = layoutInflater.inflate(R.layout.phone_inflate_listview, null);

但加载视图如下:

CheckBox checkbox = (CheckBox) /*IMPORTANT*/itemLayout.findViewById(R.id.checkBoxContact);

使用错误的布局/视图进行充气。

请改为:

CheckBox checkbox = (CheckBox) view.findViewById(R.id.checkBoxContact);

itemLayout很可能是null因为它没有被初始化(我说的最有可能是因为它是一个MCVE,我不能告诉它是否在其他地方膨胀或不是因为那个代码没有被包括在内)

答案 1 :(得分:0)

此处的代码解决了我的问题,i是当前在屏幕上可见的行,因此创建了所有视图并负责nullpointerexception,但我更愿意,如果可以的话通过适当地充气checkbox来实现。

 int num_of_visible_view=listView.getLastVisiblePosition() -
                                    listView.getFirstVisiblePosition();

                            for (int i = 0; i < num_of_visible_view; i++) {

                                LinearLayout itemLayout = (LinearLayout) listView.getChildAt(i); // Find by under LinearLayout

                                //inflate the layout that contains the checkbox or else we can get errors
                              //  LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                              //  View view = itemLayout.inflate(R.layout.phone_inflate_listview, null);
                                //associate it with a checkbox
                                CheckBox checkbox = (CheckBox) itemLayout.findViewById(R.id.checkBoxContact);
                                //get the other data related to that checkbox - name and number of contact
                                SelectPhoneContact data = (SelectPhoneContact) checkbox.getTag();
                                //if the contact is in the checked array
                                if (checkedContactsAsArrayList.contains(data.getPhone())) {
                                    //check the box
                                    checkbox.setChecked(true);
                                }
                            }