6

我要做的最后一件事是:我的应用程序中有谷歌地图,带有一些按钮和额外的东西。但我还必须始终在我的地图内显示标记的更新位置(我将从外部设备而不是安卓手机的 gps 传感器获取数据)。所以我想先使用线程,然后更改为 AsyncTask,正如您在我的代码中看到的那样,并尝试在那里使用 addMarker 方法,但每次运行它时,map 都会停止工作。我现在只想在地图上显示一个标记,但现在成功了!GoogleMap 地图无法通过 UI 线程和 AsyncTask 内部访问,为什么?有人遇到过这个吗?我应该怎么做才能解决这个问题...请帮助

 package com.example.mapsversion2;

    //All imports

    public class MainActivity extends Activity  {
    static final LatLng exmpoint = new LatLng(59.331438,18.064957);

    public static GoogleMap map;

    Button button;
    Button waypointButton;
    Button destinationButton;
    Marker wayPoint;
    TextView positiontext;
    int countclick= 3;
    public static DataModel autoboxdata= new DataModel();
    public static Bitmap arrowBitmap;
    Marker currentPlace;
    MapFragment mapF;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     mapF = ((MapFragment) getFragmentManager().findFragmentById(R.id.map));
     map= mapF.getMap();
     map.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    //  positiontext = (TextView) findViewById(R.id.position);

    // Move the camera instantly to hamburg with a zoom of 15.
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(exmpoint,15));

    // Zoom in, animating the camera.
    map.animateCamera(CameraUpdateFactory.zoomTo(6), 2000, null);

    addListenerOnButton();
    map.setOnMarkerDragListener(this);

    new PositionUpdate1().execute(); 
  }
    @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
  }

  public void addListenerOnButton() {

        destinationButton= (Button) findViewById(R.id.destinationB);

        destinationButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                //do something
            }
        });     
    }

  }

    public class PositionUpdate1  extends AsyncTask<Void, Void, Void>{


    @Override
    protected Void doInBackground(Void...arg0) {
        // TODO Auto-generated method stub


        map.addMarker(new MarkerOptions()
            .position(hereIam) );

        System.out.println("hej");
        return null;
    } 
  }
    } 

这是LogCat:

02-17 18:57:17.805: E/AndroidRuntime(9905): FATAL EXCEPTION: main
02-17 18:57:17.805: E/AndroidRuntime(9905): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mapsv2/com.example.mapsv2.MainActivity}: java.lang.NullPointerException
02-17 18:57:17.805: E/AndroidRuntime(9905):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100)
02-17 18:57:17.805: E/AndroidRuntime(9905):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
02-17 18:57:17.805: E/AndroidRuntime(9905):     at android.app.ActivityThread.access$600(ActivityThread.java:140)
02-17 18:57:17.805: E/AndroidRuntime(9905):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
02-17 18:57:17.805: E/AndroidRuntime(9905):     at android.os.Handler.dispatchMessage(Handler.java:99)
02-17 18:57:17.805: E/AndroidRuntime(9905):     at android.os.Looper.loop(Looper.java:137)
02-17 18:57:17.805: E/AndroidRuntime(9905):     at android.app.ActivityThread.main(ActivityThread.java:4898)
02-17 18:57:17.805: E/AndroidRuntime(9905):     at java.lang.reflect.Method.invokeNative(Native Method)
02-17 18:57:17.805: E/AndroidRuntime(9905):     at java.lang.reflect.Method.invoke(Method.java:511)
02-17 18:57:17.805: E/AndroidRuntime(9905):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
02-17 18:57:17.805: E/AndroidRuntime(9905):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
02-17 18:57:17.805: E/AndroidRuntime(9905):     at dalvik.system.NativeStart.main(Native Method)
02-17 18:57:17.805: E/AndroidRuntime(9905): Caused by: java.lang.NullPointerException
02-17 18:57:17.805: E/AndroidRuntime(9905):     at com.example.mapsv2.MainActivity.onCreate(MainActivity.java:140)
02-17 18:57:17.805: E/AndroidRuntime(9905):     at android.app.Activity.performCreate(Activity.java:5206)
02-17 18:57:17.805: E/AndroidRuntime(9905):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1083)
02-17 18:57:17.805: E/AndroidRuntime(9905):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2064)
02-17 18:57:17.805: E/AndroidRuntime(9905):     ... 11 more
02-17 18:57:17.935: E/android.os.Debug(2287): !@Dumpstate > dumpstate -k -t -z -d -o /data/log/dumpstate_app_error
4

3 回答 3

17

您正在尝试在后台线程中向地图添加标记,但您无法从 UI 线程以外的线程更新 Android 中的 UI。因此,将您的map.addMarker调用移至onPostExecute后台操作完成后在 UI 线程中调用的方法:

public class PositionUpdate1  extends AsyncTask<Void, Void, Location> {

    @Override
    protected Location doInBackground(Void...arg0) {
        // get your location...
        return hereIam;
    }

    @Override
    protected void onPostExecute(Location loc) {
        map.addMarker(new MarkerOptions().position(loc));
    }
}

如果要连续更新标记,最简单的方法是使用Handler

public class MainActivity extends Activity {

    final int MARKER_UPDATE_INTERVAL = 2000; /* milliseconds */
    Handler handler = new Handler();

    GoogleMap map;
    Marker marker;
    Location location;

    Runnable updateMarker = new Runnable() {
        @Override
        public void run() {
            marker.remove();
            marker = map.addMarker(new MarkerOptions().position(location));

            handler.postDelayed(this, MARKER_UPDATE_INTERVAL);
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        map = ...; // get map
        location = ...; // get location
        marker = map.addMarker(new MarkerOptions().position(location));

        handler.postDelayed(updateMarker, MARKER_UPDATE_INTERVAL);
    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacks(updateMarker);

        super.onDestroy();
    }
}
于 2013-02-17T18:03:06.120 回答
3

你可以做这样的事情。在 doInBackground 中加载您需要的数据并在 onProgressUpdate 中绘制标记。要调用 onProgressUpdate,只需从 doInBackground 执行 publishProgress()。这样您就可以从 ASyncTask 中更新 UI。为我工作。

public class CDrawHotspotsAsync extends AsyncTask<Void, CHotspot, Boolean>
{
private final Context mCntxt;
private final GoogleMap mGMap;

// ---------------------------------------------------------

public CDrawHotspotsAsync(Context cntxt, GoogleMap gmap)
{
    this.mCntxt = cntxt;
    this.mGMap = gmap;
}

// ---------------------------------------------------------

private void drawMarker(GoogleMap gmap, CHotspot hotspot)
{
    // Set marker options
    MarkerOptions mo = new MarkerOptions();
    mo.position(hotspot.getPosition());
    mo.title(hotspot.getName());
    String descr = hotspot.getAddress() + ", " + hotspot.getPostal() + ", " + hotspot.getCity();
    mo.snippet(descr);
    mo.icon(BitmapDescriptorFactory.fromResource(R.drawable.hotspot_marker));

    // Add marker to map
    gmap.addMarker(mo);
}

// ---------------------------------------------------------

@Override
protected Boolean doInBackground(Void... params)
{
    // Get hotspots from database
    CHotspotList hotspots = new CHotspotList(this.mCntxt);
    ArrayList<CHotspot> arrHotspots = hotspots.getHotspotList();

    for (CHotspot hotspot : arrHotspots)
    {
        // Publish progress
        publishProgress(hotspot);
    }

    // Always return true
    return true;
}

// ---------------------------------------------------------

@Override
protected void onProgressUpdate(CHotspot... hotspot)
{
    // Draw the marker
    drawMarker(this.mGMap, hotspot[0]);
}
}
于 2013-08-19T15:01:29.487 回答
1

如果您的异步任务正在加载多个标记,您可以执行以下操作:

private class AddMarker implements Runnable {

    private GoogleMap map;
    private MarkerOptions options;

    public AddMarker(GoogleMap map, MarkerOptions options) {
        this.map = map;
        this.options = options;
    }

    @Override
    public void run()
    {
        map.addMarker(options);
    }
}
Runnable addMarker = new AddMarker(map, markerOptions);
activity.runOnUiThread(addMarker);

而且,当然,您应该使用活动对象构造异步任务。

于 2013-08-08T06:38:15.403 回答