【问题标题】:Send Value From onPostExecute() to Activity is always NULL从 onPostExecute() 向 Activity 发送值始终为 NULL
【发布时间】:2015-02-24 18:18:37
【问题描述】:

我创建了这个类:

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 的 Activity 发送数据。


在 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,它使用我初始化的位置创建了 pin,当您输入地址并按下搜索按钮时,它会调用具有 onPost 功能的上述类,并尝试在地图中固定位置,如果位置不为空。

@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()); 中获取价值?
  • 是的,我在 logcat @ρяσѕρєяK 中得到了正确的值。
  • @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();
  • @user370305 我更新了我的问题。
  • @marialena:将position 值存储在SharedPreferences 中,因为您可能正在从MapsActivity 活动转移到其他活动,这就是为什么不再获得相同值的原因。将值存储在SharedPreferences

标签: java android android-intent android-asynctask


【解决方案1】:

有些混乱的代码和解释,

让我们一步一步来。

第 1 步:更新 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。我们会在Activity的onPostExecute()更新map,这样就不需要再启动Activity了。

第 2 步: 使用 GoogleMap map 参数为 GetAddressPositionTask 创建构造函数,以更新您在 onPostExecute()GetAddressPositionTask 中的地图位置。还有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 或者没有办法让它工作?因为那个位置是我们从类中获得的最后一个位置,所以我必须将它传递给另一个 Activity 和 Fragment,这与 MapsActivity 不同,以便我可以保存它。
  • @marialena - 将您的位置存储在SharedPreferences 中,您可以使用任何带有上下文的应用程序组件访问它..
  • @marialena - 编码快乐..!可用于 @ 和我的用户名。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-18
  • 2014-05-30
  • 1970-01-01
  • 1970-01-01
  • 2017-12-08
  • 2016-10-28
相关资源
最近更新 更多