使用Asynctask从外部站点检索数据

时间:2016-12-15 15:00:28

标签: android arrays json android-asynctask

我是Asynctask和JSon的新手。

我可以知道如何从这个网站开始检索货币汇率吗?

http://api.fixer.io/latest?base=SGD

我确实看过这篇文章,但我不太清楚如何开始......

AsyncTask Android example

从检索到的速率,我想通过使用自定义ListView适配器类将值添加到此ListView中。

enter image description here

xml文件的代码

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0.0dp"
    android:orientation="horizontal"
    android:layout_weight="0.4"
    android:weightSum="1" >

    <LinearLayout
        android:layout_width="0.0dp"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_weight="0.8" >

        <TextView
            android:id="@+id/convertedAmtTV"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="0.00"
            android:textSize="70dp"
            android:gravity="right" />

        <EditText
            android:id="@+id/inputAmtET"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="0"
            android:textAlignment="textEnd" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="0.0dp"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:layout_weight="0.2">

        <TextView
            android:id="@+id/convertedCurrTV"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="SGD"
            android:textSize="28dp"
            android:paddingLeft="2dp"
            android:paddingTop="29dp"
            android:paddingBottom="19dp"
            android:gravity="center_horizontal" />

        <TextView
            android:id="@+id/inputCurrTV"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="AUD"
            android:textSize="28dp"
            android:paddingLeft="2dp"
            android:layout_marginTop="3dp"
            android:gravity="center_horizontal" />

    </LinearLayout>

</LinearLayout>

<LinearLayout
    android:orientation="vertical"
    android:layout_weight="0.6"
    android:layout_width="match_parent"
    android:layout_height="0.0dp">

    <TextView
        android:text="From"
        android:textSize="21dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ListView
        android:id="@+id/currencyLV"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.class代码

public class MainActivity extends AppCompatActivity {

CurrencyRatesDetails crd = new CurrencyRatesDetails();

CurrencyRates cr = new CurrencyRates();

TextView inputCurrTV, convertedAmtTV;
ListView currencyLV;
EditText inputAmtET;
ArrayAdapter<String> adapter;
String[] currNameArr = crd.getNames();
String[] currCodeArr = crd.getCodes();
String[] currRateArr = crd.getRates();

String[] dbName;
String[] dbCode;
String[] dbRate;

Context context;

int index = 0;

//String[] rateCurrArr = {"AUD", "BGN", "BRL", "CAD", "CHF", "CNY"};
//double[] rateArr = {0.944, 1.2824, 2.2842, 0.96158, 0.70946, 4.8624}
Menu myMenu = null;

double amtInput, finalConversion;

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


    context = this;
    //context.deleteDatabase("currency.db");

    inputAmtET = (EditText) findViewById(R.id.inputAmtET);
    convertedAmtTV = (TextView) findViewById(R.id.convertedAmtTV);
    inputCurrTV = (TextView) findViewById(R.id.inputCurrTV);
    currencyLV = (ListView) findViewById(R.id.currencyLV);

    /*for (int i = 0; i < currNameArr.length; i++) {
        cr.addToDataBase(currNameArr[i], currCodeArr[i], currRateArr[i], getApplicationContext());
    }*/

    //cr.addToDataBase(currNameArr, getApplicationContext());

    //Resources myRes = this.getResources();
    //currArr =  myRes.getStringArray(R.array.currencyList);
    //adapter = ArrayAdapter.createFromResource(this, R.array.currencyList, android.R.layout.simple_selectable_list_item);
    //adapter = new ArrayAdapter<String>(this, android.R.layout.simple_selectable_list_item, currNameArr);
    //currencyLV.setAdapter(adapter);

    dbName = cr.retrieveAllName(getApplicationContext());
    dbCode = cr.retrieveAllCode(getApplicationContext());
    dbRate = cr.retrieveAllRate(getApplicationContext());

    currencyLV.setAdapter(new CustomAdapter(this, dbName, dbCode, dbRate));

    currencyLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            inputCurrTV.setText(dbCode[i]);

            index = i;

            //Getting rate based on selected currency code
            //rate = rateArr[i];

        }
    });
}

public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    this.myMenu = menu;
    addMenuItems(menu);

    getMenuInflater().inflate(R.menu.mainmenu, menu);
    return true;
}

private void addMenuItems(Menu menu) {
    int index = 200;
    menu.add(index, index, index, "Settings");
    menu.add(index, index + 1, index + 1, "Add Custom Rate");
    menu.add(index, index + 2, index + 2, "Load Default Rates");
}

public boolean onOptionsItemSelected(MenuItem item) {

    //getOrder() to get Menu Item at this specific orderId
    if (item.getItemId() == R.id.menu_convert) {

        amtInput = Double.parseDouble(inputAmtET.getText().toString());

        //finalConversion = amtInput / rate;

        finalConversion = crd.conversion(amtInput, index);

        //Formatting converted value to 2d.p
        String finalValue = String.format("%.2f", finalConversion);

        convertedAmtTV.setText(finalValue);

    } else if (item.getItemId() == 201) {

        Intent myIntent = new Intent(MainActivity.this, CustomXchangeRate.class);
        startActivity(myIntent);

    }

    return true;
}

}

自定义ListView适配器类

public class CustomAdapter extends BaseAdapter{

String[] resultNames;
String[] resultCodes;
String[] resultRates;

Context context;

private static LayoutInflater inflater = null;

public CustomAdapter(CustomXchangeRate customXchangeRate, String[] names, String[] codes, String[] rates) {
    resultNames = names;
    resultCodes = codes;
    resultRates = rates;

    context = customXchangeRate;

    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public CustomAdapter(MainActivity mainActivity, String[] names, String[] codes, String[] rates) {
    resultNames = names;
    resultCodes = codes;
    resultRates = rates;

    context = mainActivity;

    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return resultNames.length;
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}

public class ViewHolder{
    TextView tvName;
    TextView tvCode;
    TextView tvRate;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    ViewHolder vh = new ViewHolder();
    View rowView;

    rowView = inflater.inflate(R.layout.activity_custom_adapter, null);

    vh.tvName = (TextView) rowView.findViewById(R.id.currencyNameTV);
    vh.tvCode = (TextView) rowView.findViewById(R.id.currencyCodeTV);
    vh.tvRate = (TextView) rowView.findViewById(R.id.currencyRateTV);

    vh.tvName.setText(resultNames[position]);
    vh.tvCode.setText(resultCodes[position]);
    vh.tvRate.setText(resultRates[position]);

    return rowView;

}
}

非常感谢任何帮助...

1 个答案:

答案 0 :(得分:0)

在你的应用程序中获取此JSON的最佳方法是使用Volley:

https://developer.android.com/training/volley/simple.html

点击此链接,您会找到您要求的内容。

干杯