在Asynctask中从Google Maps添加标记

时间:2018-10-28 07:14:26

标签: android google-maps android-asynctask

在AsyncTask中完成某些操作后,我想向Google Maps添加标记。 但是,当我尝试在操作后在onPostExecute上添加标记时, 将发生错误:

 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

我搜索了此问题,但没有帮助。 如何在Asyncask的OnPostExecute内添加标记?

这是我的代码的安排。直到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=====
        }
    }
}

1 个答案:

答案 0 :(得分:1)

mMap对象未设置任何内容。因此它将返回null。您可以这样设置:

@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");
}