java - 是否可以使用改造来获取 listView 内的 Double 值数组?

标签 java android json listview retrofit

我有汇率 API ( https://api.exchangeratesapi.io/latest?base=USD ),其中包含不同货币的 double 值数组,我还有用于 listViewBaseAdapter ,我想获取这个listView 中的数据并将上次请求的时间戳保存在某处。

我希望它看起来像这样:

示例:

丹麦克朗

6.74

匈牙利福林

299.56

...

This is my XML layout of ListView

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp"
    android:layout_margin="4dp">

    <TextView
        android:id="@+id/txt_currency_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/black"
        android:textSize="18sp"
        android:text="USD"/>

    <TextView
        android:id="@+id/txt_currency_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/black"
        android:textSize="14sp"
        android:text="2222"/>

</LinearLayout>

CurrencyResponse Class

public class CurrencyResponse {

    @SerializedName("rates")
    @Expose
    private Currency rates;
    @SerializedName("base")
    @Expose
    private String base;
    @SerializedName("date")
    @Expose
    private String date;

    public Currency getRates() {
        return rates;
    }

    public String getBase() {
        return base;
    }

    public String getDate() {
        return date;
    }

public class Currency {

    @SerializedName("CAD")
    @Expose
    private Double cAD;
    @SerializedName("HKD")
    @Expose
    private Double hKD;
    @SerializedName("ISK")
    @Expose
    private Double iSK;
    @SerializedName("PHP")
    @Expose
    private Double pHP;
    @SerializedName("DKK")
    @Expose
    private Double dKK;
    @SerializedName("HUF")
    @Expose
    private Double hUF;
    @SerializedName("CZK")
    @Expose
    private Double cZK;
    @SerializedName("GBP")
    @Expose
    private Double gBP;
    @SerializedName("RON")
    @Expose
    private Double rON;
    @SerializedName("SEK")
    @Expose
    private Double sEK;
    @SerializedName("IDR")
    @Expose
    private Double iDR;
    @SerializedName("INR")
    @Expose
    private Double iNR;
    @SerializedName("BRL")
    @Expose
    private Double bRL;
    @SerializedName("RUB")
    @Expose
    private Double rUB;
    @SerializedName("HRK")
    @Expose
    private Double hRK;
    @SerializedName("JPY")
    @Expose
    private Double jPY;
    @SerializedName("THB")
    @Expose
    private Double tHB;
    @SerializedName("CHF")
    @Expose
    private Double cHF;
    @SerializedName("EUR")
    @Expose
    private Double eUR;
    @SerializedName("MYR")
    @Expose
    private Double mYR;
    @SerializedName("BGN")
    @Expose
    private Double bGN;
    @SerializedName("TRY")
    @Expose
    private Double tRY;
    @SerializedName("CNY")
    @Expose
    private Double cNY;
    @SerializedName("NOK")
    @Expose
    private Double nOK;
    @SerializedName("NZD")
    @Expose
    private Double nZD;
    @SerializedName("ZAR")
    @Expose
    private Double zAR;
    @SerializedName("USD")
    @Expose
    private Double uSD;
    @SerializedName("MXN")
    @Expose
    private Double mXN;
    @SerializedName("SGD")
    @Expose
    private Double sGD;
    @SerializedName("AUD")
    @Expose
    private Double aUD;
    @SerializedName("ILS")
    @Expose
    private Double iLS;
    @SerializedName("KRW")
    @Expose
    private Double kRW;
    @SerializedName("PLN")
    @Expose
    private Double pLN;

    public Double getcAD() {
        return cAD;
    }

    public Double gethKD() {
        return hKD;
    }

    public Double getiSK() {
        return iSK;
    }

    public Double getpHP() {
        return pHP;
    }

    public Double getdKK() {
        return dKK;
    }

    public Double gethUF() {
        return hUF;
    }

    public Double getcZK() {
        return cZK;
    }

    public Double getgBP() {
        return gBP;
    }

    public Double getrON() {
        return rON;
    }

    public Double getsEK() {
        return sEK;
    }

    public Double getiDR() {
        return iDR;
    }

    public Double getiNR() {
        return iNR;
    }

    public Double getbRL() {
        return bRL;
    }

    public Double getrUB() {
        return rUB;
    }

    public Double gethRK() {
        return hRK;
    }

    public Double getjPY() {
        return jPY;
    }

    public Double gettHB() {
        return tHB;
    }

    public Double getcHF() {
        return cHF;
    }

    public Double geteUR() {
        return eUR;
    }

    public Double getmYR() {
        return mYR;
    }

    public Double getbGN() {
        return bGN;
    }

    public Double gettRY() {
        return tRY;
    }

    public Double getcNY() {
        return cNY;
    }

    public Double getnOK() {
        return nOK;
    }

    public Double getnZD() {
        return nZD;
    }

    public Double getzAR() {
        return zAR;
    }

    public Double getuSD() {
        return uSD;
    }

    public Double getmXN() {
        return mXN;
    }

    public Double getsGD() {
        return sGD;
    }

    public Double getaUD() {
        return aUD;
    }

    public Double getiLS() {
        return iLS;
    }

    public Double getkRW() {
        return kRW;
    }

    public Double getpLN() {
        return pLN;
    }
}
}

BaseAdapter

public class CustomListAdapter extends BaseAdapter {
        private Context context;
        private List<CurrencyResponse> responseList;

        public CustomListAdapter(Context context, List<CurrencyResponse> currencyList) {
            this.context = context;
            this.responseList = currencyList;
        }

        @Override
        public int getCount() {
            return responseList.size();
        }

        @Override
        public Object getItem(int i) {
            return responseList.get(i);
        }

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

        @SuppressLint("DefaultLocale")
        @Override
        public View getView(int i, View convertView, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.adapter_view_layout, viewGroup, false);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            CurrencyResponse response = responseList.get(i);
            Double[] currencyList = new Double[]{response.getRates().getcAD(), response.getRates().gethKD(),
                    response.getRates().getiSK(), response.getRates().getpHP(), response.getRates().getdKK(), response.getRates().gethUF()
                    , response.getRates().getcZK(), response.getRates().getgBP(), response.getRates().getrON(),
                    response.getRates().getsEK(), response.getRates().getiDR(), response.getRates().getiNR(), response.getRates().getbRL(),
                    response.getRates().getrUB(), response.getRates().gethRK(), response.getRates().getjPY(),
                    response.getRates().gettHB(), response.getRates().getcHF(), response.getRates().geteUR(), response.getRates().getmYR()
                    , response.getRates().getbGN(), response.getRates().gettRY(), response.getRates().getcNY(),
                    response.getRates().getnOK(), response.getRates().getnZD(), response.getRates().getzAR(),
                    response.getRates().getuSD(),response.getRates().getmXN(), response.getRates().getsGD(), response.getRates().getaUD(),
                    response.getRates().getiLS(), response.getRates().getkRW(), response.getRates().getpLN()};
            //viewHolder.txtCurrencyName.setText(Arrays.toString(currencyList));
           // viewHolder.txtCurrencyValue.setText(String.format("%.2f", response.getRates().gethKD()));
            //viewHolder.txtCurrencyValue.setText(String.format("%.2f", currencyList[i]));



            return convertView;
        }

        private class ViewHolder {
            private TextView txtCurrencyName, txtCurrencyValue;

            ViewHolder(View view) {
                txtCurrencyName = view.findViewById(R.id.txt_currency_name);
                txtCurrencyValue = view.findViewById(R.id.txt_currency_value);
            }
        }
    }

MainActivity

public class MainActivity extends AppCompatActivity {
        private ListView listView;
        private List<Currency> currencyList;
        private List<CurrencyResponse> currencyResponses;
        private CustomListAdapter adapter;
        private CompositeDisposable disposable = new CompositeDisposable();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            listView = findViewById(R.id.list_view);
            currencyList = new ArrayList<>();
            currencyResponses = new ArrayList<>();
            fetchData();

        }

        private void fetchData() {
            CurrencyServiceApi api = ApiClient.getRetrofit().create(CurrencyServiceApi.class);
            disposable.add(api.getCurrency()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<CurrencyResponse>() {
                        @Override
                        public void accept(CurrencyResponse currencyResponse) throws Exception {
                            if (currencyResponse.getRates() != null) {
                                currencyList.add(currencyResponse.getRates());
                                currencyResponses.add(currencyResponse);
                                adapter = new CustomListAdapter(MainActivity.this, currencyResponses);
                                listView.setAdapter(adapter);
                            }
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            Toast.makeText(MainActivity.this, throwable.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }));

        }

listView 中是否可以只有一个 TextView 来设置 double 值数组。

第二个问题是,如果 api 链接(上面给出)中没有货币名称,我应该从哪里获取货币名称?

最佳答案

使用 Recyclerview

这是适配器类 公共(public)类 AdapterCurrency 扩展 RecyclerView.Adapter {

private Context context;
private List<Currency> currency;
private Activity activity;


public AdapterChat(Context context, List<Currency> currency) {
    this.context = context;
    this.currency = currency;
    activity = (Activity) context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    AdapterChat.ViewHolder vh;
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_currency, parent, false);
    vh = new AdapterChat.ViewHolder(itemView);
    return vh;
}

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    holder.txt_currency_name.setText(currency.get(position).getName());
    holder.txt_currency_name.setText(currency.get(position).getValue);
}



@Override
public int getItemCount() {
    return chat.size();
}

public  class ViewHolder extends  RecyclerView.ViewHolder{

    public TextView txt_currency_name;
    public TextView txt_currency_value;



    public ViewHolder(View itemView) {
        super(itemView);
        txt_currency_name = (TextView) itemView.findViewById(R.id.txt_currency_name);
        txt_currency_name = (TextView) itemView.findViewById(R.id.txt_currency_name);
    }
}

}

这是card_currency.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp"
    android:layout_margin="4dp">

    <TextView
        android:id="@+id/txt_currency_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/black"
        android:textSize="18sp"
        android:text="USD"/>

    <TextView
        android:id="@+id/txt_currency_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@android:color/black"
        android:textSize="14sp"
        android:text="2222"/>

</LinearLayout>

这是 Activity 公共(public)类 ActivityCurrency 扩展 AppCompatActivity {

private RecyclerView rvCurrency;
private GridLayoutManager gridLayoutManager;
public AdapterCurrency adapterCurrency;
private List<Currency> currency;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_vertrage);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    rvCurrency = (RecyclerView) findViewById(R.id.rvCurrency);
    currency  = new ArrayList<>();


    gridLayoutManager = new GridLayoutManager(this,1);
    rvCurrency.setLayoutManager(gridLayoutManager);

    adapterCurrency = new AdapterVerträge(this,currency);
    rvCurrency.setAdapter(adapterCurrency);



}
}

这是 Activity.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".Vertraege"
    tools:showIn="@layout/activity_vertrage">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rvVerträge"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/windowBackground"
            android:scrollbars="vertical" />

</androidx.constraintlayout.widget.ConstraintLayout>

数据模型

public class Currency {

    private String name;
    private String value;

    public Currency(String name, String value) {
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

私有(private)无效load_data_from_server() {

                        AsyncTask<Integer,Void,Void> task = new AsyncTask<Integer, Void, Void>() {
                            @Override
                            protected Void doInBackground(Integer... integers) {

                                OkHttpClient client = new OkHttpClient();
                                Request request = new Request.Builder()
                                        .url("https://api.exchangeratesapi.io/latest?base=USD")
                                        .build();
                                try {
                                    Response response = client.newCall(request).execute();

                                    Log.d("Response", response.toString());
                                    JSONObject object = new JSONObject(response.body().string());

                                    JSONObject rates = new JSONObject((object.getJSONObject("rates")))


                                    Iterator<String> iter = rates.keys();
                                    while (iter.hasNext()) {
                                        String key = iter.next();
                    try {
                        Object value = rates.get(key);
                        Currency data = new Currency(value.getString("name"),value.getString("value"));
                        currency.add(data);
                    } catch (JSONException e) {
                        // Something went wrong!
                    }
                }


            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                System.out.println("End of content"+e);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            adapterCurrency.notifyDataSetChanged();
        }

        @Override
        protected void onPreExecute() {

        }
    };
    task.execute();
}

关于java - 是否可以使用改造来获取 listView 内的 Double 值数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59236848/

相关文章:

java - Gradle中的String.ReplaceAlli缺少要转义的字符

java - 什么是 Java 窗口的 Windows 注册类?

android - 当我尝试创建图像 Assets 时,Android Studio 中不存在文件 Logo.png

java - Robospice-改造测试

android - 无法运行程序 "xx/sdk//tools/emulator": java. io.IOException : error=2, 没有这样的文件或目录

javascript - 查找历史雅虎财经报价

json - 统计属性为 "null"或包含 "null"的对象数量

java - 参数形式的表数量

java - 从for循环中获取值?

javascript - 在mvc View 中反序列化Json