我从String placeName = placeText.getText()。toString();得到空指针exception

您好想从编辑文本中获取地名并在地图上标记这里是我的代码,我得到空指针exception请帮助我我应该做什么以及我哪里出错了。

因为我从对话框中的编辑文本字段中获取地名。

View layout = View.inflate(this, R.layout.alertbox, null); AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setTitle("Enter the places"); dialog.setView(layout); dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // TODO Auto-generated method stub EditText placeText = (EditText) findViewById(R.id.strtplace); String placeName = placeText.getText().toString(); // Break from execution if the user has not entered anything in the field if(placeName.compareTo("")==0) numberOptions = 5; String [] optionArray = new String[numberOptions]; Geocoder gcoder = new Geocoder(TravellogActivity.this); try{ List
results = gcoder.getFromLocationName(placeName,numberOptions); Iterator
locations = results.iterator(); String raw = "\nRaw String:\n"; String country; int opCount = 0; while(locations.hasNext()){ Address location = locations.next(); lat = location.getLatitude(); lon = location.getLongitude(); country = location.getCountryName(); if(country == null) { country = ""; } else { country = ", "+country; } raw += location+"\n"; optionArray[opCount] = location.getAddressLine(0)+", "+location.getAddressLine(1)+country+"\n"; opCount ++; } Log.i("Location-List", raw); Log.i("Location-List","\nOptions:\n"); for(int i=0; i<opCount; i++){ Log.i("Location-List","("+(i+1)+") "+optionArray[i]); } } catch (IOException e){ Log.e("Geocoder", "I/O Failure; is network available?",e); } p = new GeoPoint(latE6, lonE6); myMC.animateTo(p); } }); dialog.show(); break; } return false ; }

使用EditText placeText = (EditText) layout.findViewById(R.id.strtplace); EditText placeText = (EditText) findViewById(R.id.strtplace);

NullPointerExceptions是查找和调试最容易的例外。

如果您在此行上收到NullPointerException

 String placeName = placeText.getText().toString(); 

唯一可以为null的是placeText变量或placeText.getText()

你需要弄清楚为什么它是null。 由于您的placeText处于警报状态,因此您应该使用layout.findViewById从布局中获取它。 当您从错误的位置获取它时,它将为null,从而导致NullPointerException

理论上, getText()也可以返回null,但Android SDK中的当前实现将在没有填充任何内容时返回空字符串,因此不能为null。

下面是您需要做的更改://视图和editext都应该声明为final,而findViewById方法需要一个布局来调用它

  • final view layout = View.inflate(this,R.layout.alertbox,null);
    • final EditText placeText =(EditText)layout.findViewById(R.id.strtplace);