Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何根据GPS位置或国家代码获取货币符号_Java_Android_Gps - Fatal编程技术网

Java 如何根据GPS位置或国家代码获取货币符号

Java 如何根据GPS位置或国家代码获取货币符号,java,android,gps,Java,Android,Gps,我已经实施了一个小项目,在那里我需要显示基于位置的货币符号。 例:如果我在印度,它应该显示卢比符号,如果是美元符号,我已经实现了,但它总是给出英镑符号 我的代码: LocationManager locationManager = (LocationManager) getSystemService(ListActivity.LOCATION_SERVICE); Location loc = locationManager.getLastKnownLocation(LocationManager

我已经实施了一个小项目,在那里我需要显示基于位置的货币符号。 例:如果我在印度,它应该显示卢比符号,如果是美元符号,我已经实现了,但它总是给出英镑符号

我的代码:

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();
    }
}
LocationManager LocationManager=(LocationManager)getSystemService(ListActivity.LOCATION\u服务);
Location loc=locationManager.getLastKnownLocation(locationManager.GPS\U提供程序);
如果(loc!=null){
地理编码器代码=新的地理编码器(ListActivity.this);
试一试{
列表地址=code.getFromLocation(loc.getLatitude(),loc.getLatitude(),1);
地址obj=地址。获取(0);
字符串cc=Currency.getInstance(obj.getLocale()).getSymbol();
日志d(“货币符号:”,cc);
}捕获(IOE异常){
e、 printStackTrace();
}
}

您可以使用它获取您所在位置的区域设置

Locale locale= getResources().getConfiguration().locale;
Currency currency=Currency.getInstance(locale);
String symbol = currency.getSymbol();
参考


我需要显示各自国家的货币符号,并从全球定位系统中获取国家。我搜索了很多,最后找到了下面的代码,它工作正常,所以我想分享这些代码,其他人不能浪费时间


这里您需要第一个国家代码,如在,美国从经纬度,我们得到完整的地址


请在运行代码之前检查清单文件中的GPS权限。 下面是一些权限


需要GPSTracker.java文件代码创建GPSTracker java文件并编写以下代码。在这条红线中,不要担心,它不会影响任何东西

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;
    }
}

下面是mainactivity.java类
public类MainActivity扩展了AppCompatActivity{
公共静态分类地图currencyLocaleMap;
文本视图t;
地理编码器;
私有静态最终映射COUNTRY_TO_Locale_Map=newhashmap();
静止的{
Locale[]locales=Locale.getAvailableLocales();
for(语言环境l:语言环境){
国家到地区映射。put(l.getCountry(),l);
}
}
公共静态区域设置getLocaleFromCountry(字符串国家){
返回国家/地区到地区/地图。获取(国家/地区);
}
字符串Currencysymbol=“”;
@
推翻
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(TextView)findViewById(R.id.text);
GPSTracker GPSTracker=新的GPSTracker(MainActivity.this);
geocoder=新的geocoder(MainActivity.this,getLocaleFromCountry(“”));
double lat=gpsTracker.getLatitude();
double lng=gpsTracker.getLongitude();
日志e(“横向长度”,lng+“横向长度检查”+横向长度);
currencyLocaleMap=新树映射(新比较器(){
公共整数比较(货币c1、货币c2){
返回c1.getCurrencyCode().compareTo(c2.getCurrencyCode());
}
});
for(Locale:Locale.getAvailableLocales()){
试一试{
Currency=Currency.getInstance(区域设置);
currencyLocaleMap.put(货币、区域设置);
Log.d(“locale utill”,currency+“locale1”+locale.getCountry());
}捕获(例外e){
Log.d(“区域设置utill”、“e”+e);
}
}
试一试{
列表
addresses=geocoder.getFromLocation(lat,lng,2); 地址obj=地址。获取(0); Currencysymbol=getCurrencyCode(obj.getCountryCode()); Log.e(“getCountryCode”,“异常地址”+obj.getCountryCode()); Log.e(“Currencysymbol”、“异常地址”+Currencysymbol); }捕获(例外e){ Log.e(“异常地址”、“异常地址”+e); //Log.e(“Currencysymbol”、“异常地址”+Currencysymbol); } t、 setText(货币符号); } 公共字符串getCurrencyCode(字符串countryCode){ 字符串s=“”; for(Locale:Locale.getAvailableLocales()){ 试一试{ if(locale.getCountry().equals(countryCode)){ Currency=Currency.getInstance(区域设置); currencyLocaleMap.put(货币、区域设置); Log.d(“locale utill”,currency+“locale1”+locale.getCountry()+“s”+s); s=getCurrencySymbol(货币+“”); } }捕获(例外e){ Log.d(“区域设置utill”、“e”+e); } } 返回s; } 公共字符串getCurrencySymbol(字符串currencyCode){ Currency Currency=Currency.getInstance(currencyCode); System.out.println(currencyCode+“:-”+currency.getSymbol(currencyLocaleMap.get(currency)); 返回currency.getSymbol(currencyLocaleMap.get(currency)); } }
上述代码将始终为手机提供语言环境货币。您能建议我如何获取符号..吗?请改为传递当前语言环境,如locale current=getResources().getConfiguration().locale;但这种方法不适用于gps。请参考:这是任何方法,但我需要基于位置、ip或gps显示货币符号。你可以编辑我的代码吗?它给出了£symbol。它应该根据位置显示卢比符号。他没有询问设备的区域设置。他需要一个给定纬度、经度坐标的地区(或国家或货币符号)
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));
    }
  }