Strelok Strelok - 1 year ago 152
Java Question

Android Add Map Marker Error: java.lang.IllegalStateException: Not on the main thread

I'm subscribing to a data stream that gets pushed coordinates, I want to place a marker on the map every time the listener gets a new point. What do I need to do to put the drawMarker code on the correct thread or in the correct scope?

public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;


public void drawLatestPoint(LatLng p) {
mMap.addMarker(new MarkerOptions().position(p).title("Marker in Sydney"));

private void subscribe(){
.channels(Arrays.asList("my_channel")) // subscribe to channel groups

pubNub.addListener(new SubscribeCallback() {

public void message(PubNub pubnub, PNMessageResult message) {
if (message.getMessage().get("lat") != null && message.getMessage().get("lng") != null) {
double lat = message.getMessage().get("lat").doubleValue();
double lng = message.getMessage().get("lng").doubleValue();
LatLng point = new LatLng(lat,lng);

Answer Source

You can use runOnUiThread to run the code in the GUI thread:

runOnUiThread(new Runnable() {
    public void run() {
       // Your code to run in GUI thread here
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download