繁体   English   中英

Android Sudio,无法获得使用 api 和 listview 的程序

[英]Android Sudio, cant get a program working with api and listview

我有这个问题,我无法将 api 信息拉回程序。 我检查了一些教程,但没有任何帮助。 也许有人知道可能是什么问题,或者可以提供一些有用的链接来解决问题。 我正在做一个简单的货币兑换展示应用程序来提升我的技能并了解更多关于 android 工作室的知识。 先感谢您!

主要活动

package com.example.currencyapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

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

public class MainActivity extends AppCompatActivity {

    private ListView mCurrencies;
    private RequestQueue mQueue;

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

        mCurrencies = findViewById(R.id.currencies);
        Button button = findViewById(R.id.button);

        mQueue = Volley.newRequestQueue(this);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                jsonParse();

            }
        });

    }
    private void jsonParse() {
        String url = "https://api.exchangeratesapi.io/latest";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("rates");

                            for (int i = 0; i < jsonArray.length(); i++) {
                               JSONObject rate = jsonArray.getJSONObject(i);

                               String rates = rate.getString("rates");

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

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        mQueue.add(request);

    }
}

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"
    android:padding="15dp"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/currencies"
        android:layout_width="368dp"
        android:layout_height="597dp"
        android:includeFontPadding="false"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginStart="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginTop="15dp"
        android:layout_marginEnd="13dp"
        android:layout_marginRight="13dp"
        android:textColor="@android:color/black"
        android:textSize="20sp" />

    <Button
        android:id="@+id/button"
        android:layout_width="169dp"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="144dp"
        android:layout_marginLeft="144dp"
        android:layout_marginEnd="141dp"
        android:layout_marginRight="141dp"
        android:layout_marginBottom="39dp"
        android:text="parse" />

</RelativeLayout>

如果您注意到,api 响应“rates”不是 JSONArray,而是 JSONObject。

{
   "rates":{
      "CAD":1.5621,
      "HKD":9.533,
      "ISK":156.1,
      "PHP":59.058,
      ...
     }
}

为什么mCurrencies类型是 ListView? 你的意思是List<String>

我创建了一个 function 可以帮助您获得 List 的响应

List<String> parser(JSONObject response) {
        HashMap<String, String> currencies = new HashMap<>();
        JSONObject exchangeRates = response.optJSONObject("rates");
        Iterator<String> keys = exchangeRates.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            String value = exchangeRates.optString(key);
            currencies.put(key, value);
        }
        return new ArrayList<>(currencies.values());
    }

现在在您的代码中像这样使用它

@Override
public void onResponse(JSONObject response) {
    mCurrencies = parser(response)
}

不要使用 try-catch,而是使用 optString 更安全。 让我知道这是否有帮助。

顺便说一句,欢迎加入社区✋

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM