How to plot on maps from arraylist with lon/lat? - java

This is my Map Class...
public class Mapa extends FragmentActivity implements LocationListener {
public GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa);
Getting Google Play availability status
int status =GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else {
Getting reference to the SupportMapFragment
SupportMapFragment fm = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
Getting GoogleMap object from the fragment
map = fm.getMap();
Enabling MyLocation Layer of Google Map
map.setMyLocationEnabled(true);
Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager)
getSystemService(LOCATION_SERVICE);
Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
Getting latitude of the current location
double latitude = location.getLatitude();
Getting longitude of the current location
double longitude = location.getLongitude();
Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
Showing the current location in Google Map
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
Zoom in the Google Map
map.animateCamera(CameraUpdateFactory.zoomTo(15));
Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
And this is my class with the arraylist
public void getPontos(View view) {
String codigo;
codigo = linhaList.get(spinner.getSelectedItemPosition()).getCodigo();
new WebServiceGetPontosLinha().execute(codigo);
}
private class WebServiceGetPontosLinha extends
AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this, "",
getResources().getText(R.string.connecting), true, false);
}
#Override
protected Void doInBackground(String... params) {
WebServiceConsumer webServiceConsumer = new WebServiceConsumer(
MainActivity.this);
pontoList = webServiceConsumer.getPontos(params[0]);
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
pontoArrayAdapter = new ArrayAdapter<PontosLinhas>(
MainActivity.this,
android.R.layout.simple_spinner_dropdown_item, pontoList);
spinner1.setAdapter(pontoArrayAdapter);
}
}
How do I plot the content of spinner on maps like an image?

This involves a lot of details which is not needed for your but hope you get the picture.
I developed an app that among other things shows the location of hydrants on a map and this is how I load the hydrants to the map:
private class LoadHydrantsToMapTask extends
AsyncTask<Hydrant, Integer, List<MarkerOptions>> {
private int loadHydrantsGoal = 0;
public LoadHydrantsToMapTask(int loadHydrantsGoal) {
this.loadHydrantsGoal = loadHydrantsGoal;
}
// Before running code in separate thread
#Override
protected void onPreExecute() {
Device.lockOrientation((Activity)context);
// Create a new progress dialog.
progressDialog = new ProgressDialog(context);
// Set the progress dialog to display a horizontal bar .
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage(context
.getString(R.string.adding_hydrants));
// This dialog can't be canceled by pressing the back key.
progressDialog.setCancelable(false);
// This dialog isn't indeterminate.
progressDialog.setIndeterminate(false);
// The maximum number of progress items is 100.
progressDialog.setMax(loadHydrantsGoal);
// Set the current progress to zero.
progressDialog.setProgress(0);
// Display the progress dialog.
progressDialog.show();
}
// The code to be executed in a background thread.
#Override
protected List<MarkerOptions> doInBackground(Hydrant... hydrants) {
List<MarkerOptions> markers = new ArrayList<MarkerOptions>();
for (Hydrant hydrant : hydrants) {
final String hydrant_type = hydrant.getHydrantType();
final String hydrant_icon_path = hydrant.getIconPath();
double latitude = hydrant.getLatitude();
double longitude = hydrant.getLongitude();
final LatLng position = new LatLng(latitude, longitude);
final String address = hydrant.getAddress();
final String addressNumber = hydrant.getAddressNumber();
final String addressremark = hydrant.getAddressRemark();
final String remark = hydrant.getRemark();
BitmapDescriptor icon = BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED);
if (!hydrant_icon_path.isEmpty()) {
File iconfile = new File(hydrant_icon_path);
if (iconfile.exists()) {
BitmapDescriptor loaded_icon = BitmapDescriptorFactory
.fromPath(hydrant_icon_path);
if (loaded_icon != null) {
icon = loaded_icon;
} else {
Log.e(TAG, "loaded_icon was null");
}
} else {
Log.e(TAG, "iconfile did not exist: "
+ hydrant_icon_path);
}
} else {
Log.e(TAG, "iconpath was empty on hydrant type: "
+ hydrant_type);
}
StringBuffer snippet = new StringBuffer();
if (!address.isEmpty())
snippet.append("\n" + address + " " + addressNumber);
if (addressremark.isEmpty())
snippet.append("\n" + addressremark);
if (!remark.isEmpty())
snippet.append("\n" + remark);
markers.add(new MarkerOptions().position(position)
.title(hydrant_type).snippet(snippet.toString())
.icon(icon));
publishProgress(markers.size());
}
return markers;
}
// Update the progress
#Override
protected void onProgressUpdate(Integer... values) {
// set the current progress of the progress dialog
progressDialog.setProgress(values[0]);
}
// after executing the code in the thread
#Override
protected void onPostExecute(List<MarkerOptions> markers) {
GoogleMap map = GoogleMapsModule.getInstance().getMap();
for (MarkerOptions marker : markers) {
if (marker != null)
map.addMarker(marker);
}
if (markers.size() == mHydrants.size()) {
setAllHydrantAdded(true);
setNearbyHydrantsAdded(true);
} else {
setNearbyHydrantsAdded(true);
}
Device.releaseOrientation((Activity) context);
}
}
When I call the task, I have a list of Hydrant objects. To parse the list to the AsyncTask I convert the list into an Array:
new LoadHydrantsToMapTask(hydrants.size()).execute(hydrants
.toArray(new Hydrant[hydrants.size()]));

Related

How to get my location? [duplicate]

This question already has answers here:
How to calculate distance between two locations using their longitude and latitude value
(14 answers)
Closed 5 years ago.
I am new with maps in android i have this code :
enter codepublic class MapsActivity extends FragmentActivity implements GoogleMap.OnMyLocationButtonClickListener,
GoogleMap.OnMyLocationClickListener,
OnMapReadyCallback {
private GoogleMap mMap;
Button req_button;
String[] lat;
String[] lon;
String[] id;
String[] emails;
double latitude,lonitude;
int result_search,StatusChange_customer;
String params_search ,Status_cheked_customer,params_checked_customer,Status_cheked_customer_rating;
public Handler mHandler;
Location location;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Intent intent1 = getIntent();
lat = intent1.getStringArrayExtra("latitute");
lon = intent1.getStringArrayExtra("longitude");
id = intent1.getStringArrayExtra("id");
emails = intent1.getStringArrayExtra("emails");
latitude=intent1.getDoubleExtra("MyLat",0);
lonitude=intent1.getDoubleExtra("MyLon",0);
req_button =(Button)findViewById(R.id.R_id);
this.mHandler = new Handler();
this.mHandler.postDelayed(m_Runnable,5000);
}
private final Runnable m_Runnable = new Runnable()
{
public void run()
{
Search_for_Accepted_Job();
Toast.makeText(MapsActivity.this,"in runnable",Toast.LENGTH_SHORT).show();
MapsActivity.this.mHandler.postDelayed(m_Runnable, 10000);
}
};
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LatLng [] sydeny = new LatLng[lat.length];
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// Add a marker in Sydney and move the camera
for (int i=0 ; i< lat.length;i++) {
sydeny[i] = new LatLng(Double.parseDouble(lat[i]), Double.parseDouble(lon[i]));
}
for (int i=0 ; i< sydeny.length;i++) {
mMap.addMarker(new MarkerOptions().position(sydeny[i]).title(emails[i]+ " " + id[i]));
// mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydeny[i], 5));
}
LatLng sydeny1 = new LatLng(latitude,lonitude);
mMap.addMarker(new MarkerOptions().position(sydeny1).title("Your location" ));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydeny1, 5));*/
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(this);
mMap.setOnMyLocationClickListener(this);
}
public void Request(View view) {
Toast.makeText(this," Request",Toast.LENGTH_SHORT).show();
for (int i=0; i< lat.length;i++)
{
send_request(id[i]);
}
req_button.setEnabled(false);
}
#Override
public boolean onMyLocationButtonClick() {
Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
return false;
}
#Override
public void onMyLocationClick(#NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
lonitude=location.getLatitude();
lonitude=location.getLongitude();
}
So this code take a latitude and longitude from another activity and present them in Map , recently i tried to implement two interfaces
(GoogleMap.OnMyLocationButtonClickListener
GoogleMap.OnMyLocationClickListener)
and i get my location with blue circle in map and change at real time with me and there is a method named
public void onMyLocationClick(#NonNull Location location) {
Toast.makeText(this, "Current location:\n" + location, Toast.LENGTH_LONG).show();
my Question is how to use the latitude and longitude of this method , i mean how to get the latitude and longitude of my location because it is correct i i will need it to calculate the distance between me and other places .
To correctly use location in your app, you need to handle asking user permission to turn on location in settings (in case it is turned off) and then follow the steps in the documentation:
https://developer.android.com/training/location/retrieve-current.html
To answer your question exactly, did you try location.getLatitude() and location.getLongitude()?

AsyncTask execute crashes app when perform it

The user must add a marker by tapping the map. My goal is to send the Name, Category, Latitude and Longitude to a SQL database. I followed this issue: How can you pass multiple primitive parameters to AsyncTask?,
but the app crashes when I hit the button which calls the shopReg.
Also, maybe there is something wrong with the communication between my app and the WampServer. I wonder if the connection URL is correct. I found on the Internet that the default WAMP localhost IP is 10.0.2.2. See the code:
AddShopActivity.java
public class AddShopActivity extends MainScreen implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
Spinner spinner;
ArrayAdapter<CharSequence> adapter;
GoogleMap mGoogleMap;
GoogleApiClient mGoogleApiClient;
String Name, Category;
Double Latitude, Longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_shop);
initMap();
spinner = (Spinner) findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this, R.array.eidoskatastimatos, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
private void initMap() {
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
}
LocationRequest mLocationsRequest;
#Override
public void onConnected(Bundle bundle) {
mLocationsRequest = LocationRequest.create();
mLocationsRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationsRequest.setInterval(5000);
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationsRequest, this);
mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
EditText shop_name = (EditText)findViewById(R.id.editName);
Spinner shop_category = (Spinner)findViewById(R.id.spinner);
MarkerOptions marker = new MarkerOptions()
.position(new LatLng(latLng.latitude, latLng.longitude))
.draggable(true)
.title(shop_name.getText().toString())
.snippet(shop_category.getSelectedItem().toString());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latLng, 16);
mGoogleMap.animateCamera(update);
mGoogleMap.clear();
mGoogleMap.addMarker(marker);
Name = shop_name.getText().toString();
Category = shop_category.getSelectedItem().toString();
Latitude = latLng.latitude;
Longitude = latLng.longitude;
}
});
}
public void shopReg(View view)
{
String method = "save";
BackgroundTask backgroundTask = new BackgroundTask(this);
new BackgroundTask(method,Name,Category,Latitude,Longitude).execute();
finish();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
if (location == null){
Toast.makeText(this, "Can't get current location", Toast.LENGTH_LONG).show();
} else {
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, 16);
mGoogleMap.animateCamera(update);
}
}
}
BackgroundTask.java
public class BackgroundTask extends AsyncTask<String,Void,String> {
String Name, Category;
Double Latitude, Longitude;
BackgroundTask(String method, String Name, String Category, Double Latitude, Double Longitude) {
this.Name = Name;
this.Category = Category;
this.Latitude = Latitude;
this.Longitude = Longitude;
}
Context ctx;
BackgroundTask(Context ctx){
this.ctx = ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://10.0.2.2/shop/register.php";
String method = params[0];
if(method.equals("save"))
{
String Name = params[1];
String Category = params[2];
Double Latitude = Double.parseDouble(params[3]);
Double Longitude = Double.parseDouble(params[4]);
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("Name", "UTF-8") +"="+URLEncoder.encode(Name,"UTF-8")+"&"+
URLEncoder.encode("Category", "UTF-8") +"="+URLEncoder.encode(Category,"UTF-8")+"&"+
URLEncoder.encode("Latitude", "UTF-8") +"="+URLEncoder.encode(String.valueOf(Latitude),"UTF-8")+"&"+
URLEncoder.encode("Longitude", "UTF-8") +"="+URLEncoder.encode(String.valueOf(Longitude),"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Το κατάστημα προστέθηκε!";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
}
}
register.php
<?php
require"init.php";
$Name=$_POST["Name"];
$Category=$_POST["Category"];
$Latitude=$_POST["Latitude"];
$Longitude=$_POST["Longitude "];
$sql_query="insert into shop_info
values('$Name','$Category','$Latitude','$Longidude');";
?>
init.php
<?php
$db_name="shops";
$mysql_user="root";
$mysql_pass="";
$server_name="localhost";
?>
Context - ctx is null and will result in crash
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx,result,Toast.LENGTH_LONG).show();
}
backgroundTask is not used after initialisation.
BackgroundTask backgroundTask = new BackgroundTask(this);
For below async task which you execute, context - ctx is null.
new BackgroundTask(method,Name,Category,Latitude,Longitude).execute();
Please add one more parameter and pass context as well like below:
new BackgroundTask(ctx, method,Name,Category,Latitude,Longitude).execute();
Actually it was very obvious, but I didn't see it. The String method = "save";accepts only String type and I was trying to pass double with Latitude and Longitude. So I just turned doubles to Strings using;
Latitude = String.valueOf(latLng.latitude);
Longitude = String.valueOf(latLng.longitude);
Thanks for help!

Android map Multiple markers on click button after Json parsing

I want to plot the coordinates of latitude and longitude values I get here
String longitude = c.getString("long");
String latitude = c.getString("lat");
and attach it on button.
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), g.getLatitude() + " " + g.getLongitude(), Toast.LENGTH_SHORT).show();
}
});
Here is the complete code: https://pastebin.com/MCNj2LLS
public class MapFragment extends Fragment implements OnMapReadyCallback {
SnailTrail st;
GoogleMap map, map2;
PopupWindow popupWindow;
LocationManager mLocationManager;
Button b;
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "http://mark.journeytech.com.ph/json/2.json";
ArrayList<HashMap<String, String>> contactList;
SnailTrail g = new SnailTrail();
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_contact_us, container, false);
// new GetCoordinates(getActivity()).getCoordinates();
b = (Button) v.findViewById(R.id.b1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), g.getLatitude() + " " + g.getLongitude(), Toast.LENGTH_SHORT).show();
}
});
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map1);
mapFragment.getMapAsync(this);
new GetVehicles().execute();
}
private class GetVehicles extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("snailtrail_data");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String account = c.getString("account");
String trxdate = c.getString("trxdate");
String trxtime = c.getString("trxtime");
String longitude = c.getString("long");
String latitude = c.getString("lat");
String location = c.getString("location");
String direction = c.getString("direction");
String compass = c.getString("compass");
String id = c.getString("id");
String remarks = c.getString("remarks");
String status = c.getString("status");
String kmrun = c.getString("kmrun");
String speed = c.getString("speed");
String totalkm = c.getString("totalkm");
String engine = c.getString("engine");
String plateno = c.getString("plateno");
/*// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("account", account);
contact.put("trxdate", trxdate);
contact.put("trxtime", trxtime);
contact.put("longitude", longitude);
contact.put("latitude", latitude);
contact.put("location", location);
contact.put("direction", direction);
contact.put("compass", compass);
contact.put("id", id);
contact.put("remarks", remarks);
contact.put("status", status);
contact.put("kmrun", kmrun);
contact.put("speed", speed);
contact.put("totalkm", totalkm);
contact.put("engine", engine);
contact.put("plateno", plateno);
// adding contact to contact list
contactList.add(contact);*/
}
} catch (final JSONException e) {
}
} else {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
MarkerOptions option = new MarkerOptions();
g.setLocation("3rd Floor Sky Freight Building\n" +
"Ninoy Aquino Avenue,Paranque City\n" +
"1704 Philippines\n" +
"Tel. No: +639.2.852-8410 \n" +
"Fax. No: +639.2.851-8745 ");
map = googleMap;
String lat1 = "-34.8799074";
String long1 = "174.7565664";
double latitude = Double.parseDouble(lat1);
double longitude = Double.parseDouble(long1);
/* String[] latlong = "-34.8799074,174.7565664".split(",");
double latitude = Double.parseDouble(latlong[0]);
double longitude = Double.parseDouble(latlong[1]);*/
LatLng pp = new LatLng(latitude, longitude);
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(LAYOUT_INFLATER_SERVICE);
View myContentView = inflater.inflate(R.layout.marker_popup, null);
TextView loc = ((TextView) myContentView
.findViewById(R.id.textView2));
loc.setText(marker.getTitle());
TextView plate_num = ((TextView) myContentView
.findViewById(R.id.textView4));
plate_num.setText(marker.getSnippet());
/* Button btnDismiss = (Button) myContentView.findViewById(R.id.dismissbtn);
btnDismiss.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
popupWindow.dismiss();
}
});*/
return myContentView;
}
});
// map.moveCamera(CameraUpdateFactory.newLatLngZoom(pp, 8));
map.addMarker(new MarkerOptions()
.position(pp)
.title(g.getLocation())
.snippet("SkyFreight")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)));
map.addMarker(new MarkerOptions()
.title("India")
.snippet("New Delhi")
.position(new LatLng(20.59, 78.96))
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));
map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
Toast.makeText(getActivity(), "TOOOAST", Toast.LENGTH_LONG);
}
});
};
}`

How can I send current location from one activity to another?

I am using map to get current location and now I want to send my current location to another activity which has form to input all the data.
I am confused about which variables and methods I should use to send the location data.
ChooseFromMapActivity
This is the activity where I am getting my current location. And now on Click of useLocation layout I want to send this location to the edit text of another activity i.e GoSendActivity.
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
}
}
GoSendActivity
This is my GoSendActivity which has edit text view. I want to get the current location on edttxt_from text view.
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);
setUI();
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
}
#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);
}
});
}
}
Location class
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;}
}
How can I achieve this?? Please help..
try this :
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);
}
});
And inside onCreate of GoSendActivity,get latitude and longitude like this :
Bundle extras = getIntent().getExtras();
if (extras != null) {
double latitude = extras.getDouble("Latitude");
double longitude = extras.getDouble("Longitude");
}
Now you can set latitude and longitude to your edittext edittext.setText(String.valueOf(latitude));
Apart from passing the data to the next activity using intents, you can also use shared preferences, TinyDB lib achieves great results for caching data. Yoou will need to sync this in your gradle file :
compile 'com.mukesh:tinydb:1.0.1'
then in your onCreate in each activity you will be using the same, initialize the tinyDB by passing application context
TinyDB tinyDB = new TinyDB(getApplicationContext());
With that you can store and retrieve any data within the app using a key-value pair,example to store your coordinates, just call :
tinyDB.putDouble("latitude",latitude);
tinyDB.putDouble("longitude",longitude);
And you can retrieve the data this way:
double latitude = tinyDB.getDouble("latitude");
double longitude = tinyDB.getDouble("longitude");
This class supports all data formats, from Strings,Double,Float and even objects such as ararayLists. Would highly recommend you to try it out.
Make this class as serialisable and put it into intent using bundle.putSerializable("myclaa",location).
Class Location implements Seraializable{
}

Passing object list to another activity

In my code I am creating an area object by placing markers on map and taking its values from user then storing it in a list. Then I used parcelableArrayList to pass this list to another activity. What I want is that user presses displayArea button only then this activity is launched and list is displayed in AllAreas activty. But my app crashes whenever I click that button
Code for mapActivity
public class MainActivity extends
FragmentActivity implements View.OnClickListener,MapDropdown.DialogListener {
public static final String mapLongitude="longitude";
public static final String mapLatitude="latitude";
FragmentManager fm = getSupportFragmentManager();
Button displayareas;
Switch deleteareas;
private boolean del = false;
private int set = 0;
public ArrayList<Area> areas;
private GoogleMap newmap; // Might be null if Google Play services APK is not available.
LatLng m;
float radius;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayareas = (Button) findViewById(R.id.display);
displayareas.setOnClickListener(this);
deleteareas = (Switch) findViewById(R.id.delete);
areas = new ArrayList<Area>();
deleteareas.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
del = true;
Toast.makeText(getApplicationContext(), "Deleting enabled", Toast.LENGTH_LONG).show();
} else {
del = false;
Toast.makeText(getApplicationContext(), "Deleting disabled", Toast.LENGTH_LONG).show();
}
}
});
Log.d("Map","MapCreated");
setUpMapIfNeeded();
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.display) {
Intent intent = new Intent(getApplicationContext(),AllAreas.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("data", areas);
intent.putExtras(bundle);
startActivity(intent);
}
}
#Override
protected void onResume() {
super.onResume();
//setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (newmap == null) {
// Try to obtain the map from the SupportMapFragment.
newmap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (newmap != null) {
setUpMap();
Log.d("MAPS","Map working");
}
else Log.d("MAPS","not working");
}
}
private void setUpMap() {
newmap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));
// Enable MyLocation Layer of Google Map
newmap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
// set map type
newmap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
double latitude = myLocation.getLatitude();
// Get longitude of the current location
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
newmap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
newmap.animateCamera(CameraUpdateFactory.zoomTo(20));
newmap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My location"));
Log.d("LATITUDE",String.valueOf(latitude));
Log.d("LONGITUDE",String.valueOf(longitude));
GoogleMap.OnMarkerClickListener listener = new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(final Marker marker) {
if(del == false){
m=marker.getPosition();
MapDropdown dFragment = new MapDropdown();
// Show DialogFragment
dFragment.show(fm, "Dialog Fragment");}
else if(del == true){
marker.remove();
}
return true;
}
};
newmap.setOnMarkerClickListener(listener);
newmap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
// This will be displayed on taping the marker
markerOptions.title(latLng.latitude + " : " + latLng.longitude);
// Animating to the touched position
newmap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
// Placing a marker on the touched position
Marker mmarker = newmap.addMarker(markerOptions);
m = latLng;
Log.d("ADDED LATITUDE",String.valueOf(latLng.latitude));
Log.d("ADDED LONGITUDE",String.valueOf(latLng.longitude));
Toast.makeText(getApplicationContext(),"Block area updated",Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onDialogPositiveClick(DialogFragment dialog , String s, String n){
Log.d("Button","positive");
Log.d("Name",n);
Log.d("Radius",s);
Log.d("On press LATITUDE",String.valueOf(m.latitude));
Log.d("On press LONGITUDE",String.valueOf(m.longitude));
Area newarea = new Area(n,m.latitude,m.longitude,Float.valueOf(s));
Log.d("object",newarea.getId());
Log.d("object",newarea.getName());
areas.add(newarea);
areas.get(0);
Log.d("areas",areas.get(0).getName());
}
#Override
public void onDialogNegativeClick(DialogFragment dialog){
Log.d("Button","negative");
}
}
Part of mainActivity.java adding to list is
#Override
public void onDialogPositiveClick(DialogFragment dialog , String s,
String n){
Log.d("Button","positive");
//areas is list name
//m is current marker
Area newarea = new Area(n,m.latitude,m.longitude,Float.valueOf(s));
areas.add(newarea);
}
And of passing list in mainactivity is
public void onClick(View v) {
//id of button that will launch Allareas activity
if (v.getId() == R.id.display) {
Intent intent = new Intent(getApplicationContext(),AllAreas.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("data", areas);
intent.putExtras(bundle);
startActivity(intent);
}
}
for AllAreas class
public class AllAreas extends ActionBarActivity {
//initial layout
private Area a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.areas);
Bundle bundle = getIntent().getExtras();
ArrayList<Area> arealist = bundle.getParcelableArrayList("mylist");
if (arealist.isEmpty()) {
Log.d("area list lala", "is empty");
}
else {
for (int i = 0; i < arealist.size(); i++) {
a = arealist.get(0);
Log.d("area list lala", a.getName());
}
}
}
}
You are getting it with wrong key.you used the key "data" for putting it into bundle and trying to get it by the key "mylist"
bundle.putParcelableArrayList("data", areas);
change the line
ArrayList<Area> arealist = bundle.getParcelableArrayList("mylist");
to
ArrayList<Area> arealist = bundle.getParcelableArrayList("data");
let me know if it works.

Categories