如何使用exchangeatesapi.io和okhttp更改汇率基础货币,并在微调器中选择所有基础货币?

时间:2019-12-23 11:35:26

标签: java android api currency

我想做的是将汇率基础(默认情况下为欧元)更改为任何其他货币,并将它们都像我要更改的货币一样放在微调器中,以便用户可以选择任何基础货币以及要使用微调器转换的货币。

在这里是这样,但以基本货币为

这是我的代码

public static BreakIterator data;
    List<String> keysList;
    Spinner toCurrency;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toCurrency = findViewById(R.id.planets_spinner);
        final EditText edtEuroValue = findViewById(R.id.editText4);
        final Button btnConvert = findViewById(R.id.button);
        textView = findViewById(R.id.textView7);
        try {
            //From the API loads the conversion types from a url and makes a request(gets all of the currencies)
            loadConversionTypes();
        } catch (IOException e) {
            e.printStackTrace();
        }

        btnConvert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //If the inserted currency to convert from is not empty the program will initialize the toCurency(will get the
                //selected item and then will get the double value of the currency to convert from(weird as hell ik)
                if(!edtEuroValue.getText().toString().isEmpty())
                {
                    String toCurr = toCurrency.getSelectedItem().toString();
                    double euroValue = Double.valueOf(edtEuroValue.getText().toString());

                    Toast.makeText(MainActivity.this, "Calculating..", Toast.LENGTH_SHORT).show();
                    try {
                        //calls the convertCurrency() method and takes in the parameters of the currrency to convert to, and the
                        //currency to convert from(2nd paramter)
                        convertCurrency(toCurr, euroValue);
                    }
                    //will catch an error if the conversion doesn't work
                    catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
                //If the value of the currency to convert from is empty, it will show a message:
                else
                {
                    Toast.makeText(MainActivity.this, "Please enter a value first.", Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

    public void loadConversionTypes() throws IOException {

        String url = "https://api.exchangeratesapi.io/latest";

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .header("Content-Type", "application/json")
                .build();


        //passes in parameter request from the api(code above)
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                //takes the failure message and displays it as a toast
                String mMessage = e.getMessage().toString();
                Log.w("failure Response", mMessage);
                Toast.makeText(MainActivity.this, mMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                final String mMessage = response.body().string();


                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //Toast.makeText(MainActivity.this, mMessage, Toast.LENGTH_SHORT).show();
                        try {
                            JSONObject obj = new JSONObject(mMessage);
                            JSONObject b = obj.getJSONObject("rates"); //b is a collection of rate data
                            //JSONObject base = obj.getJSONObject("base");

                            Iterator keysToCopyIterator = b.keys(); //the Iterator gets all of the data from the b rates and
                                                                    //stores it in keysToCopyIterator
                            //a new scalable ArrayList of keys is created, the keys are stored as strings
                            keysList = new ArrayList<String>();

                            //while the key iterator keeps returning true for any tokens to be scanned it will keep on checking
                            //for the next keys possible until it returns false(all tokens have been scanned)
                            while(keysToCopyIterator.hasNext()) {

                                //finds and returns the complete key and saves it a string, which is later saved to an arraylist
                                String key = (String) keysToCopyIterator.next();

                                //adds the key to the ArrayList
                                keysList.add(key);

                            }


                            //An ArrayAdapter is created and sets all of the currencies(keysLists or exchange rates) to the spinner
                            ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, keysList );
                            toCurrency.setAdapter(spinnerArrayAdapter); //the to currency spinner is set to the adapter






                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
            }




        });
    }

    public void convertCurrency(final String toCurr, final double euroValue) throws IOException {

        String url = "https://api.exchangeratesapi.io/latest";

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(url)
                .header("Content-Type", "application/json")
                .build();



        //catches execption incase of failure or error
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                String mMessage = e.getMessage().toString();
                Log.w("failure Response", mMessage);
                Toast.makeText(MainActivity.this, mMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                final String mMessage = response.body().string();
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //Toast.makeText(MainActivity.this, mMessage, Toast.LENGTH_SHORT).show();
                        try {
                            JSONObject obj = new JSONObject(mMessage);
                            JSONObject  b = obj.getJSONObject("rates");

                            String val = b.getString(toCurr);

                            double output = /*selected currency */euroValue*Double.valueOf(val);


                            textView.setText(String.valueOf(output));

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
            }





        });
    }
}

别介意我是初学者,我正在尝试学习编写代码并注释掉所有内容 如果您帮不上忙,那么也许您可以找到有关操作方法的文档,我一直到处都是,找不到合适的Java代码。谢谢!

1 个答案:

答案 0 :(得分:0)

由于没有人回答我提出了自己的解决方案。

我创建了2个微调器,并称它们为baseCurrency和toCurrency,然后 我所做的就是-创建了另一个微调器,然后将微调器适配器设置为baseCurrency.setAdapter(spinnerArrayAdapter);

然后在convertCurrency()中,将这两行内容放入

String fromCurrVal = b.getString(baseCurrency);
double output = baseValue/Double.valueOf(frommCurrVal)*Double.valueOf(val);

这将获得输入数字的基值,将其除以所选货币汇率,然后乘以要转换成的货币值。 有点令人困惑,但它可以非常有效地完成工作。

相关问题