i'm new to android ,I am try to get my current location address.my code is working but value of the text box is refreshing time to time. how i stop it...
this is my code..
public class MylocMainActivity extends Activity {
String lat="", lon="";
String ret= "" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myloc_main);
//button click done
Button btnLocation = (Button)findViewById(R.id.btn_done);
btnLocation.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
location();
Log.d("OnClick","Passed");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.myloc_main, menu);
return true;
}
public void location()
{
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) MylocMainActivity.this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
lat = Double.toString(location.getLatitude());
lon = Double.toString(location.getLongitude());
TextView tv = (TextView) findViewById(R.id.tv_location);
tv.setText("Your Location is:" + lat + "--" + lon);
tv.setText(GetAddress(lat, lon));
Intent i = new Intent(MylocMainActivity.this,MainActivity.class);
i.putExtra("clist",ret.toString());
startActivity(i);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
// get the address
public String GetAddress(String lat, String lon)
{
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(lat), Double.parseDouble(lon), 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");
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ret = "Can't get Address!";
}
return ret;
}
}
........Main Activity class.............
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent startbuttonintent = getIntent();
String conlist = null;
conlist = startbuttonintent.getStringExtra("clist");
TextView name = (TextView) findViewById(R.id.family_Text);
name.setText(conlist);
Button btn = (Button)findViewById(R.id.btn_location);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,MylocMainActivity.class);
startActivity(i);
// TODO Auto-generated method stub
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Each time the location changes it changes the content of the textview although the content might not have actually changed due to number precision.
Try this or something similar with setting the textview:
public void onLocationChanged(Location location)
{
// Called when a new location is found by the network location provider.
lat = Double.toString(location.getLatitude());
lon = Double.toString(location.getLongitude());
TextView tv = (TextView) findViewById(R.id.tv_location);
if(!tv.getText().equals(GetAddress(lat, lon)))
{
tv.setText("Your Location is:" + lat + "--" + lon);
tv.setText(GetAddress(lat, lon));
}
Intent i = new Intent(MylocMainActivity.this,MainActivity.class);
i.putExtra("clist",ret.toString());
startActivity(i);
}
you could store the Location from onLocationChanged in an Location value (mLocation).
every time the location changes you check
if (mLocation != null) { // do something }
Related
Hi Guys an working on map activity. I would like to get my exact location address i.e. name and save it and later retrieve the information.At the moment am getting the coordinates and the city name anyone with any idea please assist.
public class GetCurrentLocation extends Activity
implements OnClickListener {
private LocationManager locationMangaer = null;
private LocationListener locationListener = null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb = null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_current_location);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo
.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to" +
" see the changes in coordinates." + "\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----Method to Check GPS is enable or disable ----- */
private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext()
.getContentResolver();
boolean gpsStatus = Settings.Secure
.isLocationProviderEnabled(contentResolver,
LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(), "Location changed : Lat: " +
loc.getLatitude() + " Lng: " + loc.getLongitude(),
Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " + loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(),
Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc
.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude +
"\n\nMy Currrent City is: " + cityName;
editLocation.setText(s);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
Store your Lat / Long values:
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("Latitude", Latitude).commit();
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("Longitude", Longitude).commit();
Then retrieve it using:
PreferenceManager.getDefaultSharedPreferences(context).getString("Latitude", "No Latitude Value Stored");
PreferenceManager.getDefaultSharedPreferences(context).getString("Longitude", "No Longitude Value Stored");
Use Shared preferences to store your data. Create an array list, update the co-ordinates into it and save it. Here's the Shared preferences documentation for reference. If you need code snippets or an explanation of anything, feel free to ask.
UPDATE
Set<String> Lats = new HashSet<String>();
Set<String> Longs = new HashSet<String>();
Lats.add(Latitude);
Longs.add(Longitude);
Context C = getApplicationContext();
SharedPreferences SP = C.getSharedPreferences("My_Prefs",MODE_PRIVATE);
SharedPreferences.Editor E = SP.edit();
E.clear();
E.putStringSet("Lats",Lats);
E.putStringSet("Longs",Longs);
E.commit();
This is for when you save it initially. When you've already saved one or more pairs, retrieve older values then add new ones and then save it:
Context C = getApplicationContext();
SharedPreferences SP = C.getSharedPreferences("My_Prefs",MODE_PRIVATE);
Set<String> Lats = SP.getStringSet("Lats",null);
Set<String> Longs = SP.getStringSet("Longs",null);
Hope I helped :D
I tracked the gps with the following code, But How to get notified If the gps tracker reaches that location ...
Capture.java
public class Capture extends Activity implements LocationListener{
Button btnNWShowLocation,btnsave;
TextView etlat,etlng,alreadyposted,t3,t4,t5;
EditText etplace;
String state1,state2;
protected String v1, v2, v3;
JSONParser jsonParser = new JSONParser();
JSONArray jsonarray;
ArrayList<HashMap<String,String>> arraylist;
JSONObject jsonobject;
String TAG_SUCCESS="success";
double latitude,longitude;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
double lat1,lng1;
String lat2,lng2;
String providernet,speed1,accuracy1;
float speed,accuracy;
Location location;
public LocationManager locationManager;
String provider;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
btnsave = (Button) findViewById(R.id.buttonsave);
etlat=(TextView)findViewById(R.id.textlatitude);
etlng=(TextView)findViewById(R.id.textlongitude);
alreadyposted=(TextView)findViewById(R.id.alreadyposted);
etplace=(EditText)findViewById(R.id.editplace);
t3=(TextView)findViewById(R.id.provider);
t4=(TextView)findViewById(R.id.speed);
t5=(TextView)findViewById(R.id.accuracyset);
alreadyposted.setVisibility(View.INVISIBLE);
locationManager = (LocationManager)Capture.this.getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(false);
provider = locationManager.getBestProvider(criteria,false);
Location location = locationManager.getLastKnownLocation(provider);
//Initialize the location fields
if (location!= null){
onLocationChanged(location);
latitude = location.getLatitude();
longitude =location.getLongitude();
} else {
Toast.makeText(getApplicationContext(), "Not available", Toast.LENGTH_SHORT).show();
}
btnsave.setOnClickListener(new View.OnClickListener() {
protected ArrayList<NameValuePair> parameters;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
parameters = new ArrayList<NameValuePair>();
v1 = etlat.getText().toString();
v2 = etlng.getText().toString();
v3 = etplace.getText().toString();
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://placementreadyguarantee.com/android/gps_tracking/Jsoncheckcapture.php?latitude="+v1+"&longitude="+v2);
try {
// Locate the array name in JSON
int success = jsonobject.getInt(TAG_SUCCESS);
if(success==1){
alreadyposted.setVisibility(View.VISIBLE);
}
else{
NameValuePair latitudejson = new BasicNameValuePair("latitude",v1);
NameValuePair longitudejson = new BasicNameValuePair("longitude",v2);
NameValuePair placejson = new BasicNameValuePair("place",v3);
parameters.add(latitudejson);
parameters.add(longitudejson);
parameters.add(placejson);
try {
JSONObject json =jsonParser.makeHttpRequest("http://placementreadyguarantee.com/android/gps_tracking/captureupload.php?latitude="
+URLEncoder.encode(v1,"UTF-8")
+"&longitude="
+URLEncoder.encode(v2,"UTF-8")
+"&place="
+URLEncoder.encode(v3,"UTF-8"),
"POST",parameters);
} catch (UnsupportedEncodingException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
alreadyposted.setVisibility(View.INVISIBLE);
}
}catch(Exception e){
e.printStackTrace();
}
}
});
}
/*Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider,400,1,this);
//getting gps
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(isGPSEnabled){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,400,1,this);
}
else if(isNetworkEnabled){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,400,1,this);
}
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause(){
super.onPause();
//locationManager.removeUpdates(this);
locationManager.requestLocationUpdates(provider,400,1,this);
//getting gps
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(isGPSEnabled){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,400,1,this);
}
else if(isNetworkEnabled){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,400,1,this);
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
lat1=location.getLatitude();
lng1=location.getLongitude();
providernet=location.getProvider();
speed=location.getSpeed();
accuracy=location.getAccuracy();
accuracy1=Float.toString(accuracy);
speed1=Float.toString(speed);
lat2=Double.toString(lat1);
lng2=Double.toString(lng1);
etlat.setText(lat2);
etlng.setText(lng2);
t3.setText(providernet);
t4.setText(speed1);
t5.setText(accuracy1);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
In this i used json to store the latitude and longitude in mysql database(which is in my server space).
By clicking on button it saved current latitude and longitude in database .
Now i need to Do more , with this if the device reached that already saved place or around 10 meters or 20 meteers it send notification , or storing in database like that anything i need to do .
Thanks in advance . :)
I made an application in android. I have to find current location of user i.e. City name
I use the below code, it could generate latitude & longitude but did not get name of the city.
My code is:
public class GetCurrentLocation extends Activity implements OnClickListener {
private LocationManager locationMangaer=null;
private LocationListener locationListener=null;
private Button btnGetLocation = null;
private EditText editLocation = null;
private ProgressBar pb =null;
private static final String TAG = "Debug";
private Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//if you want to lock screen for always Portrait mode
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
editLocation = (EditText) findViewById(R.id.editTextLocation);
btnGetLocation = (Button) findViewById(R.id.btnLocation);
btnGetLocation.setOnClickListener(this);
locationMangaer = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
flag = displayGpsStatus();
if (flag) {
Log.v(TAG, "onClick");
editLocation.setText("Please!! move your device to see the changes in coordinates."+"\nWait..");
pb.setVisibility(View.VISIBLE);
locationListener = new MyLocationListener();
locationMangaer.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10,
locationListener);
} else {
alertbox("Gps Status!!", "Your GPS is: OFF");
}
}
/*----------Method to Check GPS is enable or disable ------------- */
private Boolean displayGpsStatus() {
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(
contentResolver, LocationManager.GPS_PROVIDER);
if (gpsStatus) {
return true;
} else {
return false;
}
}
/*----------Method to create an AlertBox ------------- */
protected void alertbox(String title, String mymessage) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your Device's GPS is Disable")
.setCancelable(false)
.setTitle("** Gps Status **")
.setPositiveButton("Gps On",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
// AlertBoxAdvance.this.finish();
Intent myIntent = new Intent(
Settings.ACTION_SECURITY_SETTINGS);
startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
editLocation.setText("");
pb.setVisibility(View.INVISIBLE);
Toast.makeText(getBaseContext(),"Location changed : Lat: " + loc.getLatitude()
+ " Lng: " + loc.getLongitude(),Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " +loc.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " +loc.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
String cityName=null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName=addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
String s = longitude+"\n"+latitude +"\n\nMy Currrent City is: "+cityName;
editLocation.setText(s);
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
}
How can I get name of the city i.e Current location of user ( like delhi, mumbai etc) ?
Try this way:
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");
strReturnedAddress.append(returnedAddress.getLocality()).append("\n");
strReturnedAddress.append(areturnedAddress.getPostalCode()).append("\n");
strReturnedAddress.append(returnedAddress.getCountryName()).append("\n");
}
myAddress.setText(strReturnedAddress.toString());
For more information go to: http://developer.android.com/reference/android/location/Geocoder.html
try this-
Geocoder geocoder = new Geocoder(getActivity(),Locale.ENGLISH);
StringBuilder stringBuilder = new StringBuilder();
List<Address> addressList;
try {
addressList = geocoder.getFromLocation(Latitude, Longitude, 1);
if (addressList.size() > 0) {
Address address = addressList.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
stringBuilder.append(address.getAddressLine(i)).append("\n");
stringBuilder.append(address.getLocality()).append("\n");
stringBuilder.append(address.getPostalCode()).append("\n");
stringBuilder.append(address.getCountryName()).append("\n");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Don't forget to give permissions in manifest-
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
I would recommend to use google play services to vet the location http://developer.android.com/google/play-services/location.html
If your app can be installed in devices with no google play services check out this code https://github.com/BeyondAR/beyondar/tree/master/android/BeyondAR_Framework/src/com/beyondar/android/util/location and start with the location manager
I'm trying sample code for getting location using gps service.bt not gettong location.
Below is my code.-
public class MainActivity extends Activity implements LocationListener{
Location mLocation;
LocationManager mManager;
LocationListener mlistener;
Geocoder mcoder;
Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
txtLat = (TextView) findViewById(R.id.tv);
}
public void getMyLocation(){
String addressString = "";
final Geocoder gc = new Geocoder(this, Locale.getDefault());
try
{
final List<Address> addresses = gc.getFromLocation(18.5203, 73.8567, 4);
final StringBuilder sb = new StringBuilder();
System.out.println("location..."+sb);
if ( addresses.size() > 0 )
{
final Address address = addresses.get(0);
for ( int i = 0; i < address.getMaxAddressLineIndex(); i++ )
{
sb.append(address.getAddressLine(i)).append("\n");
}
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
}
catch ( final IOException e )
{
}
txtLat.setText("Your Current Position is:\n" +
"\n" + addressString);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
getMyLocation();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Your code just needs some minor changes.
You must implement all methods of the listener to understand if the provider is available, if any is built into the device and if you can expect Location updates anyway.
In getMyLocation() you call the Geocoder.getFromLocation() with hardcoded latitude and longitude. Is this for debugging purposes?
Then there's a System.println() of a newly created , empty StringBuilder. If you want to print something out it's better to use Log.d().
And finally - if everything else works, but you still get no address in the textview - then try to Toast the address. It has less possibilities to go wrong but you need to stare on the screen as the message disappears after a second.
My guess here is, that your Emulator has no GPS configured or you do not get updates - either because there's no satellite or you simply do not wait long enough for satellite connections.
I wrote a program to show my current location, Address etc in android phone. The API used is Android 2.2. Previously it worked fine in a MTS CDMA phone. It had an API of Android 2.3. It also works fine in emulator. Now. I have bought a Sony Ericsson Xperia Minipro and it also has Android 2.3. But the program will run on it. But the edit texts will not show anything. I use edit texts to display the values. They are not updated by the program at all. What can be the problem? Same program works fine in emulator and it shows location! Please help. I can paste the code below
public class TravelGuide extends Activity {
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES=1;
private static final long MINIMUM_TIME_BETWEEN_UPDATES=1000;
StringBuilder strReturnedAddress;
List<Address> addresses;
protected LocationManager locationManager;
static String videoId;
Double lat;
Double longd;
Address returnedAddress;
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
//Double latitude = location.getLatitude();
//Double longitude = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,new MyLocationListener());
showCurrentLocation();
}
public void showCurrentLocation()
{
Location location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!=null)
{
TextView myLatitude = (TextView)findViewById(R.id.mylatitude);
TextView myLongitude = (TextView)findViewById(R.id.mylongitude);
TextView myAddress = (TextView)findViewById(R.id.myaddress);
String message=String.format("currentLocation\n Longitude:%1$s \n Latitude:%2$s",location.getLongitude(),location.getLatitude());
Toast.makeText(TravelGuide.this,message,Toast.LENGTH_LONG).show();
myLatitude.setText("Latitude: " + String.valueOf(location.getLatitude()));
myLongitude.setText("Longitude: " + String.valueOf(location.getLongitude()));
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(Double.valueOf(location.getLatitude()),
Double.valueOf(location.getLongitude()), 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");
}
videoId = (returnedAddress.getAddressLine(1)).toString();
//sendAddress(videoId);
myAddress.setText(strReturnedAddress.toString());
}
else{
myAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//test = "kovalam";
myAddress.setText("Canont get Address!");
}
}
}
public class MyLocationListener implements LocationListener
{
//private final Context MyLocationListener = null;
//double LATITUDE;
//double LONGITUDE;
TextView myLatitude;
TextView myLongitude;
TextView myAddress;
public void onLocationChanged(Location location)
{
//Context context = null;
myLatitude = (TextView)findViewById(R.id.mylatitude);
myLongitude = (TextView)findViewById(R.id.mylongitude);
myAddress = (TextView)findViewById(R.id.myaddress);
//String message=String.format("new Location\n Longitude:%1$s \n Latitude:%2$s",
//location.getLongitude(),location.getLatitude());
//Toast.makeText(TouristGuideActivity.this,message,Toast.LENGTH_LONG).show();
myLatitude.setText("Latitude: " + String.valueOf(location.getLatitude()));
myLongitude.setText("Longitude: " + String.valueOf(location.getLongitude()));
Geocoder geocoder = new Geocoder(TravelGuide.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(Double.valueOf(location.getLatitude()),
Double.valueOf(location.getLongitude()), 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");
}
videoId = (returnedAddress.getAddressLine(1)).toString();
//sendAddress(videoId);
//myAddress.setText(strReturnedAddress.toString());
myAddress.setText("Hello");
}
else{
myAddress.setText("No Address returned!");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
myAddress.setText("Canont get Address!");
}
}
public void onStatusChanged(String s, int i, Bundle b)
{
//Toast.makeText(TouristGuideActivity.this,"Provider status changed",Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s)
{
Toast.makeText(TravelGuide.this,"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s)
{
Toast.makeText(TravelGuide.this,"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
you are getting locaton object null,try put log in else condition..and the reason is you are fetching last known location which in not available in that phone some how..
so if its true..
Go to this answer here implement that code to get current location...and it will work fine.
If you are using GPS Provider to get Location,Its found that Its not so accurate to return you location object,Network Provider is better option According to me.