android - Adding markers from Google Maps in Asynctask
问题描述
I want to add a marker to Google Maps after I've done something in AsyncTask. However, when I attempt to add a marker onPostExecute after the operation, An error will occur:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
I searched for this problem, but it didn't help. How do I add a marker inside OnPostExecute in Asyncask?
This is an arrangement of my code. It works normally until DoInBackground.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
GoogleMap mMap;
Document doc = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(final GoogleMap googleMap) {
GetXMLTask task = new GetXMLTask(getApplicationContext());
task.execute("http://openapi.its.go.kr:8081/api/NCCTVInfo?key=1526041502162&ReqType=2&MinX=" + 126 + "&MaxX=" + 127 + "&MinY=" + 35 + "&MaxY=" + 38 + "&type=ex");
}
@SuppressLint("NewApi")
private class GetXMLTask extends AsyncTask<String, Void, Document> {
public GetXMLTask(Context applicationContext) {
}
@Override
protected Document doInBackground(String... urls) {
URL url;
try {
} catch (Exception e) {
}
return doc;
}
@Override
protected void onPostExecute(Document doc) {
MarkerOptions makerOptions = new MarkerOptions();
makerOptions
.position(new LatLng(0, 0))
.title("title");
mMap.addMarker(makerOptions); //<=====ERROR=====
}
}
}
解决方案
mMap object didn't set anything. So it will return null. You can set like that:
@Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
GetXMLTask task = new GetXMLTask(getApplicationContext());
task.execute("http://openapi.its.go.kr:8081/api/NCCTVInfo?key=1526041502162&ReqType=2&MinX=" + 126 + "&MaxX=" + 127 + "&MinY=" + 35 + "&MaxY=" + 38 + "&type=ex");
}
推荐阅读
- c# - 如何使用从 Login_View.cshtml 检索到的数据进行令牌认证
- azure - 将环境 APPLICATION_ENV 放入 AppService IIS 的任何解决方案(天蓝色)
- python - 如何在 Python 中单击按钮时更改按钮颜色
- r - 应用优化
- android - 如何进行非常基本的 AWS Device Farm 应用程序端到端测试:只需在指定时间内运行应用程序
- performance - 在 x86 ASM 中测试零通常更快:“TEST EAX,EAX”与“TEST AL,AL”?
- javascript - Bootstrap 4 行,容器末尾有两个列
- azure - 如何使用 C# 将 AppSettings.json 转换为高级 Azure 设置?
- javascript - Jquery mouseenter 和 mouseleave 在 svg 上没有正确触发
- reactjs - 如何禁用材质 ui 自动完成选项