首页 > 解决方案 > 将加元兑换成美元,

问题描述

我正在编写一个简单的 android 应用程序来将 CAD 转换为美元,它可以工作,但我总是使用相同的汇率,所以我想从互联网上自动获取汇率,我该怎么做?

这是我的代码:

public void currencyChange (View view){
    double usd = 0;
    String value;
    DecimalFormat finalUSD = new DecimalFormat("0.00");//To print just 2 decimals numbers
    Log.i("info","Button pressed");

    EditText cad = (EditText) findViewById(R.id.DollarEditText);
    value = cad.getText().toString();//Converting the value to string
    Log.i("amount in CAD ", cad.getText().toString());
    usd = Double.valueOf(value).doubleValue();

    usd = usd * 0.76; // ****  RATE   ****

    Log.i("amount in USD ", Double.toString(usd));




    Toast.makeText(this,value + " CAD" + " => " + finalUSD.format(usd) + " USD",Toast.LENGTH_LONG).show();}

谢谢您的帮助!

标签: javaandroid

解决方案


您可以使用欧洲中央银行的每日外汇汇率:https ://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/index.en.html

请阅读免责声明,但他们在其网站上为开发人员提供了一个 PHP 示例。据我所知,除了将它们命名为源之外,没有其他限制。

    String fxRates = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
    URLConnection httpcon = new URL(fxRates).openConnection();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db;
    try {
      db = dbf.newDocumentBuilder();
      Document doc = db.parse(httpcon.getInputStream());

      NodeList cubes = doc.getElementsByTagName("Cube");
      double fxEurCad = 0.0;
      double fxEurUsd = 0.0;

      for (int i = 0; i < cubes.getLength(); i++) {
        Node cube = cubes.item(i);
        Node currency = cube.getAttributes().getNamedItem("currency");
        Node rate = cube.getAttributes().getNamedItem("rate");
        if (null != currency && "CAD".equals(currency.getNodeValue())) {
          fxEurCad = Double.parseDouble(rate.getNodeValue());
        }
        if (null != currency && "USD".equals(currency.getNodeValue())) {
          fxEurUsd = Double.parseDouble(rate.getNodeValue());
        }
      }

      double fxCadUsd = fxEurCad/fxEurUsd;

推荐阅读