如何在 Android Studio 中使用改造来检索数据

Posted

技术标签:

【中文标题】如何在 Android Studio 中使用改造来检索数据【英文标题】:How to retrieve data using retofit in Android Studio 【发布时间】:2021-07-14 12:44:55 【问题描述】:
https://pro-api.coinmarketcap.com/v1/tools/price-conversion?symbol=NGN&amount=1000897.01&convert=BTC&CMC_PRO_API_KEY=*********************************

这是 url,这里是查询该 url 返回的 json:

"status":"timestamp":"2021-04-20T08:48:16.990Z","error_code":0,"error_message":null,"elapsed":17,"credit_count":1,"notice":null,"data":"id":2819,"symbol":"NGN","name":"Nigerian Naira","amount":1000897.01,"last_updated":"2021-04-20T08:48:07.000Z","quote":"BTC":"price":0.0444454708294559,"last_updated":"2021-04-20T08:48:02.000Z"

以下是我在android studio中从上述api获取数据的代码

我的 pojo 课程:

import com.google.gson.annotations.SerializedName;

public class CurrencyModel 
    @SerializedName("name")
    private String currencyName;
    @SerializedName("Amount")
    private int currencyAmount;
    @SerializedName("quote")
    Quota quota;

    public CurrencyModel(Quota quota) 
        this.quota = quota;
       // quota.bitcoinModel.getCoinPrice();
    

    public CurrencyModel(String currencyName, int currencyAmount, Quota quota) 
        this.currencyName = currencyName;
        this.currencyAmount = currencyAmount;
        this.quota = quota;
    

    public String getCurrencyName() 
        return currencyName;
    

    public void setCurrencyName(String currencyName) 
        this.currencyName = currencyName;
    

    public int getCurrencyAmount() 
        return currencyAmount;
    

    public void setCurrencyAmount(int currencyAmount) 
        this.currencyAmount = currencyAmount;
    

    public Quota getQuota() 
        return quota;
    

    public void setQuota(Quota quota) 
        this .quota = quota;
    

public class Quota 
    int price;

    @SerializedName("BTC")
    BitcoinModel bitcoinModel;

    public Quota(BitcoinModel bitcoinModel) 
        this.bitcoinModel = bitcoinModel;
    

    public BitcoinModel getBitcoinModel() 
        return bitcoinModel = new BitcoinModel(price);
    

    public void setBitcoinModel(BitcoinModel bitcoinModel) 
        this.bitcoinModel = bitcoinModel;
    


public class BitcoinModel 

    @SerializedName("price")
    private int coinPrice;

    public BitcoinModel(int coinPrice) 
        this.coinPrice = coinPrice;
    

    public int getCoinPrice() 
        return coinPrice;
    

    public void setCoinPrice(int coinPrice) 

        this.coinPrice = coinPrice;
    

我的活动

public class BitcoinConversionActivity extends AppCompatActivity 
    TextInputEditText amountConverted;

    Button conversionButton, buyCoinButton;

    TextView amountInCurrency;
    int amount;
    String amountEntered;
    Quota quota;
    CurrencyModel currencyModel;
    JsonPojo pojo;

    String symbol = "NGN";
    String convert = "BTC";
    int amountneeded = 1024587;
    String apiKey = "b34416c7-2bb9-44b1-aa76-1293edd14dda";
    String currencyName;
    int amountnm;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_coinconversion);

        amountConverted = findViewById(R.id.amount_edit_text);
        amountInCurrency = findViewById(R.id.conversion_rate_tv);
        conversionButton = findViewById(R.id.conversion_button);
        buyCoinButton = findViewById(R.id.buy_exchange_coin_button);

        conversionButton.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                amount = Integer.parseInt(amountConverted.getText().toString());
                if (TextUtils.isEmpty(Double.toString(amount)))

                    Toast.makeText(BitcoinConversionActivity.this, "Please Enter a valid Amount", Toast.LENGTH_LONG).show();

                else

                    CoinExchange();
                

            
        );

    

    private void CoinExchange() 

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://pro-api.coinmarketcap.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        BitcoinInterface service = retrofit.create(BitcoinInterface.class);
        Call<CurrencyModel> call = service.loadNairaToBitcionExchange(symbol,amountneeded,convert,apiKey);
        call.enqueue(new Callback<CurrencyModel>() 
            @Override
            public void onResponse(Call<CurrencyModel> call, Response<CurrencyModel> response) 
                if (response.isSuccessful())

                    String price = response.body().toString();
                    //amountInCurrency.setText(price);
                    amountInCurrency.setText("https://pro-api.coinmarketcap.com/"+symbol+amount+convert+apiKey);
                    Toast.makeText(BitcoinConversionActivity.this, "Data: " + response.body().getQuota().getBitcoinModel().getCoinPrice(), Toast.LENGTH_LONG).show();

            

            @Override
            public void onFailure(Call<CurrencyModel> call, Throwable t) 
                Toast.makeText(BitcoinConversionActivity.this, "Error: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            
        );

    

API接口:

public interface BitcoinInterface 
    @GET("v1/tools/price-conversion?")
    Call<CurrencyModel> loadNairaToBitcionExchange(@Query("symbol") String coinsSymbol,
                                                   @Query("amount") int currencyaAmount,
                                                   @Query("convert") String convertedToCurrency, 
                                                   @Query("CMC_PRO_API_KEY") String ApiKey);

调用返回 null,有时返回零。

【问题讨论】:

square.github.io/retrofit 这会有所帮助。 【参考方案1】:

API 中,您没有得到完全正确的CurrencyModel 作为响应。你得到另一个对象 CurrencyModel 是一个子对象。 您必须创建如下响应对象:

public class ResponseObject
 //@SerializedName("status")
 //private int status;


 @SerializedName("data")
 private CurrencyModel currencyModel;

  //getters and setters goes here

然后您的 interface 应该如下所示,因为您在这里期待 ResponseObject

public interface BitcoinInterface 
@GET("v1/tools/price-conversion?")
Call<ResponseObject> loadNairaToBitcionExchange(@Query("symbol") String coinsSymbol,
                                               @Query("amount") int currencyaAmount,
                                               @Query("convert") String convertedToCurrency, 
                                               @Query("CMC_PRO_API_KEY") String ApiKey);

【讨论】:

非常感谢@NRUSINGHA MOHARANA,您的观察救了一个兄弟。我非常感谢您的贡献

以上是关于如何在 Android Studio 中使用改造来检索数据的主要内容,如果未能解决你的问题,请参考以下文章

如何访问数组改造 2 / android studio 中的对象“播放器”

如何在 android 中使用改造来解析这个 web 服务?

如何使用 Kotlin 在 Android Studio 的字符串列表中转换 StringBuilder 项?

当应该为真时,Android Studio 改造响应返回布尔值为假

GroovyAndroid Studio 中创建 Groovy 工程 ( 创建 Android Studio 工程 | 创建并改造 Java 依赖库 | 编写 Groovy 代码并运行 )

如何将 localhost 与改造结合使用来测试 android 应用程序 kotlin [重复]