requestLocationUpdates throws error - java

sorry, I know such questions happened here, but I cannot action them in my code, I am a beginner...
So, I am trying to get a GPS coordinates read from LocationManager and my code is throwing a "Can't create handler inside thread that has not called Looper.prepare()".
So my code works this way. I used a Timer and Timertask classes to create a scheduled task from which my coordinates are being read.
This is a timer class:
public class GeoLocationTimer extends Timer {
private List coords;
private Context context;
public GeoLocationTimer(Context context){
this.context = context;
this.coords = new ArrayList<Double>();
//Log.e("cont timer","content" + context);
}
public void addPosition(Double pos) {
this.coords.add(pos);
}
public void scheduleTasks(long interval) {
//Log.e("z schedule","cont"+context);
this.schedule(new GeoLocationTask(this, context), 0, interval);
}
public void cancelTasks() {
this.cancel();
}
public List getList(){
return coords;
}
This is task:
public class GeoLocationTask extends TimerTask{
private final GeoLocationTimer timerContext;
private final Context context;
private Pair<Double, Double> coordsSet;
public GeoLocationTask(GeoLocationTimer timerContext, Context context){
this.timerContext = timerContext;
this.context = context;
}
#Override
public void run() {
// TODO Auto-generated method stub
GeoActivity tracker = new GeoActivity(context);
coordsSet = tracker.getLocation();
Log.e("first","timertask");
if (coordsSet != null){
Log.e("first","a tu wartosc" + coordsSet.first);
Log.e("second","a tu wartosc" + coordsSet.second);
timerContext.addPosition(coordsSet.first);
timerContext.addPosition(coordsSet.second);
//context.addPosition(tracker.getLocationNow().get(1));
}
}
public boolean cancel() {
return false;
}
}
Here is context from which I am trying to run this task:
package com.example.gpstracking;
public class GeoActivity extends ContextWrapper {
Context context;
public GeoActivity(Context base) {
super(base);
this.context = base;
}
public Pair<Double, Double> getLocation(){
Tracking track = new Tracking(context);
return track.getLocation();
}
And tracking now:
public class Tracking extends Service implements LocationListener{
private final Context mContext;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 30 * 1; // 0.5 minute
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
protected LocationManager locationManager;
public Tracking(Context context) {
this.mContext = context;
}
public Pair<Double, Double> getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
Log.e("no provider","turn it on man!");
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
Log.e("Network", "Network");
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.e("latitude","latitude"+latitude);
Log.e("longitude","longitude"+longitude);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
return new Pair(latitude,longitude);
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
Log.e("GPS", "GPS");
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
return new Pair(latitude,longitude);
}
}
} catch (Exception e) {
Log.e("excepton:","exp" + e.getMessage());
e.printStackTrace();
e.getMessage();
}
return new Pair(0.0,0.0);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
So, sorry for being stupid. Could someone help me with this?
Cheers
A

I probably found the issue: I really should not call requestlocationupdates in here, as I am calling for updates in the timer class. Need to go and test it outside :)
Cheers!

Related

Current Location with Geocoder not working for non activities

I am currently building an Android app and my main problem is that I have a class that retrieves the current latitude and longitude of my current location.
Whenever I make an activity out of it, it works fine. However, now that I;m trying to make it a class that will just retrieve the latitude and longitude and will set it to a setter, it doesn't work.
Namely, I am using FusedLocationProviderClient and Geocoder in order to retrieve those two elements.
The problem is that both of them won't take the current object as an argument (context, since it's a non activity class), whereas they work just fine with activities. In other words, this doesn't apply whenever I apply this for the context. Below is my class, with the problems that I am facing.
I would appreciate some help here thank you in advance.
public class CurrentLocationFinder {
FusedLocationProviderClient fusedLocationProviderClient;
double lagitudeValue, longitudeValue;
private final static int REQUEST_CODE = 100;
public CurrentLocationFinder() {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);//*******doesn't accept 'this' in method
getLastLocation();
}
private void getLastLocation() { //doesn't accept 'this'
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(location -> {
if (location != null) {
Geocoder geocoder = new Geocoder(this, Locale.getDefault()); //doesn't accept 'this'
List<Address> addressList = null;
try {
addressList = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
System.out.println("********************" + addressList.get(0).getLatitude());
setLagitude(addressList.get(0).getLatitude());
setLongitude(addressList.get(0).getLongitude());
System.out.println("=====================" + addressList.get(0).getLatitude());
} catch (IOException e) {
e.printStackTrace();
}
}
});
} else {
//askPermission();
}
}
public double getLagitude() {
return this.lagitudeValue;
}
public double getLongitude() {
return this.longitudeValue;
}
public void setLagitude(double lagitude) {
this.lagitudeValue = lagitude;
}
public void setLongitude(double longitude) {
this.longitudeValue = longitude;
}
}

java.lang.NullPointerException Can't set text from class to activity [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I'm rather new to coding and my long term goal is to create an android weather app. I've created the main activity and a class, plus I'm using Weatherlib to make things a bit easier.
The main activity asks for permission and grabs the location using GPS. Those coords are sent to the getweather method which grabs the information using OpenWeatherMap. When the data is retrieved, in this case, cloud percentage, what I want it to do is pass that to the main activity to setText for the TextView clouds. My issue is that it's throwing a NullPointerException when I try to do that from onWeatherRetrieved.
public class MainActivity extends AppCompatActivity {
private double latitude;
private double longitude;
private FusedLocationProviderClient fusedLocationClient;
private String response;
private TextView clouds;
private Context context;
private Context x;
private WeatherOWM weatherOWM;
//Get location
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
clouds = findViewById(R.id.clouds);
x = this;
context = getApplicationContext();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
requestPermissions();
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
return;
}
fusedLocationClient.getLastLocation().addOnSuccessListener (this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null){
double latitude = location.getLatitude();
double longitude = location.getLongitude();
System.out.println(latitude + " " + longitude);
WeatherOWM loc = new WeatherOWM(latitude, longitude, context);
loc.getWeather();
}
}
});
}
public void setClouds(Integer cloud) {
clouds.setText(cloud);
}
private void requestPermissions(){
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
}
}
public class WeatherOWM{
private double latitude;
private double longitude;
private Context ma;
WeatherConfig config = new WeatherConfig();
private Object WeatherConfig;
private Object hourForecast;
private Object MainActivity;
private MainActivity mainActivity;
public WeatherOWM(double latitude, double longitude, Context ma){
this.latitude = latitude;
this.longitude = longitude;
this.ma = ma;
}
public void getWeather() {
TextView clouds = new TextView(ma);
//Init client
WeatherClient client = null;
config.ApiKey = "REDACTED";
try {
client = (new WeatherClient.ClientBuilder()).attach(ma)
.httpClient(WeatherDefaultClient.class)
.provider(new OpenweathermapProviderType())
.config(config)
.build();
} catch (WeatherProviderInstantiationException e) {
e.printStackTrace();
}
client.getHourForecastWeather(new WeatherRequest(latitude, longitude), new WeatherClient.HourForecastWeatherEventListener() {
#Override
public void onWeatherRetrieved(WeatherHourForecast weatherHourForecast) {
List<HourForecast> hourList = weatherHourForecast.getHourForecast();
for (HourForecast hourForecast: hourList) {
Weather weather = hourForecast.weather;
long timestamp = hourForecast.timestamp;
mainActivity.setClouds(hourForecast.weather.clouds.getPerc());
System.out.println(hourForecast.weather.clouds.getPerc());
}
}
#Override
public void onWeatherError(WeatherLibException wle) {
System.out.println("ERROR");
}
#Override
public void onConnectionError(Throwable t) {
System.out.println("ERROR");
}
});
}
}
In the WeatherOWM class , you have created an instance of MainActivity as here :
private MainActivity mainActivity;
and in the method , you have written :
mainActivity.setClouds(hourForecast.weather.clouds.getPerc());
the problem is that the variable "mainActivity" has no value and is empty so you have to give value to it.
so in the WeatherOWM class , write this code :
mainActivity = new MainActivity();
please reply is solved your problem

Passing longitude and latitude to a java class

I need to find the least distant pharmacy and add its id to a table in the database.
public class gpslocation implements LocationListener {
private final Context mContext;
protected LocationManager locationManager;
boolean checkGPS = false;
boolean checkNetwork = false;
boolean canGetLocation = false;
Location loc;
double latitude;
double longitude;
String city;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
public gpslocation(Context mContext) {
this.mContext = mContext;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
// getting GPS status
checkGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
checkNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!checkGPS && !checkNetwork) {
Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show();
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (checkNetwork) {
Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show();
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
} catch (SecurityException e) {
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (checkGPS) {
Toast.makeText(mContext, "GPS", Toast.LENGTH_SHORT).show();
if (loc == null) {
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
}
} catch (SecurityException e) {
Log.d("Exce", e + "");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return loc;
}
public double getLongitude() {
if (loc != null) {
longitude = loc.getLongitude();
}
return longitude;
}
public double getLatitude() {
if (loc != null) {
latitude = loc.getLatitude();
// loc.
}
return latitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS Not Enabled");
alertDialog.setMessage("Do you wants to turn On GPS");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void stopUsingGPS() {
if (locationManager != null) {
// locationManager.removeUpdates(this);
}
}
#Override
public void onLocationChanged(Location location) {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(mContext, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 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()
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();
// Only if available else return NULL
Toast.makeText(mContext, "Longitude:" + Double.toString(longitude) + "\nLatitude:" + Double.toString(latitude), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
// Boolean checkgps = true;
// String gps = String.valueOf(checkgps);
}
this is my code to find latitude and longitude in Android Studio.
package DatabasePackage;
import java.sql.ResultSet;
import org.json.JSONArray;
import org.json.JSONObject;
public class locationcalculation {
double distance;
boolean b;
int i;
ConnectionClass con=new ConnectionClass();
public String getlocation(String lat1,String lon1){
String a="";
String se="Select * from tbl_pharmacy ";
ResultSet rs=con.selectCommand(se);
JSONArray ja = new JSONArray();
JSONObject job;
try{
while(rs.next()){
String lattitude=rs.getString("lattitude");
String longitude=rs.getString("longitude");
double dis=Calculation(lat1, lattitude, lon1, longitude);
distance=dis;
if(dis<=10){
job=new JSONObject();
job.put("distance", distance);
job.put("id", rs.getString("phar_id"));
ja.put(job);
break;
}
else if(dis<5){
break;
}
}
}catch(Exception ex){
}
return ja.toString();
}
public double Calculation(String latt1,String latt2,String longg1,String longg2){
String j="";
final int R = 6371; // Radius of the earth
double lat1=Integer.parseInt(latt1);
double lat2=Integer.parseInt(latt2);
double lon1=Integer.parseInt(longg1);
double lon2=Integer.parseInt(longg2);
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1))
* Math.sin(deg2rad(lat2))
+ Math.cos(deg2rad(lat1))
* Math.cos(deg2rad(lat2))
* Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180.0);
}
private double rad2deg(double rad) {
return (rad * 180.0 / Math.PI);
}
}
This is my java class (written in NetBeans) to find the distance between two pairs of latitude and longitude. one pair is to be obtained from the android device and other pair from the heidisql database.
String Dis=distance.getlocation(latt, lon);
String str1="insert into
tbl_prescription(prescription,user_id)values('"+value[0]+"','1')";
// String str1="insert into
tbl_prescription(prescription)values('"+value[0]+"')";
// System.out.println(str1
//out.println(str1);
boolean status=con.executeCommand(str1);
this is where i have to call the function getLocation()(also written in NetBeans but in a different jsp page) that is defined in the java class. But I do not know how to get the value from the android device to this function call. Can someone solve this for me?

How to get a Currency symbol based on GPS location or Country code

I have implemented a mini project and there i need to display currency symbol based on Location.
ex: If i am in India it should display rupee symbol if USA $ symbol, I have implemented but it always gives Pound symbol
My Code:
LocationManager locationManager = (LocationManager) getSystemService(ListActivity.LOCATION_SERVICE);
Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
Geocoder code = new Geocoder(ListActivity.this);
try {
List<Address> addresses = code.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
Address obj = addresses.get(0);
String cc = Currency.getInstance(obj.getLocale()).getSymbol();
Log.d("Currency Symbol : ", cc);
} catch (IOException e) {
e.printStackTrace();
}
}
I needed to show currency symbol of respective country and get country are from GPS i searched lot finally came up with below code its working properly so i want to share this code others could not waste there time
here you need first country code like IN,US from latitude longitude we get full address
Please check GPS permission in manifest file before run code.
below are the some permissions
need GPSTracker.java file code create GPSTracker java file and write below code. in this some red line dont worry it affect nothing
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// Flag for GPS status
boolean isGPSEnabled = false;
// Flag for network status
boolean isNetworkEnabled = false;
// Flag for GPS status
boolean canGetLocation = false;
Location location; // Location
double latitude; // Latitude
double longitude; // Longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// Getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// No network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app.
* */
public void stopUsingGPS() {
if (locationManager != null) {
//locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/Wi-Fi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog.
* On pressing the Settings button it will launch Settings Options.
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing the Settings button.
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// On pressing the cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#
Override
public void onLocationChanged(Location location) {}
#
Override
public void onProviderDisabled(String provider) {}
#
Override
public void onProviderEnabled(String provider) {}
#
Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#
Override
public IBinder onBind(Intent arg0) {
return null;
}
}
here is mainactivity.java class
public class MainActivity extends AppCompatActivity {
public static SortedMap < Currency, Locale > currencyLocaleMap;
TextView t;
Geocoder geocoder;
private static final Map < String, Locale > COUNTRY_TO_LOCALE_MAP = new HashMap < String, Locale > ();
static {
Locale[] locales = Locale.getAvailableLocales();
for (Locale l: locales) {
COUNTRY_TO_LOCALE_MAP.put(l.getCountry(), l);
}
}
public static Locale getLocaleFromCountry(String country) {
return COUNTRY_TO_LOCALE_MAP.get(country);
}
String Currencysymbol = "";
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.text);
GPSTracker gpsTracker = new GPSTracker(MainActivity.this);
geocoder = new Geocoder(MainActivity.this, getLocaleFromCountry(""));
double lat = gpsTracker.getLatitude();
double lng = gpsTracker.getLongitude();
Log.e("Lat long ", lng + "lat long check" + lat);
currencyLocaleMap = new TreeMap < Currency, Locale > (new Comparator < Currency > () {
public int compare(Currency c1, Currency c2) {
return c1.getCurrencyCode().compareTo(c2.getCurrencyCode());
}
});
for (Locale locale: Locale.getAvailableLocales()) {
try {
Currency currency = Currency.getInstance(locale);
currencyLocaleMap.put(currency, locale);
Log.d("locale utill", currency + " locale1 " + locale.getCountry());
} catch (Exception e) {
Log.d("locale utill", "e" + e);
}
}
try {
List < Address > addresses = geocoder.getFromLocation(lat, lng, 2);
Address obj = addresses.get(0);
Currencysymbol = getCurrencyCode(obj.getCountryCode());
Log.e("getCountryCode", "Exception address " + obj.getCountryCode());
Log.e("Currencysymbol", "Exception address " + Currencysymbol);
} catch (Exception e) {
Log.e("Exception address", "Exception address" + e);
// Log.e("Currencysymbol","Exception address"+Currencysymbol);
}
t.setText(Currencysymbol);
}
public String getCurrencyCode(String countryCode) {
String s = "";
for (Locale locale: Locale.getAvailableLocales()) {
try {
if (locale.getCountry().equals(countryCode)) {
Currency currency = Currency.getInstance(locale);
currencyLocaleMap.put(currency, locale);
Log.d("locale utill", currency + " locale1 " + locale.getCountry() + "s " + s);
s = getCurrencySymbol(currency + "");
}
} catch (Exception e) {
Log.d("locale utill", "e" + e);
}
}
return s;
}
public String getCurrencySymbol(String currencyCode) {
Currency currency = Currency.getInstance(currencyCode);
System.out.println(currencyCode + ":-" + currency.getSymbol(currencyLocaleMap.get(currency)));
return currency.getSymbol(currencyLocaleMap.get(currency));
}
}
You can use this to get locale of your Location
Locale locale= getResources().getConfiguration().locale;
Currency currency=Currency.getInstance(locale);
String symbol = currency.getSymbol();
Refernce : Getting Current Locale

How to access a External class member inside a android Service?

Basically I have a android Service LogService which I trigger from my MainActivity. Inside service class I am creating a object of LocationListener class LocationFetcher with the name locationFetcher. The LocationFetcher class has a public string member FormattedResult. Now Inside the LogService.run() I want to fetch FormattedResult periodically. How to do That ?? Below is code for reference.
I have a LocationListener like This:
/*This is relevant content of LocationFetcher.java */
public class LocationFetcher extends TimerTask implements LocationListener{
public String FormattedResult;
private boolean availableFlag;
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
this.availableFlag=true;
this.FormattedResult=String.format(Locale.ENGLISH, "Lat=\t%f\nLong=\t%f", arg0.getLatitude(),arg0.getLongitude());
Log.d("LocationFetcher",this.FormattedResult);
}
#Override
public void run() {
// TODO Auto-generated method stub
Log.d("LocationFetcher","This is Timer Run !!!");
}}
My android service is like this :
/* This is the relevant pert from LogService.java file*/
public class LogService extends Service{
private Logger logger;
private LocationFetcher locationFetcher;
public LocationManager locationManager;
private Timer timer1;
#Override
public int onStartCommand(Intent intent,int flags, int startId){
super.onStartCommand(intent, flags, startId);
if(!this.running){
this.logger = new Logger(); //Initiated member from subclass
this.logger.start(); //Started
this.timer1 = new Timer(); //Timer for timed job
this.locationFetcher = new LocationFetcher();//THIS IS MY EXTERNAL CLASS in "LocationFetcher.java"
//I am using GPS data.
this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if(this.locationFetcher != null){//NULLPointerException is thrown if I REMOVE this if ??WHY
this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this.locationFetcher);
this.timer1.scheduleAtFixedRate(this.locationFetcher, 5000, 2000);
//Below Line still throws NullPointrException ??WHY
//this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this.locationFetcher);
}else{
Log.d("GPS-Logger"," Found Null LocationFlecther !");
}
}
public void run(){
LogService ll = LogService.this;
LocationManager mgr = ll.locationManager; //THIS IS MY QUESTION
// HOW DO I ACCESS THE GPS LOCATION STORED in locationmanager.FormattedResult
// Which is a string
// //////////////////////////////////////////////////////////////////////////
while(ll.isActive){
try {
String temp ;
if(!temp.isEmpty()){
Log.d("GPS-Logger","data is :"+temp);
}
Log.d("GPS-Logger","data is :");
Thread.sleep(5000);
sec +=1 ;
if(sec >= 12){
Log.d("GPS-Logger","Sending Data Here");
sec = 0;
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
ll.isActive=false;
Log.d("GPS-Logged","EXIT Request Received");
}
}
}
I know that I have asked multiple Questions above but I didn't knew how to separate them.
NEED HELP!!!
You can have the location Fetcher modified as "LocationListenerClass" shown below:
The main concern to see in the modified class are as follows:
1.I have used a singleton class for registering and removing location updates from overall area.(i.e say our service etc).
2.You should initialize the location string say (FormattedResult as in you case ) from both onLocationChngaed() and getCurrentLocation(). Because onLocationChngaed() will only call when the distance and time changed as provided in requestLocationUpdates study more about this.
public class LocationListenerClass implements LocationListener{
private static LocationListenerClass instance;
private static Context context;
private LocationManager myLocationManager;
private LocationListener myLocationListener;
private Double latitude = 0d;
private Double longitude = 0d;
public static String FormattedResult;
public static LocationListenerClass getInstance(Context context) {
LocationListenerClass.context = context;
if (null == instance) {
instance = new LocationListenerClass();
}
return instance;
}
public void getCurrentLocation() {
try {
myLocationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
myLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 30000, 100,
this);
Location location;
location = myLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
myLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 30000, 100,
myLocationListener);
location = myLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location != null) {
try {
latitude = location.getLatitude();
Data.CURENT_LATITUDE = latitude;
Log.v(ConstantLib.LOG, " latitude : "
+ Data.CURENT_LATITUDE);
longitude = location.getLongitude();
Data.CURENT_LONGITUDE = longitude;
Log.v(ConstantLib.LOG, " longitude : "
+ Data.CURENT_LONGITUDE);
**FormattedResult=String.format(Locale.ENGLISH, "Lat=\t%f\nLong=\t%f", latitude(),longitude());
Log.d("LocationFetcher",this.FormattedResult);**
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void removeLocationUpdates() {
try {
if (myLocationManager != null) {
myLocationManager.removeUpdates(myLocationListener);
}
} catch (Exception e) {
}
}
public void onLocationChanged(Location location) {
try {
if (location != null) {
Data.CURENT_LATITUDE = location.getLatitude();
Log.v(ConstantLib.LOG, "LOCATION CHANGED" + " latitude : "
+ Data.CURENT_LATITUDE);
longitude = location.getLongitude();
Data.CURENT_LONGITUDE = location.getLongitude();
Log.v(ConstantLib.LOG, "LOCATION CHANGED" + " longitude : "
+ Data.CURENT_LONGITUDE);
**FormattedResult=String.format(Locale.ENGLISH, "Lat=\t%f\nLong=\t%f", latitude(),longitude());
Log.d("LocationFetcher",this.FormattedResult);**
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}

Categories

Resources