从onPostExecute()发送值到Activity始终为NULL

3

我创建了这个类:

public class GetAddressPositionTask extends
        AsyncTask<String, Integer, LatLng> {
    //...
}

它具有以下功能:
@Override
    public void onPostExecute(LatLng result) {
        Log.i("GEOCODE", result.toString());

        super.onPostExecute(result);

        Intent i = new Intent(this.mainContxt , MapsActivity.class);

        i.putExtra("latlng" , result);

        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        this.mainContxt.startActivity(i);
    }

我将尝试从onPostExecute方法向名为MapsActivity的活动发送数据。
在MapsActivity中,在onCreate之前我有以下内容:
LatLng position = new LatLng(34.6767, 33.04455);

我的onCreate方法:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

            if (getIntent() != null) {
                Intent intent = getIntent();

                if (getIntent().getExtras().getParcelable("latlng")!= null) {
                    position = getIntent().getExtras().getParcelable("latlng");
                }
                else {
                    Log.d("NULL?", "position is empty!");
                }
            } else {
            }

            MapFragment mapFragment = (MapFragment) getFragmentManager()
                    .findFragmentById(R.id.
                            map);
            mapFragment.getMapAsync(this);
    }

这是我的onMapReady函数,用于创建一个标记并显示我初始化的位置。当您输入地址并按下搜索按钮时,它会调用上面的class,并尝试在地图上标记位置(如果该位置不为空)。

@Override
    public void onMapReady(final GoogleMap map) {
        map.setMyLocationEnabled(true);
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13));
        CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
        map.animateCamera(zoom);

        map.addMarker(new MarkerOptions()
                .title("Shop")
                .snippet("Is this the right location?")
                .position(position))
                .setDraggable(true);

        // map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
        map.setOnInfoWindowClickListener(this);
        map.setOnMarkerDragListener(this);

        ImageButton search = (ImageButton) findViewById(R.id.search);

        final EditText searchaddress = (EditText) findViewById(R.id.locationsearch);

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //FIND LOCATION BY ADDRESS

                if (searchaddress.getText().toString() != null && !searchaddress.getText().toString().isEmpty()) {

                    new GetAddressPositionTask(getApplicationContext()).execute(searchaddress.getText().toString());

                    map.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13));
                    CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
                    map.animateCamera(zoom);

                    //Marker marker = null;
                    map.clear();
                    //marker.setPosition(position);
                    map.addMarker(new MarkerOptions()
                            .title("Shop")
                            .snippet("Is this the right location?")
                            .position(position))
                            .setDraggable(true);

                    // map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
                    map.setOnInfoWindowClickListener(MapsActivity.this);
                    map.setOnMarkerDragListener(MapsActivity.this);
                } else {
                    Toast.makeText(getApplicationContext(), "Please enter an address!", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

我的操作是打开MapsActivity,然后输入正确的地址并尝试显示它。 结果是位置没有改变,但在点击按钮后我没有在logcat中收到消息NULL?﹕ position is empty!


这是我第一次导航到MapsActivity并点击调用该类的按钮时的logcat:

02-24 20:55:35.133    5907-5907/guide_me_for_all.guide_me_for_all E/Spinner﹕ setPopupBackgroundDrawable: incompatible spinner mode; ignoring...
02-24 20:55:35.143    5907-5907/guide_me_for_all.guide_me_for_all E/Spinner﹕ setPopupBackgroundDrawable: incompatible spinner mode; ignoring...
02-24 20:55:35.143    5907-5907/guide_me_for_all.guide_me_for_all E/Spinner﹕ setPopupBackgroundDrawable: incompatible spinner mode; ignoring...
02-24 20:55:35.223    5907-5907/guide_me_for_all.guide_me_for_all I/Choreographer﹕ Skipped 47 frames!  The application may be doing too much work on its main thread.
02-24 20:55:36.775    5907-5907/guide_me_for_all.guide_me_for_all I/Timeline﹕ Timeline: Activity_launch_request id:guide_me_for_all.guide_me_for_all time:42579264
02-24 20:55:36.865    5907-5907/guide_me_for_all.guide_me_for_all I/x﹕ Making Creator dynamically
02-24 20:55:37.265    5907-5907/guide_me_for_all.guide_me_for_all I/Google Maps Android API﹕ Google Play services client version: 6587000
02-24 20:55:37.285    5907-5907/guide_me_for_all.guide_me_for_all I/Google Maps Android API﹕ Google Play services package version: 6776034
02-24 20:55:38.406    5907-5907/guide_me_for_all.guide_me_for_all I/dalvikvm﹕ Could not find method android.content.pm.PackageManager.getPackageInstaller, referenced from method com.google.android.gms.common.ew.c
02-24 20:55:38.406    5907-5907/guide_me_for_all.guide_me_for_all W/dalvikvm﹕ VFY: unable to resolve virtual method 441: Landroid/content/pm/PackageManager;.getPackageInstaller ()Landroid/content/pm/PackageInstaller;
02-24 20:55:38.406    5907-5907/guide_me_for_all.guide_me_for_all D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000f
02-24 20:55:39.117    5907-5907/guide_me_for_all.guide_me_for_all D/NULL?﹕ position is empty!
02-24 20:55:39.377    5907-5907/guide_me_for_all.guide_me_for_all I/Choreographer﹕ Skipped 57 frames!  The application may be doing too much work on its main thread.
02-24 20:55:39.517    5907-5907/guide_me_for_all.guide_me_for_all I/libblt_hw﹕ Library opened (handle = 0, fd = 100)
02-24 20:55:39.788    5907-5907/guide_me_for_all.guide_me_for_all I/Timeline﹕ Timeline: Activity_idle id: android.os.BinderProxy@424fec18 time:42582274
02-24 20:55:41.970    5907-5912/guide_me_for_all.guide_me_for_all I/dalvikvm﹕ Jit: resizing JitTable from 4096 to 8192
02-24 20:55:47.946    5907-6133/guide_me_for_all.guide_me_for_all I/GEOCODE_background﹕ lat/lng: (64.963051,-19.020835)
02-24 20:55:47.946    5907-5907/guide_me_for_all.guide_me_for_all I/GEOCODE﹕ lat/lng: (64.963051,-19.020835)
02-24 20:55:47.946    5907-5907/guide_me_for_all.guide_me_for_all I/Timeline﹕ Timeline: Activity_launch_request id:guide_me_for_all.guide_me_for_all time:42590434

Log.i("GEOCODE", result.toString()); 中获取数值? - ρяσѕρєя K
是的,我在logcat中得到了正确的值@ρяσѕρєяK。 - Marialena
@Ranjith 我已经发布了。@user370305 我的onCreate()方法里面有很多不必要的东西。这是跟获取数值有关的部分: `if (getIntent() != null) { Intent intent = getIntent(); position_from_address = intent.getStringExtra("latlng"); Toast.makeText(MapsActivity.this.getApplicationContext(), position_from_address, Toast.LENGTH_LONG).show();` - Marialena
@marialena:日志中没有收到 Log.d("NULL?", "position is empty!"); 吗? - ρяσѕρєя K
1
@marialena:将 position 值存储在 SharedPreferences 中,因为您可能正在从 MapsActivity 活动转移到其他活动,所以无法再次获得相同的值。将值存储在 SharedPreferences 中。 - ρяσѕρєя K
显示剩余16条评论
1个回答

2

一些有点令人困惑的代码和解释,

我们来逐步进行。

第一步:更新你的MapsActivity的onCreate()方法

像这样,

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

这里不需要使用Intent,因为您只是在同一个MapsActivity中调用MapsActivity,我们将在ActivityonPostExecute()中更新地图,因此无需重新启动Activity。

第二步:GetAddressPositionTask创建构造函数,带有GoogleMap map参数,以在GetAddressPositionTaskonPostExecute()中更新您的地图位置。和onPostExecute()

例如,

public class GetAddressPositionTask extends
        AsyncTask<String, Integer, LatLng> {

  GoogleMap googleMap;
  LatLng mapPosition;

  GetAddressPositionTask(GoogleMap map, LatLng position)
  {
   googleMap = map;
   mapPosition = position;
  }
    //...
@Override
    public void onPostExecute(LatLng result) {

     if(result != null)
     {
       Log.i("GEOCODE", result.toString());
       mapPosition =  result;

        googleMap.clear();
        googleMap.addMarker(new MarkerOptions()
                            .title("Shop")
                            .snippet("Is this the right location?")
                            .position(mapPosition))
                            .setDraggable(true);
      }
   }
}

步骤3:搜索按钮的onClick()长什么样子,不需要额外的代码。

public void onClick(View v) {
   //FIND LOCATION BY ADDRESS

   if (searchaddress.getText().toString() != null && !searchaddress.getText().toString().isEmpty()) {

          GetAddressPositionTask addressTask = new GetAddressPositionTask(map, position);
          addressTask.execute(searchaddress.getText().toString());

  } else {
          Toast.makeText(getApplicationContext(), "Please enter an address!", Toast.LENGTH_LONG).show();
  }
}

它运行得很好,位置在地图上正确显示。非常感谢您的帮助。但我想问一下...有没有办法将这个位置返回给MapsActivity,或者说没有办法让它工作?因为那个位置是我们从类中获取的最后一个位置,我不得不将其传递到另一个活动和片段中,与MapsActivity不同,以便我可以保存它。 - Marialena
1
@marialena - 将您的位置存储在SharedPreferences中,您可以使用Context访问任何应用程序组件。 - user370305
@marialena - 祝你编程愉快..!可以使用 @ 符号和我的用户名。 :) - user370305

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接