my findViewByID is thowing error? - android

My findViewById is throwing error saying it has not been defined and it asks me to create a function. What should I do?
public void geoLocate(View v) throws IOException {
hideSoftKeyboard(v);
EditText et = (EditText) findViewById(R.id.editText1);
String location = et.getText().toString();
Geocoder gc = new Geocoder(context);
List<Address> list = gc.getFromLocationName(location, 1);
Address add = list.get(0);
String locality = add.getLocality();
Toast.makeText(context, locality, Toast.LENGTH_LONG).show();
double lat = add.getLatitude();
double lng = add.getLatitude();
gotoLocation(lat, lng, DEFAULTZOOM);
MarkerOptions markerOptions = new MarkerOptions().title(locality).position(new LatLng(lat,lng));
mMap.addMarker(markerOptions);
}

In your function find id like this
EditText et = (EditText) v.findViewById(R.id.editText1);
You havve to use the View variable passed in the method to find id

Related

how to get city name using latitude and longitude in android

I am trying to get city in TextView using latitude and longitude. I am getting IndexOutOfBoundsException.
AndroidGPSTrackingActivity.java
import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import static com.example.khaledsb.location.R.id.lng;
import static java.util.Locale.*;
public class AndroidGPSTrackingActivity extends Activity {
public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
double earthRadius = 6371000; //meters
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
float dist = (float) (earthRadius * c);
return dist;
}
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
final TextView lat =(TextView) findViewById(R.id.lat);
final TextView lon = (TextView) findViewById(R.id.longt);
final TextView addr = (TextView) findViewById(R.id.address);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
double Distance;
Distance = distFrom((float) 36.5925907, 2.9051544f, 36.5805505f, 2.914749f);
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Geocoder geocoder = new Geocoder(AndroidGPSTrackingActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
addr.setText(strReturnedAddress.toString());
}
else{
addr.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
addr.setText("Can not get Address!");
}
// \n is for new line
//Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude+" " +
//" diastance "+Distance, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
}
I am getting the following error in logcat :
5-09 11:17:21.858 4501-4501/com.example.khaledsb.location E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at com.example.khaledsb.location.AndroidGPSTrackingActivity$1.onClick(AndroidGPSTrackingActivity.java:79)
at android.view.View.performClick(View.java:4204)
at android.view.View$PerformClick.run(View.java:17355)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Try
Geocoder gcd = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = gcd.getFromLocation(lat, lng, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
String locality = addresses.get(0).getLocality();
}
Use below code to get city name
Geocoder geocoder = new Geocoder(this);
try {
List<Address>addresses = geocoder.getFromLocation(latitude,longitue,1);
if (geocoder.isPresent()) {
StringBuilder stringBuilder = new StringBuilder();
if (addresses.size()>0) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String name = returnAddress.getFeatureName();
String subLocality = returnAddress.getSubLocality();
String country = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
String state = returnAddress.getAdminArea();
}
} else {
}
} catch (IOException e) {
e.printStackTrace();
}
Try this code, Hope it helps..
private static String getRegionName(double lati, double longi) {
String regioName = "";
Geocoder gcd = new Geocoder(AppInstance, Locale.getDefault());
try {
List<Address> addresses = gcd.getFromLocation(lati, longi, 1);
if (addresses.size() > 0) {
regioName = addresses.get(0).getLocality();
}
} catch (Exception e) {
e.printStackTrace();
}
return regioName;
}
Try to use following code to get complete address,
//Get address from Google api
//Log.e("Else","else");
try {
JSONObject jsonObj = getJSONfromURL("http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + ","
+ longitude + "&sensor=true");
String Status = jsonObj.getString("status");
if (Status.equalsIgnoreCase("OK")) {
JSONArray Results = jsonObj.getJSONArray("results");
JSONObject location = Results.getJSONObject(0);
finalAddress = location.getString("formatted_address");
}
} catch (Exception e) {
e.printStackTrace();
}
instead of,
geocoder.getFromLocation(latitude, longitude, 1);
For Avoid ArrayIndexOutOfBound you could add if condition like below:
if (addresses != null && addresses.size() > 0) {
String locality = addresses.get(0).getLocality();
}
but, as I saw your code you are trying to get address using GeoCoder inside button click, So avoid this because it is a network call. You should not perform network call in main thread, it could block UI Or Cause ANR. You should use AsyncTask/Thread for network operation to avoid blocking Of UI.
Also make sure you have added
INTERNET_PERMISSION
in your manifest file.
Hope It help you !
Error states that the Array list is empty so make sure you initialize the list and check if it contains any data.
try this code:
List<Address> addresses = new List<Address>;
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if(addresses != null) {
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName();
}
This should give you required info.
Fetching location address from latlong co-ordinates fetched from Location object.
#Override
public void onLocationChanged(Location location) {
String longitude = "Longitude: " + location.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + location.getLatitude();
Log.v(TAG, latitude);
String address = null;
String knownName = null;
String city = null;
String state = null;
String country = null;
String postalCode = null;
Geocoder gcd = new Geocoder(MainActivity.this.getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
address = addresses.get(0).getAddressLine(0);
if (addresses.get(0).getFeatureName() != address) {
knownName = addresses.get(0).getFeatureName();
}
city = addresses.get(0).getLocality();
state = addresses.get(0).getAdminArea();
country = addresses.get(0).getCountryName();
postalCode = addresses.get(0).getPostalCode();
} catch (IOException e) {
e.printStackTrace();
}
String foundAddress = knownName + ", " + address + ", " + city + ", " + state + ", " + country + "- " + postalCode + "\n";
myLocation.setText(foundAddress);
storeLocation();
}

Options to save data from a map marker to be used in a different activity android studio

I am looking advice on options i have to save data from markers and searches from placepicker on google maps.
Ive looked into shared preferences and tried the code out but not working.
I need to take address data from a place picker search and save it so that a history activity can generate a list.
is there any option that place picker saves searches?
im using android studio
This is an example of my place picker
Place place = PlacePicker.getPlace(data, this);
LatLng placeLatLng = place.getLatLng(); // gett lat lng from place
double placeLat = placeLatLng.latitude;
double placeLong = placeLatLng.longitude;
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
Marker destination = mMap.addMarker(new MarkerOptions().position(new LatLng(placeLat, placeLong)).title("This is your destination"));
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Current Location
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location myLocation = locationManager.getLastKnownLocation(provider);
//Current Location LatLong
final double currentLat = myLocation.getLatitude();
final double currentLng = myLocation.getLongitude();
List<CharSequence> listItems = new ArrayList<>();
//Directions From Current Location To Destination
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?" + "saddr=" + currentLat + "," + currentLng + "&daddr=" + placeLat + "," + placeLong));
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
listItems.add(name);
listItems.add(address);
startActivity(intent);
}
}
public void saveInfo(View v){
SharedPreferences sharedPreferences = getSharedPreferences("Place Deatils", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
}
get location address using Geocoder and store the information in SharedPreferences
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latt,lang, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String area = addresses.get(0).getSubLocality();
String dist= addresses.get(0).getSubAdminArea();
String city = addresses.get(0).getLocality();
mapMarker.setTitle(area+","+dist+","+city);
} catch (IOException e) {
e.printStackTrace();
}
check this SharedPreferences

getLastKnownLocation can't get new data by location.setLatitude/setLongitude?

My full code
https://gist.github.com/anonymous/6dd0f33270cc4f46149e
In line 110~131 I want to change the location, it does work, the mapview will change
private class MapClickedListener implements OnClickListener {
#Override
public void onClick (View v) {
String lng = "121.558561";
lng = edt_lng.getText().toString().trim();
String lat = "25.031005";
lat = edt_lat.getText().toString().trim();
if(lng.equals("")||lat.equals("")){
Toast.makeText(getApplicationContext(), "input again!", Toast.LENGTH_LONG).show();
location = locManager.getLastKnownLocation(bestProvider);
updateToNewLocation(location);
}else{
Location location = new Location(LocationManager.NETWORK_PROVIDER);
location.setLongitude(Double.parseDouble(lng));
location.setLatitude(Double.parseDouble(lat));
updateToNewLocation(location);
}
}
}
On line 133~148, I want to know distance between location and a point I set
private Button.OnClickListener EQ = new Button.OnClickListener(){
#Override
public void onClick (View v) {
eqlocation.setLongitude(120.82);
eqlocation.setLatitude(23.85);
location = locManager.getLastKnownLocation(bestProvider);
float[] result = new float[5];
Location.distanceBetween(location.getLatitude(), location.getLongitude(), eqlocation.getLatitude(), eqlocation.getLongitude(), result);
BigDecimal bd = new BigDecimal(result[0]);
BigDecimal rounded = bd.setScale(2, RoundingMode.HALF_UP);
double dis = rounded.doubleValue();
String dist = String.valueOf(dis/1000);
Toast.makeText(getApplicationContext(), "distance: " + dist + "km", Toast.LENGTH_LONG).show();
}
};
But the result is wrong when I change the location by line 110~131's code.
What should I do to get the right result?
have you tried distanceTo() and checked if you get any better results?, I ususally use distanceTo() with good results.

Android:how to get lat and long into my adapter

I want to get latitude and longitude of a place when i enter my address. i have one activity with programatically created custom dailog, this has the address feilds, when i type my address i need to get the latitude and logitude. below is my adapter code where i am trying to get the lat and lng details
public void performAction(View v, final Activity activity) {
Context myContext = v.getContext();
PopUpMenu popUpMenu = (PopUpMenu) v.getTag();
String result = popUpMenu.getMenuName();
if (result != null
&& result.equalsIgnoreCase(myContext.getResources().getString(
R.string.addnewplace))) {
AttractionData attractionData = new AttractionData();
createDiloag(attractionData,activity.getResources().getString(R.string.addnewplace));
setgpsLocation();
}
public void setgpsLocation() {
final EditText address = new EditText(this.activity);
String addressText = address.getText().toString();
try {
final StringBuffer myAddress = new StringBuffer();
if(addressText!=null&&!addressText.trim().equals("")){
myAddress.append(addressText);
}
Geocoder gcd = new Geocoder(parentActivity, Locale.getDefault());
List<Address> addresses = gcd.getFromLocationName(addressText, 5);
if (addressList != null && addressList.size() > 0) {
Address location = addressList.get(0);
location.getLatitude();
location.getLongitude();
// int lat = (int) (addressList.get(0).getLatitude() * 1e6);
// int lng = (int) (addressList.get(0).getLongitude() * 1e6);
AttractionData attractionData = new AttractionData();
attractionData.setLatitude(location.getLatitude());
attractionData.setLongitude( location.getLongitude());
} catch (Exception e) {
Log.e(TAG, "Error", e);
}
}
I am unable to get the lat lng details, Any help is appreciated.
I believe the problem is with the following lines:
final EditText address = new EditText(this.activity);
String addressText = address.getText().toString();
You addressText will be an empty string every time because you're creating a new EditText instead of using the one from the existing activity.
Try to replace it with:
final EditText address = (EditText)this.activity.findViewById(R.id.your_edit_text_id);
and replace your_edit_text_id with the id in your layout file.
If you created your view programmatically then provide a getter for it.
In your activity:
public EditText getAddressEditText() {
return this.mAddressEditText;
}
And then use it like this:
final EditText address = this.activity.getAddressEditText();

Using Geocoder to show user's location Address

I have this method to show the user's latitude and longitude on a map activity:
public void animateMap(Location location){
double lat = location.getLatitude();
double lng = location.getLongitude();
Toast.makeText(MyMapActivity.this,
"Sie sind an\n" + lat + "\n" + lng, Toast.LENGTH_SHORT)
.show();
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapController.animateTo(point, new Message());
mapOverlay.setPointToDraw(point);
}
How to implement the Geocoder on my method? So the Toast will display the location's address instead of the coordinates
you use
Geocoder myLocation = new Geocoder(context, Locale.ENGLISH);
List<Address> myList= myLocation.getFromLocation(lat, lng, 1);
Address add = myList.get(0);
String addressString = add.getAddressLine(0);
String country = add.getCountryName();
String city = add.getLocality();
The easiest implementation is by using the geocoder class:
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
geocoder.getFromLocation(lat, lng, 1);
List<Address> ls=new ArrayList();
ls= geocoder.getFromLocation(lat, lng, 1);
String myLocation = ls.get(0).getSubAdminArea();
You can check all the information returned by this class and choose which one fits you most. It contains from country names to landmarks name, neighbors postalcodes... almost anything you may need.
But keep in mind, if Google has no info about this location will return a null string!
So for you exapmple should be something like that:
public void animateMap(Location location){
double lat = location.getLatitude();
double lng = location.getLongitude();
String myLocation;
try{
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
geocoder.getFromLocation(lat, lng, 1);
List<Address> ls=new ArrayList();
ls= geocoder.getFromLocation(lat, lng, 1);
myLocation = ls.get(0).getSubAdminArea();
}catch(Exception e){
myLocation="Sorry, we have no information about this location";
}
Toast.makeText(MyMapActivity.this,
"Sie sind an\n" + myLocation , Toast.LENGTH_SHORT)
.show();
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapController.animateTo(point, new Message());
mapOverlay.setPointToDraw(point);
}
Get the list of Addresses at your location from Geocoder and check for a null or empty result:
Geocoder geocoder = new Geocoder(getApplicationContext,Locale.getDefault());
List<Address> address = geocoder.getFromLocation(lat, long, 1);
String myLocation = "";
if(address != null && !address.isEmpty())
{
myLocation = address.get(0).getSubAdminArea();
}

Categories

Resources