获取“转换器”Android应用程序,根据用户输入将一种货币转换为另一种货币

时间:2016-06-11 02:16:39

标签: java android json xml android-studio

所以这是我的指示:

  

从以下位置检索当前货币转换率:

 http://api.fixer.io
     

例如,要将美元兑换成英镑,请致电:

 http://api.fixer.io/latest?base=USD&symbols=GBP
     

2-提供两种旋转器,其中包含您选择的5种货币。

     

3 - 对转换查找使用异步调用,它们不应该阻塞   UI线程。

现在我已经从JSON API中提取值并使其成功显示1美元到1英镑的转换率(这是通过硬编码以美元和英镑从JSON API中提取来完成的。但是现在我正在努力试图让硬编码的货币从一对包含5种不同货币的纺纱厂中拉出来。此外,我很难让费率乘以用户指定的金额(例如,如果价格是0.69并且用户想要将10USD转换为GBP应用程序应该报告转换量为6.90GBP)但是目前我得到的是“运营商*不能应用于双倍” 目前,该应用程序在发布时崩溃,我的首要任务是让它运行并将1个货币单位转换为等量的另一个货币单位。

这是我的FetchConversionRateTask.java文件

以及Android Studio引发错误的地方

package edu.ggc.tkeating.currencyconverter;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.Scanner;

/**
 * Created by T3P0 on 6/9/2016.
 */

//http://api.fixer.io/latest?base=USD&symbols=GBP
public class FetchConversionRateTask extends AsyncTask<String, String, Double> {

    private HttpURLConnection conn;
    private TextView tv;
    private Context context;
    private EditText amount;
    private TextView conversionTV;

    public FetchConversionRateTask(Context _context, TextView _tv, EditText _amount){
        this.tv = _tv;
        this.context = _context;
        this.amount = _amount;
    }

    private final static String TAG = "CurrencyConverter";




    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        MediaPlayer tingMP = MediaPlayer.create(context, R.raw.ting);
        tingMP.start();
    }

    @Override
    protected Double doInBackground(String... currencies){
        String from = currencies[0];
        String to = currencies[1];
        double rate = 0.0d;
        double conversion = 0.0d;


        try{
            URL url = new URL("http://api.fixer.io/latest?base="+ from +
                    "&symbols="+ to);
            conn =  (HttpURLConnection) url.openConnection();
            Scanner scanner = null;
            scanner = new Scanner(new BufferedInputStream(conn.getInputStream()));


            String rslt ="";
            while (scanner.hasNext()) rslt += scanner.nextLine();
            Log.i(TAG, rslt);

            // {"base":"USD","date":"2016-06-09","rates":{"GBP":0.69151}}
            rate = new JSONObject(rslt).getJSONObject("rates").getDouble(to);
            conversion = new JSONObject(rslt).getJSONObject("conversion").getDouble(String.valueOf(amount));



            scanner.close();
            return conversion;

        } catch (IOException | JSONException e){
            e.printStackTrace();
        }
        return rate;

    }

    @Override
    protected void onPostExecute(Double rate){
        super.onPostExecute(rate);
        MediaPlayer tingMP = MediaPlayer.create(context, R.raw.ting);
        tingMP.start();
        DecimalFormat format = new DecimalFormat("###.##");
        String msg = "rate=" + format.format(rate);
        Log.i(TAG, msg);
        tv.setText(msg);


    }
}

这是我的MainActivity.java

package edu.ggc.tkeating.currencyconverter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    private TextView result;
    private EditText amount;
    private String fromCurr;
    private String toCurr;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.btnConvert);
        result = (TextView) findViewById(R.id.tvResult);
        amount = (EditText) findViewById(R.id.amount);
        Spinner spinner2 = (Spinner) findViewById(R.id.spinnerFrom);
        fromCurr = spinner2.getSelectedItem().toString();
        Spinner spinner = (Spinner) findViewById(R.id.spinnerTo);
        toCurr = spinner.getSelectedItem().toString();
// Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.currency_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
        spinner.setAdapter(adapter);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new FetchConversionRateTask(getApplicationContext(), result,
                        amount).execute(fromCurr, toCurr);
            }
        });
    }
}

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="edu.ggc.tkeating.currencyconverter.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay"/>

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main"/>

</android.support.design.widget.CoordinatorLayout>

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="edu.ggc.tkeating.currencyconverter">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>

</manifest>

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="edu.ggc.tkeating.currencyconverter.MainActivity"
    tools:showIn="@layout/activity_main">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Convert"
        android:id="@+id/btnConvert"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Result"
        android:id="@+id/tvResult"
        android:layout_marginTop="44dp"
        android:layout_below="@+id/btnConvert"
        android:layout_centerHorizontal="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:ems="10"
        android:id="@+id/amount"
        android:layout_above="@+id/btnConvert"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="79dp"
        android:hint="How much do you want to convert?"/>

    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinnerTo"
        android:spinnerMode="dropdown"
        android:layout_above="@+id/btnConvert"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_toRightOf="@+id/tvResult"
        android:layout_toEndOf="@+id/tvResult"/>

    <Spinner
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinnerFrom"
        android:spinnerMode="dropdown"
        android:layout_above="@+id/btnConvert"
        android:layout_toLeftOf="@+id/btnConvert"
        android:layout_toStartOf="@+id/btnConvert"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Result"
        android:id="@+id/conversionTV"
        android:layout_marginTop="22dp"
        android:layout_below="@+id/tvResult"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

我觉得我错过了一些非常简单明了的东西,我希望新鲜的眼睛(以及更有经验的程序员)能够想出这个代码。先谢谢你了

0 个答案:

没有答案