How to send android.location.Address with intent as putextra
-
17-06-2021 - |
Question
Is it possible to put an instance of android.location.Address
with Intent
to another activity?
Address current_location;
I mean, I am trying to put current_location directly with the intent by:
IntentName.putExtra("current_location",current_location);
or indirectly by a bundle:
Bundle b = new Bundle(); b.put....("current_location",current_location); IntentName.put(b);
If none of the above strategy support "Address" then what should be the best approach to pass the Address instance to another activity?
If I declare,
public static Address current_location;
and try to access it from another activity then there is no guarantee that Android will hold current_location data. Or am I wrong?
In such situation, what approach should be followed?
Solution
You'll want to pass it through as a parcelable. By looking at the API, I think they already conform to the standard.
Address extends Object implements Parcelable
https://developer.android.com/reference/android/location/Address.html
So to package it up and send it you would do:
String key = getResources().getString(key);
startActivity( new Intent()
.setClass(this, YourActivity.class)
.putExtra(key, current_location )
);
Then to reassemble it in your activity you would do:
String key = getResources().getString(key);
Address current_location = getIntent().getExtras().getParcelable(key);
The key is simply the name you use to store the parcelable under.
OTHER TIPS
I don't know whether you'd be able to pass an Address (see below), but why not just pass the longitude and latitude (both double
s, which can be placed as extras) and then reconstruct it in the next Activity?
Address does seem to implement the Parcelable
interface which means you may be able to send it as intent.putParcelable(key, address)
.