Java 如何将当前位置从一个活动发送到另一个活动?
我正在使用map获取当前位置,现在我想将当前位置发送到另一个活动,该活动具有输入所有数据的表单。 我不知道应该使用哪些变量和方法来发送位置数据 从映射活动中选择 这是我获取当前位置的活动。现在单击useLocation布局,我想将此位置发送到另一个活动的编辑文本,即GoSendActivityJava 如何将当前位置从一个活动发送到另一个活动?,java,android,android-activity,location,send,Java,Android,Android Activity,Location,Send,我正在使用map获取当前位置,现在我想将当前位置发送到另一个活动,该活动具有输入所有数据的表单。 我不知道应该使用哪些变量和方法来发送位置数据 从映射活动中选择 这是我获取当前位置的活动。现在单击useLocation布局,我想将此位置发送到另一个活动的编辑文本,即GoSendActivity public class ChooseFromMapActivity extends AppCompatActivity implements LocationListener, Goog
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;
@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) {
}
});
}
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;
double x, y;
StringBuilder str;
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 Location {
private int id;
private String mFrom_loc;
private String mTo_loc;
private String mFromloc_details;
private String mToloc_details;
private String mItems_details;
public Location(int id,String mFrom_loc,String mFromloc_details,String mTo_loc,String mToloc_details,String mItems_details)
{
this.id=id;
this.mFrom_loc=mFrom_loc;
this.mFromloc_details=mFromloc_details;
this.mTo_loc=mTo_loc;
this.mToloc_details=mToloc_details;
this.mItems_details=mItems_details;
}
public Location(String mFrom_loc){
this.mFrom_loc=mFrom_loc;
}
public Location(){}
public int getId(int id){return id;}
public String getmFrom_loc(String mFrom_loc){return mFrom_loc;}
public String getmTo_loc(String mTo_loc){return mTo_loc;}
public String getmFromloc_details(String mFromloc_details){return mFromloc_details;}
public String getmToloc_details(String mToloc_details){return mToloc_details;}
public String getmItems_details(String mItems_details){return mItems_details;}
public void setId(){this.id=id;}
public void setmFrom_loc(){this.mFrom_loc=mFrom_loc;}
public void setmTo_loc(){this.mTo_loc=mTo_loc;}
public void setmFromloc_details(){this.mFromloc_details=mFromloc_details;}
public void setmToloc_details(){this.mToloc_details=mToloc_details;}
public void setmItems_details(){this.mItems_details=mItems_details;}
}
我怎样才能做到这一点??请帮助..将此类设置为可序列化,并使用bundle.putSerializable(“myclaa”,location)将其放入intent 类位置实现了Serializable{ }试试这个:
useLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ChooseFromMapActivity.this , GoSendActivity.class);
intent.putExtra("Latitude", latitude);
intent.putExtra("Longitude", longitude);
startActivity(intent);
}
});
在GoSendActivity的onCreate中,按如下方式获取纬度和经度:
Bundle extras = getIntent().getExtras();
if (extras != null) {
double latitude = extras.getDouble("Latitude");
double longitude = extras.getDouble("Longitude");
}
现在您可以将纬度和经度设置为edittext
edittext.setText(String.valueOf(latitude))代码>除了使用意图将数据传递到下一个活动之外,您还可以使用共享首选项,TinyDB lib在缓存数据方面取得了很好的效果。您需要在您的gradle文件中同步此文件:
compile 'com.mukesh:tinydb:1.0.1'
然后,在每个活动的onCreate中,通过传递应用程序上下文来初始化tinyDB
TinyDB tinyDB = new TinyDB(getApplicationContext());
有了它,您可以使用键值对在应用程序中存储和检索任何数据,例如,要存储您的坐标,只需调用:
tinyDB.putDouble("latitude",latitude);
tinyDB.putDouble("longitude",longitude);
您可以通过以下方式检索数据:
double latitude = tinyDB.getDouble("latitude");
double longitude = tinyDB.getDouble("longitude");
该类支持所有数据格式,包括字符串、双精度、浮点,甚至是ArarayList之类的对象。强烈建议您试用。设置onClickListener并使用putExtra()方法在其中添加您的位置,从而创建新的Intent()。做一个小小的谷歌搜索,你会看到很多例子。相关:是的,我可以通过put额外的方法传递给另一个活动。但是如何将我的位置添加到location类变量中呢?我认为您的位置
类中的set-and-get函数已被交换。我真的不明白你的问题。您不想知道如何在位置
类实例中设置值吗?这就是setter的用途。使用这个答案,它可能会帮助我们询问您的答复。我试试这个。但我的纬度和经度存储在拉特朗的中心变量中。这是否有助于获得单独的纬度和经度值@bhargavI希望在我的编辑文本视图中显示反向地理编码值@bhargavrefer和我已经完成了获取反向地理编码位置的步骤。现在我只想在GoSendActivity的编辑文本视图中看到这一点@bhargavIf我将此代码放在onCreate of GoSend活动中,它给我一个异常,试图在double latitude=intent2.getExtras().getDouble(“latitude”)上的空对象引用上调用虚拟方法“double android.os.Bundle.getDouble(java.lang.String)”;这一行。使用此库优于sharedPref
?@androidXP。tinyDB库直接来自共享首选项。所有共享偏好的优点和缺点都是tinyDB的优点和缺点。您可以在这里查看原始java文件,如果两者都是,则没有理由添加额外的库same@androidXp这是正确的。与原始共享首选项体系结构相比,Its使共享首选项实例更容易使用,体积更小。但那只是我的意见。您可以尝试这两种方法并选择最适合您的方法,但它们的缓存体系结构是相同的。实际上,我使用的是共享首选项,没有发现任何问题。我认为这将是一些有用的东西,我也可以实施。谢谢你的意见
double latitude = tinyDB.getDouble("latitude");
double longitude = tinyDB.getDouble("longitude");