Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

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=====
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...