你想从编辑文本中获取地名并在地图上标记这里是我的代码,我得到空指针异常请帮助我应该做什么以及我哪里出错。
因为我从对话框的编辑文本字段中获取地名。
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 ;
}
答案 0 :(得分:4)
NullPointerExceptions
是查找和调试最容易的例外。
如果您在此行中获得NullPointerException
:
String placeName = placeText.getText().toString();
唯一可以为null的是placeText变量或placeText.getText()
你需要找出它为空的原因。由于您的placeText处于警报状态,因此您应该使用layout.findViewById从布局中获取它。当您从错误的位置获取它时,它将为null,从而导致NullPointerException
。
理论上,getText()
也可以返回null,但Android SDK中的当前实现将在没有填充任何内容时返回空字符串,因此不能为null。
答案 1 :(得分:2)
使用EditText placeText = (EditText) layout.findViewById(R.id.strtplace);
代替EditText placeText = (EditText) findViewById(R.id.strtplace);
答案 2 :(得分:0)
继承你需要做的改变: //视图和editext都应该声明为final,而findViewById方法需要一个可以调用它的布局