java.lang.NullPointerException:在android.widget.EditText.addTextchangedlistener上

时间:2015-06-16 12:09:25

标签: java android

我正在开发Android应用程序并将过滤功能放在Listview上。但我得到错误

  

java.lang.RuntimeException:无法启动活动   componentInfo:java.lang.NullPointerException:尝试调用   虚方法无效   android.widget.EditText.addTextchangedListener(android.text.TextWatcher)   在Null对象参考

以下是我的代码。

  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.shopdetail);
    aq=new AQuery(this);
    value=5;



                GPSTracker  gps = new GPSTracker(Shopdetail.this);
                    if(gps.canGetLocation()){
                        double latitude = gps.getLatitude();
                        double longitude = gps.getLongitude();
                         getdatalatlog(latitude,longitude);                     
                   }else{
                        gps.showSettingsAlert();
                    }                       
                    Intent openStartingPoint=getIntent();
                    String city=openStartingPoint.getStringExtra("spinnerText");
                    bindcity(city);

            final EditText inputSearch = (EditText)findViewById(R.id.inputSearch);                      
                    inputSearch.addTextChangedListener(new TextWatcher() {

                        @Override
                        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
                            // When user changed the Text
                            //Shopdetail.this.adapter.getFilter().filter(cs);  
                            //((SimpleAdapter)Shopdetail.this.adapter).getFilter().filter(cs); 

                          //  ((SimpleAdapter)getListAdapter()).getFilter().filter(cs); 

                            //get the text in the EditText
                                                                                     EditText inputSearch =    (EditText)findViewById(R.id.inputSearch);
                             String searchString=inputSearch.getText().toString();
                               int textLength=searchString.length();
                               searchResults.clear();

                               for(int i=0;i<mCommentList.size();i++)
                               {
                              String shopName=mCommentList.get(i).get(TAG_TITLE).toString();
                              if(textLength<=shopName.length()){
                              //compare the String in EditText with Names in the ArrayList
                                 if(searchString.trim().equalsIgnoreCase(shopName.trim().substring(0,textLength))){
                                searchResults.add(mCommentList.get(i));

                                getdata();}
                              }
                               }

                               adapter.notifyDataSetChanged();
                        }

                        @Override
                        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                int arg3) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void afterTextChanged(Editable arg0) {
                            // TODO Auto-generated method stub                          
                        }
                    });




    }

        private void getdata() {
    // TODO Auto-generated method stub
    String[] data = new String[]{TAG_TITLE,TAG_USERNAME ,TAG_CONTACT ,TAG_MESSAGE ,TAG_LATITUDE , TAG_LONGITUDE };

    int[] to= new int[] {R.id.shop_name,R.id.address,R.id.contact,R.id.distance,R.id.latitude,R.id.longitude};

    final   SimpleAdapter  adapter = new SimpleAdapter(this, mCommentList,R.layout.single_post, data,to);

     ListView lv = ( ListView ) findViewById(android.R.id.list);
     lv.setAdapter(adapter);

}`

下面是我首先绑定数据的代码。

  

块引用

private void getdatalatlog(double latitude, double longitude) {
    // TODO Auto-generated method stub
    //value=5;
    String url = "http://192.168.2.4/PHP/webservice/comments.php?latitude='"+latitude+"'&longitude='"+longitude+"'&value='"+value+"'";
    aq.progress(R.id.progressBar1).ajax(url, JSONObject.class, this,"jsonCallback");

}

@SuppressWarnings("unchecked")
public void jsonCallback(String url, JSONObject json, AjaxStatus status) {  


    if (json != null) { 


    List<String> city = new ArrayList<String>();
    mCommentList = new ArrayList<HashMap<String, Object>>();

        Gson gson = new GsonBuilder().create();
        try {

         JSONArray jsonResponse = json.getJSONArray("posts");
            city = gson.fromJson(jsonResponse.toString(),List.class);
            for (int i = 0; i < jsonResponse.length(); i++) {
                JSONObject c = jsonResponse.getJSONObject(i);       

                String title = c.getString(TAG_TITLE);
                String content = c.getString(TAG_MESSAGE);
                String username = c.getString(TAG_USERNAME);
                String lat = c.getString(TAG_LATITUDE);
                String log = c.getString(TAG_LONGITUDE);
                String cont = c.getString(TAG_CONTACT);

                // creating new HashMap
                HashMap<String, Object> map = new HashMap<String, Object>();

                map.put(TAG_TITLE, title);
                map.put(TAG_MESSAGE, content);
                map.put(TAG_USERNAME, username);
                map.put(TAG_LATITUDE, lat);
                map.put(TAG_LONGITUDE, log);
                map.put(TAG_CONTACT, cont);
                    // adding HashList to ArrayList
            mCommentList.add(map);

            searchResults=new ArrayList<HashMap<String,Object>>(mCommentList);
            //HashMap<String, String> map1 = new HashMap<String, String>();
            //map1.put(TAG_TITLE, title);
            //sortdata;


            }
        } 
        catch (JSONException e) {

            Toast.makeText(aq.getContext(), "Error in parsing JSON", Toast.LENGTH_LONG).show();
        }
        catch (Exception e) {
            Toast.makeText(aq.getContext(), "Something went wrong", Toast.LENGTH_LONG).show();
        }


        String[] data = new String[]{TAG_TITLE,TAG_USERNAME ,TAG_CONTACT ,TAG_MESSAGE ,TAG_LATITUDE , TAG_LONGITUDE };

        int[] to= new int[] {R.id.shop_name,R.id.address,R.id.contact,R.id.distance,R.id.latitude,R.id.longitude};

        final   SimpleAdapter  adapter = new SimpleAdapter(this, mCommentList,R.layout.single_post, data,to);

         ListView lv = ( ListView ) findViewById(android.R.id.list);
         lv.setAdapter(adapter);




        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {

                Intent intent = new Intent();
                 Bundle b = new Bundle();


                 String name= ((TextView) view.findViewById(R.id.shop_name)).getText().toString()+" , "+((TextView) view.findViewById(R.id.contact)).getText().toString();

                 String lati= ((TextView) view.findViewById(R.id.latitude)).getText().toString();

                 String longi= ((TextView) view.findViewById(R.id.longitude)).getText().toString();

                 b.putString("shop",name);
                 b.putString("lati",lati);
                 b.putString("long",longi);
                intent.setClass(Shopdetail.this, Mapview.class);
                intent.putExtras(b);
                startActivity(intent);
            }
        });



} 

}

当用户在EditText上键入字母时,数据会被过滤,并且根据它在listview中进行绑定。它不起作用。请指导我。

非常感谢。

2 个答案:

答案 0 :(得分:8)

您忘了初始化inputSearch

inputSearch=(EditText)findViewById(R.id.editTextId);

移动

 EditText inputSearch = (EditText)findViewById(R.id.inputSearch);

 inputSearch.addTextChangedListener(new TextWatcher() {

答案 1 :(得分:1)

在Null对象引用上调用方法将始终抛出java.lang.NullPointerException。

在您的情况下,日志清楚地表明&#34;尝试在Null对象上调用方法addTextchangedListener(android.text.TextWatcher)&#34;。

简而言之 - inputSearch为null,应该在任何方法调用之前进行初始化。