您好,想从编辑文本中获取地名并在地图上标记,这是我的代码,其中出现空指针异常,请帮助我应该做什么以及哪里出错了。
因为我从对话框中的编辑文本字段获取地名。
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<Address> results = gcoder.getFromLocationName(placeName,numberOptions);
Iterator<Address> 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 ;
}
NullPointerExceptions
是最容易查找和调试的异常。
如果你得到一个NullPointerException
在这一行:
String placeName = placeText.getText().toString();
唯一可以为 null 的是 placeText 变量,或者placeText.getText()
您需要弄清楚为什么它为空。由于您的 placeText 处于警报状态,因此您应该使用layout.findViewById 从布局中获取它。当您从错误的位置获取它时,它将为空,从而导致NullPointerException
.
理论上,getText()
也可以返回null,但是Android SDK中当前的实现在没有填写任何内容时会返回一个空字符串,所以不能为null。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)