如何将地址从地理编码器 class 发送到另一个 activity?

How to send address from geocoder class to another activity?

我的应用程序中有这个特定的 ChooseFromMapActivity。在此地址是通过使用反向地理编码获取的,因此当我们移动地图时,位置会在下面使用位置布局的 TextView 上更改。 如下所示:

现在我想在另一个 activity 的编辑文本视图中显示这个特定的当前位置。如下所示:

在此,在地理编码器中 class 位置存储在 StringBuilder str 变量中。所以我试图从 str 中检索字符串并将其显示在文本视图中。但它并不是文本视图中显示的完美地址。 str 变量只显示本地区域和邮政编码。我想在编辑文本视图中显示完美的地理编码值。那么使用 StringBuilder 变量的方法是否正确?或者还有其他方法可以实现吗??

其中经纬度存储在center变量中,这个center变量是latlng变量。我们可以将 latlng 变量传递给另一个 activity 吗?我们如何在编辑文本视图中显示 latlng 变量地址? 请帮帮我..

ChooseFromMapActivity

   public class ChooseFromMapActivity extends AppCompatActivity implements
    LocationListener, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {

private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;

private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude;
double longitude;
private GPSTracker gps;
private LatLng curentpoint;
private LinearLayout useLocation;
Intent intent;
double x, y;
StringBuilder str;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_choose_from_map);
    Address = (TextView) findViewById(R.id.textShowAddress);
    markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
    useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);

    int status = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(getBaseContext());

    if (status != ConnectionResult.SUCCESS) { // Google Play Services are
        // not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
                requestCode);
        dialog.show();

    } else { // Google Play Services are available

        // Getting reference to the SupportMapFragment
        // Create a new global location parameters object
        mLocationRequest = LocationRequest.create();

        /*
         * Set the update interval
         */
        mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);

        // Use high accuracy
        mLocationRequest
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        // Set the interval ceiling to one minute
        mLocationRequest
                .setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);

        // Note that location updates are off until the user turns them on
        mUpdatesRequested = false;

        /*
         * Create a new location client, using the enclosing class to handle
         * callbacks.
         */
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).build();

        mGoogleApiClient.connect();
    }

    useLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


           /* Intent intent = new Intent(ChooseFromMapActivity.this ,GoSend.class);
           intent.putExtra("latitude",latitude);
            intent.putExtra("Longitude",longitude);
            startActivity(intent);*/
        ///    Bundle bundle = new Bundle();
          //  bundle.putSerializable("value",str);
          //  intent.putExtras(bundle);

            intent = new Intent(ChooseFromMapActivity.this,GoSend.class);
            String value=str.toString();
           // intent.putExtra("value",value);
            intent.putExtra("x",x);
            intent.putExtra("y",y);
            startActivity(intent);

         //   intent.putExtra("string", (Serializable) str);

          //  Bundle args = new Bundle();
            //args.putParcelable("from_position",curentpoint);
          //  intent.putExtra("bundle", args);
            //Bundle bundle = new Bundle();

        }
    });
}


private void stupMap() {
    try {

        mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
                R.id.map)).getMap();

        // Enabling MyLocation in Google Map
        mGoogleMap.setMyLocationEnabled(true);
        mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
        mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
        mGoogleMap.getUiSettings().setCompassEnabled(true);
        mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
        mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);

        gps = new GPSTracker(this);

        gps.canGetLocation();

        latitude = gps.getLatitude();
        longitude = gps.getLongitude();
        curentpoint = new LatLng(latitude, longitude);

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(curentpoint).zoom(19f).tilt(70).build();

        mGoogleMap.setMyLocationEnabled(true);
        mGoogleMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));
        // Clears all the existing markers
        mGoogleMap.clear();

        mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {

            @Override
            public void onCameraChange(CameraPosition arg0) {
                // TODO Auto-generated method stub
                center = mGoogleMap.getCameraPosition().target;

                mGoogleMap.clear();
                markerLayout.setVisibility(View.VISIBLE);

                try {
                    new GetLocationAsync(center.latitude, center.longitude)
                            .execute();

                } catch (Exception e) {
                }
            }
        });


    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
public void onLocationChanged(Location location) {
    // TODO Auto-generated method stub

}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onConnected(Bundle arg0) {
    // TODO Auto-generated method stub
    stupMap();

}

private class GetLocationAsync extends AsyncTask<String, Void, String> {

    // boolean duplicateResponse;


    public GetLocationAsync(double latitude, double longitude) {
        // TODO Auto-generated constructor stub

        x = latitude;
        y = longitude;
    }

    @Override
    protected String doInBackground(String... params) {

        try {
            geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
            addresses = geocoder.getFromLocation(x, y, 1);
            str = new StringBuilder();
            if (Geocoder.isPresent()) {

                if ((addresses != null) && (addresses.size() > 0)) {
                    Address returnAddress = addresses.get(0);

                    String localityString = returnAddress.getLocality();
                    String city = returnAddress.getCountryName();
                    String region_code = returnAddress.getCountryCode();
                    String zipcode = returnAddress.getPostalCode();

                    str.append(localityString + "");
                    str.append(city + "" + region_code + "");
                    str.append(zipcode + "");



                }
            } else {
            }
        } catch (IOException e) {
            Log.e("tag", e.getMessage());
        }
        return null;

    }

    @Override
    protected void onPostExecute(String result) {
        try {
            Address.setText(addresses.get(0).getAddressLine(0)
                    + addresses.get(0).getAddressLine(1) + " ");


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onProgressUpdate(Void... values) {

    }
}

@Override
public void onConnectionSuspended(int arg0) {
    // TODO Auto-generated method stub

}
      }

去发送

public class GoSend extends AppCompatActivity {
LatLng latLng;
private GoogleMap mMap;
MarkerOptions markerOptions;
LinearLayout ll;
Toolbar toolbar;
EditText editTextLocation;
EditText edtxt_from;
EditText edtxt_to;



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

    Location l=new Location();
    setUI();

    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
    }



    Intent intent = this.getIntent();
    String data = intent.getStringExtra("x");
    String d=intent.getStringExtra("y");
    String data1=(data+d);
    edtxt_from.setText(data1);


    //Bundle bundle = getIntent().getParcelableExtra("bundle");
 //  double fromPosition = bundle.getParcelable("from_position");

  //  edtxt_from.setText(fromPosition);
   /* Bundle extras = getIntent().getExtras();
   if (extras != null) {
        double latitude = extras.getDouble("latitude");
       double longitude = extras.getDouble("Longitude");


        edtxt_from.setText(String.valueOf(latitude));*/


 //   Bundle bundle = intent.getExtras();

//    Serializable value =bundle.getSerializable("value");

     //   edtxt_from.setText(String.valueOf(longitude));
    }



@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }
    return super.onOptionsItemSelected(item);
}

public void setUI() {

    ll = (LinearLayout) findViewById(R.id.LinearLayoutGoSend);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle("GO-SEND");



    try {
        if (mMap == null) {
            mMap = ((MapFragment) getFragmentManager().
                    findFragmentById(R.id.map)).getMap();
        }
        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        mMap.setMyLocationEnabled(true);
    } catch (Exception e) {
        e.printStackTrace();
    }

     edtxt_from=(EditText)findViewById(R.id.editText_from);
     edtxt_to=(EditText)findViewById(R.id.editText_to);

    edtxt_from.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
            startActivity(i);
        }
    });

    edtxt_to.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent  i=new Intent(getApplicationContext(),PickLocationActivity.class);
            startActivity(i);
        }
    });

}
       }

您可以将地址作为字符串从一个 activity 传递到另一个 activity,方法是在用于启动另一个 activity 的意图中设置该地址,例如

Intent intent = new Intent(ChooseFromMapActivity.this, GoSend.class); 
intent.putExtra("addressTag", stringAddress);
startActivity(intent);

另一方面在接收中activity你可以这样得到它

Bundle bundle = getIntent().getExtras();
if(bundle != null)
    String stringAddress = bundle.getString("addressTag");

更简单的方法是创建一个名为 Address 的模型class。

class Address implements Serializable{

String Street;

String City;
//...Fileds

}

在此 class 中填写信息并在意图中将其作为可序列化对象发送。