Android 在谷歌地图搜索中苦苦挣扎
地图活动Android 在谷歌地图搜索中苦苦挣扎,android,dictionary,search,nullpointerexception,Android,Dictionary,Search,Nullpointerexception,地图活动 public class Agriculture extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnInfoWindowClickListener, GoogleMap.OnMarkerClickListener { GoogleMap mMap; Address address; LatLng latLng;
public class Agriculture extends AppCompatActivity implements
OnMapReadyCallback,
GoogleMap.OnInfoWindowClickListener,
GoogleMap.OnMarkerClickListener {
GoogleMap mMap;
Address address;
LatLng latLng;
SupportMapFragment sMapFragment;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
public void onSearch(View view)
{
EditText tfLocation = (EditText) findViewById(R.id.tfLocation);
String location = tfLocation.getText().toString();
List<Address> addressList = null;
if (location!=null && !location.equals(""))
{
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 0);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude() , address.getLongitude());
忽略
location
不能为null
首先将列表设置为null
List<Address> addressList = null;
但是,在这里,如果出现异常,addressList
仍然为空,因此您的错误
Address address = addressList.get(0);
在没有看到实际异常的情况下,很难给出完整的答案,但防止空指针的快速解决方案是将最后一行移动到
try
(在尝试访问其数据之前,可以选择检查!addressList.isEmpty()
) 错误出现在Agriculture.java的第45行。您的地址列表可能为空getFromLocationName()
如果找不到匹配项或没有可用的后端服务,将返回null或空列表。请提供完整的布局和活动代码plz提供完整的代码b'z如果onclick中出现错误,则可能缺少某些内容。所以我们可以指出。大家好,谢谢您的时间,我已经编辑并添加了布局和完整活动@priyankPatel我已经看到问题存在,但似乎无法解决。请帮助。@cricket\u 007非常感谢您,我已将地址列表放入其中。获取(0);你是一个明星
if (!TextUtils.isEmpty(location))
{
Geocoder geocoder = new Geocoder(this);
try {
addressList = geocoder.getFromLocationName(location, 0);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);