我正在设计一种加密货币跟踪器,该基本URL不适用于我需要的特定数据。我读到我的错误很可能是由于API URL调用不正确引起的。
错误
java.lang.NullPointerException: Attempt to invoke interface method
'java.lang.Object java.util.List.get(int)' on a null object reference
基本网址
https://rest.coinapi.io/
http请求
GET /v1/symbols?filter_symbol_id={filter_symbol_id}
我的代码
String BASE_URL = "https://rest.coinapi.io/";
@GET("v1/symbols")
Call<List<Coin>> getCoin(@Query("filter_symbol_id") String filter_symbol_id);
}
代码调用API
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
final ListView listView = findViewById (R.id.listView);
Retrofit retrofit = new Retrofit.Builder ()
.baseUrl (Api.BASE_URL)
.addConverterFactory (GsonConverterFactory.create ())
.build ();
Api api = retrofit.create (Api.class);
Call<List<Coin>> call = api.getCoin ("filter_symbol_id");
call.enqueue (new Callback<List<Coin>> () {
@Override
public void onResponse(Call<List<Coin>> call,
Response<List<Coin>> response) {
List<Coin> coin = response.body ();
String[] coinName = new String[10];
for (int i = 0; i < 10; i++) {
coinName[i] = coin.get (i).getsymbol_id ();
listView.setAdapter (
new ArrayAdapter<String> (
getApplicationContext (),
android.R.layout.simple_list_item_1,
coinName
)
);
}
}
@Override
public void onFailure(Call<List<Coin>> call, Throwable t) {
Toast.makeText (getApplicationContext (), t.getMessage (),
Toast.LENGTH_SHORT).show ();
}
});
}
}
Coin.java
package com.dev20tx.android.cryptohero;
public class Coin {
private String symbol_id;
public Coin(String symbol_id) {
this.symbol_id = symbol_id;
}
public String getsymbol_id() {
return symbol_id;
}
}
我发现了许多有用的stackoverflow帖子,这些帖子可以帮助我获取其他数据,但这使我感到困惑。有人可以指出我正确的方向吗?
已解决的问题:我使用了另一个URL“ v1 / assets”,该URL修复了NullPointerException,更新了我在Java文件中的代码,并且可以正常工作。出于某些原因,coinapi.io
目前无法使用API v1 / symbols答案 0 :(得分:1)
您丢失了api_key
@GET("v1/symbols")
Call<List<Coin>> getCoin(@Query("filter_symbol_id") String filter_symbol_id, @Query("apikey") String apiKey);
有关更多信息,请访问https://docs.coinapi.io/#authorization
答案 1 :(得分:0)
该错误必须在您的Coin
类中。因此,请发布Coin.class
。我认为NullPointerException
是因为GSON
无法序列化Coin
对象,可能是@SerializedName("")
丢失了。否则显示Coin.class
代码。 (请记住也缺少apikey
参数,因此响应将为401 Unauthorized
,但不会引起任何NullPointerException
。)
package com.dev20tx.android.cryptohero;
public class Coin {
@SerializedName("symbol_id") //replace with your response field.
private String symbol_id;
public Coin(String symbol_id) {
this.symbol_id = symbol_id;
}
public String getsymbol_id() {
return symbol_id;
}
}