Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've been looking at the right way to work with the following code which is in my MainActivity and pull the result in to another activity so I can call a URL of 'http://www.website.com?lat:lng:speed:bearing' which will be based on the values pulled through.
locationCheck() sits in my Mainactivity how ever I have a JSONParse activity which I want to use the location found to construct the url. What I do not is how to share the result.
In HTML or PHP I would use a global value.
Although I can call and toast on create I have not found the best way to share the result.
public void locationCheck() {
MyLocation myLocation = new MyLocation();
// this is the result
myLocation.getLocation(this, locationResult);
}
public LocationResult locationResult = new LocationResult() {
public void gotLocation(final Location location) {
try {
double lat = location.getLatitude();
double lng = location.getLongitude();
if (lat != 0.0 && lng != 0.0) {
String sLat;
String sLng;
sLat = Double.toString(lat);
sLng = Double.toString(lng);
String gps_location = sLat + " : " + sLng;
Toast.makeText(getBaseContext(),
"We got gps location! " + gps_location + "",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
};
The following allows me to have a location activity run and post its results as strings in to a globally accessible form which then allows me to use in the format of creating a context aware URL through another activity...
As you can see the toast uses the global value which allowed me to test they where accessible.
In the Mainactivity....
public void locationCheck() {
MyLocation myLocation = new MyLocation();
// this is the result
myLocation.getLocation(this, locationResult);
}
public LocationResult locationResult = new LocationResult() {
public void gotLocation(final Location location) {
try {
double lat = location.getLatitude();
double lng = location.getLongitude();
double bearing = location.getBearing();
double speed = location.getSpeed();
if (lat != 0.0 && lng != 0.0) {
String sLat;
String sLng;
String sBearing;
String sSpeed;
sLat = Double.toString(lat);
sLng = Double.toString(lng);
sBearing = Double.toString(bearing);
sSpeed = Double.toString(speed);
// send to global vars
Globals.glat = sLat;
Globals.glng = sLng;
Globals.gBearing = sBearing;
Globals.gSpeed = sSpeed;
String gps_location = Globals.glat + " : " + Globals.glng;
#SuppressWarnings("unused")
String gps_location2 = sBearing + " : " + sSpeed;
Toast.makeText(getBaseContext(),
"We got gps location! " + gps_location + "",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
}
}
};
In the Globals Activity
// Global Values
// http://stackoverflow.com/questions/3100726/sharing-global-variables-across-activities-problem-when-using-a-webview
// http://stackoverflow.com/questions/708012/android-how-to-declare-global-variables?rq=1
public class Globals {
static String glat;
static String glng;
static String gBearing;
static String gSpeed;
}
Related
I know it is a common question and has been answered a number of times... But I am looking for an answer to a specific problem.
I have written a method which is required to return current lat/long as string. The code goes like this:
public class LibraryProvider {
public String basicMethod(String string) {
String text = string;
LocationManager locationManager;
String provider;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
text = "Provider " + provider + " has been selected.";
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
text = text + "\n" + "lat: " + String.valueOf(lat);
text = text + "\n" + "lng: " + String.valueOf(lng);
} else {
text = "Location not available";
}
return text;
}
}
However, the android studio is not allowing this.get System Service:
cannot resolve Method getSystemService(java.lang.String)
I am new to android and not clear about context and intents... I think the problem has something to do with it.
(edited)
the code i was using to load the above class is as under
private final class ServiceHandler extends android.os.Handler {
public ServiceHandler(Looper looper){
super(looper);
}
public void handleMessage(Message msg){
dynamicClassLoader();
}
String text;
private void dynamicClassLoader(){
final String apkFile =Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/apkFile.apk";
String className = "com.va.android.level2.lib.LibraryProvider";
final File optimisedDexOutputPath = getDir("outdex", 0);
DexClassLoader classLoader = new DexClassLoader(apkFile,optimisedDexOutputPath.getAbsolutePath(),null,getClassLoader());
try{
Class loadedClass = classLoader.loadClass(className);
// LibraryInterface lib = (LibraryInterface) loadedClass.newInstance();
// lib.basicMethod("hello");
Object obj =(Object)loadedClass.newInstance();
Method method = loadedClass.getMethod("basicMethod", String.class);
text = (String) method.invoke(obj,"added method");
showOutput(text);
} catch (Exception e){
e.printStackTrace();
}
}
private void showOutput(final String str){
mServiceHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MyService.this,str, Toast.LENGTH_LONG).show();
}
});
}
}
earlier it was working, but now it is raising some exception at loadedClass.newInstance(); .....i think i need to pass the context ...but how??
Try get Activity Context reference in custom class constructor and use it ;
public class LibraryProvider {
private Context context;
public LibraryProvider(Context context){
this.context=context;
}
}
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
You need a Context to call getSystemService(...).
Actually you are calling it from "this" that is not a class that has a Context.
try this
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
Log.d("DEBUG",location.toString());
double lat = location.getLatitude();
double lon = location.getLongitude();
}
};
try this
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
see this link on how to get current location in Android
I am using the BroadcastReceiver in my application ,here i am receiving the current location and place in this class.hence i am getting the current location,hence my question is how to send this location string from this class to another class .i have to load this string data in the listview in another class so how can do this please help thanks in advance. My code is
public class AlarmReceiver extends BroadcastReceiver implements LocationListener {
MyTrip trip_method;
double latitude, longitude;
Context context;
private static final long MIN_DISTANCE_FOR_UPDATE = 10;
private static final long MIN_TIME_FOR_UPDATE = 1000 * 60 * 2;
protected LocationManager locationManager;
Location location;
#Override
public void onReceive(Context context, Intent intent) {
trip_method = new MyTrip();
this.context = context;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Find_location();
// For our recurring task, we'll just display a message
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
public void Find_location() {
// Location nwLocation;
try {
location = getLocation(LocationManager.NETWORK_PROVIDER);
System.out.println("nwLocation-------" + location);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
System.out.println("latitude-------" + latitude + "longitude-----" + longitude);
Toast.makeText(
context,
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
// To display the current address in the UI
(new GetAddressTask()).execute(location);
} else {
trip_method.showSettingsAlert("NETWORK");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
locationManager.requestLocationUpdates(provider,
MIN_TIME_FOR_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
return null;
}
/* *//**//*
* Following is a subclass of AsyncTask which has been used to get
* address corresponding to the given latitude & longitude.
*//**//**/
private class GetAddressTask extends AsyncTask<Location, Void, String> {
Context mContext;
/* public GetAddressTask(Context context) {
super();
mContext = context;
}*/
/* *//**//*
* When the task finishes, onPostExecute() displays the address.
*//**//**/
#Override
protected void onPostExecute(String address) {
// Display the current address in the UI
Toast.makeText(context.getApplicationContext(),
"address---" + address,
Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Location... params) {
String Address = null;
String Location = null;
Geocoder geocoder;
List<android.location.Address> addresses;
geocoder = new Geocoder(context, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
Address = addresses.get(0).getAddressLine(0) + ", " + addresses.get(0).getAddressLine(1) + ", " + addresses.get(0).getAddressLine(2);
Location = addresses.get(0).getAddressLine(2);
System.out.println("Location----" + Location);
//This "Location" value i have to send to another activity
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Return the text
return Address;
/* } else {
return "No address found";
}*/
}
}// AsyncTask class
}
Use this in your code as appropriate:
In your First class:
Intent intent = new Intent(this, another_activity.class);
intent.putExtra("Location", Location.toString);
startService(intent)
In your Second class:
String Location = getActivity().getIntent.getStringExtra("Location")
Now you have passed string from one class to another. Use the Location variable where you need it.
i need your help regarding the location update in android. Following is my code for getting location update and it is working fine. But it returns invalid message body when i get the stored variable with location in oncreate method of main class. After thorough research it seems that the variable i called in oncreate method is empty. Can you please tell me how to get the address as it appears in onlocationChanged Method. Thank you!
Calling class with oncreate method:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = new Mylocation();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
String address1= listener.getAddress();
{
sendSms(phone, message, false);
} catch (Exception e) {
Log.i("Error Is ", e.toString());
}
}
location class:
class Mylocation implements LocationListener{
double lat, lon;
static final String address="";
public void onLocationChanged(Location location)
{
//...
lat = location.getLatitude();
lon = location.getLongitude();
address = GetAddressDetail(lat, lon);
Log.i("Messge is", address); //working here
}
public String getAddress(){ //not returning the address
return address;
}
public String GetAddressDetail(Double lat2, Double lon2)
{
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}
}
Make sure your variables are initialized properly. I don't see evidence of this in the question so I am just checking.
// Instantiation
Mylocation listener;
String phone;
String message;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
listener = new Mylocation(this);
phone = "";
message = "";
// These two lines aren't really necessary,
// this should be in your MyLocation class
//locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
// Add this line, we are going to initialize this class
// and make sure that address gets set
listener = new Mylocation();
String address1 = listener.getAddress();
try {
// If neither phone nor message is empty lets sendSms()
if (!phone.isEmpty() || !message.isEmpty()) {
sendSms(phone, message, false);
}
} catch (Exception e) {
Log.i("Error Is ", e.toString());
}
}
Change the String address to private and in the getter try return this.address;
class Mylocation implements LocationListener {
double lat, lon;
// Let's make this private so it can't be accessed directly,
// since you have the setter and getter.
private String address = "";
// Make sure you are overriding this method
#Override
public void onLocationChanged(Location location) {
/** ... */
lat = location.getLatitude();
lon = location.getLongitude();
address = GetAddressDetail(lat, lon);
Log.i("Messge is", address);
}
public String getAddress(){
return (address.isEmpty()) ? "Address not set" : this.address;
}
public String GetAddressDetail(Double lat2, Double lon2) {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}
}
Edit
I made changes to your code in my answer above, check the comments. I am also going to suggest additional methods for your MyLocation class:
class Mylocation implements LocationListener {
protected LocationManager locationManager;
private Context activityContext;
// The initializing method, this fires off first
// when a new instance of the class is created
public MyLocation(Context context) {
this.activityContext = context;
locationManager = (LocationManager) activityContext.getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);) {
locationManager.requestLocationUpdates(
NETWORK_PROVIDER,
MIN_TIME,
MIN_DISTANCE,
this
);
}
getLocation();
}
private double lat;
private double lon;
public double getLat() {
return this.lat;
}
public double getLng() {
return this.lng;
}
public void getLocation() {
if (location == null) {
locationManager.requestLocationUpdates(NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(NETWORK_PROVIDER);
if (location != null) {
// Set the coordinate variables
lat = location.getLatitude();
lon = location.getLongitude();
Log.i("Network", "Lat: " + latitude + " / Lng: " + longitude);
}
}
}
}
}
You are calling getAdress directly after you set the locationmanager to probe for a location. The onLocationChanged method probably hasn't been called yet when you call getAddress this way. I would recommend changing it to something like below to make sure it has been called:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listener = new Mylocation();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,new LocationListener(){
#Override
public void onLocationChanged(Location location) {
//...
long lat = location.getLatitude();
long lon = location.getLongitude();
String address = GetAddressDetail(lat, lon);
//Do whatever you want to do with the address here, maybe add them to the message or something like that.
sendSms(phone, message, false);
}
});
}
public String GetAddressDetail(Double lat2, Double lon2)
{
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.ENGLISH);
try {
List<Address> addresses = geocoder.getFromLocation(lat2,lon2, 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("Address:");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i));
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
return ret;
}
i am developing an gps program in that i am getting gps values for every 5 minutes,
and it is working great, but i have to store the values which i get. it has been refreshed for every 5 minutes and i have only one text view so that it deletes the old values when the new one is refreshed.
this is my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
{
//initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is enabled
//if not, notify user with a toast
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)); else {
//get a location provider from location manager
//empty criteria searches through all providers and returns the best one
String providerName = manager.getBestProvider(new Criteria(), true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else {
tv.setText("Last known location not found. Waiting for updated location...");
}
//sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
manager.requestLocationUpdates(providerName, 60000, 1, this);
}
}
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else {
tv.setText("Problem getting location");
}
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
//sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
((lon - curStatLon) * (lon - curStatLon)) );
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
Thank you.
You can store your Textview's value into a file for persistance storage. Study my answer properly, I am adding a file store method in your existing code,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
{
//initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is enabled
//if not, notify user with a toast
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)); else {
//get a location provider from location manager
//empty criteria searches through all providers and returns the best one
String providerName = manager.getBestProvider(new Criteria(), true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else {
tv.setText("Last known location not found. Waiting for updated location...");
}
//sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
manager.requestLocationUpdates(providerName, 60000, 1, this);
}
}
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
// I have added this line
appendData ( location.getLatitude() + " latitude, " + location.getLongitude() + " longitude" );
} else {
tv.setText("Problem getting location");
}
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
//sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
((lon - curStatLon) * (lon - curStatLon)) );
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
// method to write in file
public void appendData(String text)
{
File dataFile = new File("sdcard/gpsData.txt");
if (!dataFile.exists())
{
try
{
dataFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(dataFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You need to write following permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Well you have plenty of persistence options, but in this case the best is using SharedPreferences
No one can say for sure without knowing exactly what you need to do with the saved data. ArrayList is a good option if you need to store it temporarily. You can create a new ArrayList then put the value in there at the same time that you use it in setText(). If you want something permanent then you will probably want to store it in a DB or a file. Check out Storage Options
Also, in this case, a good idea may be to store it in an ArrayList temporarily then use that list to transfer them to a file or DB for permanent storage if that's what you want
Another way to store it temporarily, and possibly save somewhere later would be a HashMap. Maybe something in the form of HashMap<String, HashMap<String, String>>. Since we don't know your exact intentions with the data, examples could be endless but maybe this will give you a good starting point so you can decide what will work best for you then you can find many examples all over SO and the Google for your choice
I'm trying to get a address with using this code by ihrupin from http://www.hrupin.com/2011/04/android-gps-using-how-to-get-current-location-example
It works fine until I add geocode to get an address form latitude and longitude in onLocationChanged
Here is the code :
buttonGetLocation.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
progress.setVisibility(View.VISIBLE);
// exceptions will be thrown if provider is not permitted.
try
{
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch (Exception ex)
{
}
try
{
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
catch (Exception ex)
{
}
// don't start listeners if no provider is enabled
if (gps_enabled)
{
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
if (network_enabled)
{
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
}
}
});
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// This needs to stop getting the location data and save the battery power.
locManager.removeUpdates(locListener);
String londitude = "Londitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
String altitiude = "Altitiude: " + location.getAltitude();
String accuracy = "Accuracy: " + location.getAccuracy();
String time = "Time: " + location.getTime();
//
String address = "Adress : "+goToGeocoder(location.getLatitude().getLongitude());
editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + address);
progress.setVisibility(View.GONE);
}
}
Context context;
public String goToGeocoder(String ll)
{
List<Address> almt;
String alamat = null;
double lat,lng;
StringBuilder sb = new StringBuilder();
lat = Double.parseDouble(ll.substring(0,ll.indexOf(",")-1));
lng = Double.parseDouble(ll.substring(ll.indexOf(",")+1));
try
{
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
almt = geocoder.getFromLocation(lat, lng, 5);
if(almt.size()>0)
{
Address almtSkrng = almt.get(0);
String admin_area = sb.append(almtSkrng.getAdminArea()).toString();
if(almtSkrng.getAddressLine(0).equals(null) || almtSkrng.getAddressLine(0).equals(""))
{
alamat = almtSkrng.getFeatureName();
}
alamat = almtSkrng.getAddressLine(0)+" "+almtSkrng.getAdminArea();
//temp_koordinate.setAlamat(alamat);
}
else
{
alamat = "";
//temp_koordinate.setAlamat(alamat);
}
}
catch(IOException e)
{
//
}
return alamat;
}
The application was force closed.
Anyone can give the solution to fix this problem?
Many thanks
kind regards
Hard to answer the reason for your Force Close without you providing logs that show the crash (i.e. stack trace)...
Without that information, the answer might be:
You need to handle the situation whereby geocoding returns null.
if(almt != null) {
//do what you need to do
} else {
//handle the null situation here
}
OR you could add a catch block to your try/catch statement to handle NullPointerException.