如何在androidstudio中使用retofit检索数据

biswetbf  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(513)
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"}}}}

下面是我在androidstudio中从上面的api获取数据的代码

my pojo classes

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;
    }
}

myactivity

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();

    enter code here
            }
        });

    }
}

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,时间为零。

dgjrabp2

dgjrabp21#

API 你没有得到完全正确的答案 CurrencyModel 作为回应。你得到的另一个物体是 CurrencyModel 是子对象。必须创建如下所示的resposne对象:

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);
}

相关问题