如何从 StringBuilder 获取值并将其传递给另一个 activity?

How to get value from StringBuilder and pass it to another activity?

我有一个 StringBuilder 变量,我想从中获取最终值并将其传递给另一个 activity。我想在编辑文本视图中显示最终的字符串值。

我尝试使用 toString() 方法获取值,但我无法在空白文本视图中看到该值。

 String value=str.toString();
 intent.putExtra("value",value);

 startActivity(intent);

通过这个我得到了价值并发送到第二个activity。

 Intent intent = this.getIntent();
 String data = intent.getStringExtra("keyName");
 edtxt_from.setText(data);

使用这个我得到了第二个 activity 中的值。

怎么了?? 请帮忙...

我在编辑文本视图中没有得到更新的地址..

ChooseFromMapActivity

public class ChooseFromMapActivity 扩展 AppCompatActivity 实现 位置监听器,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 = new Intent(ChooseFromMapActivity.this,GoSend.class);
            String value=str.toString();
            intent.putExtra("value",value);

        }
    });
}


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));
    }

    //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));*/
    Intent intent = this.getIntent();
    String data = intent.getStringExtra("value");
    edtxt_from.setText(data);

 //   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);
        }
    });

}

}

改变

String data = intent.getStringExtra("keyName");

String data = intent.getStringExtra("value");

您使用了错误的密钥。

简单地做: 将 keyName 替换为 value