android - 获取“尝试获取空数组的长度”错误
问题描述
我收到“尝试获取空数组的长度”错误。当我尝试单击按钮时,我试图从链接https://gturnquist-quoters.cfapps.io/api/random获取随机引号:键入“成功”值
id 7 引用“引导的真正好处,但是,它只是 Spring。这意味着代码采用的任何方向,无论复杂性如何,我都知道这是一个安全的选择。
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btnCallRestApi;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnCallRestApi = findViewById(R.id.btnCallRestApi);
btnCallRestApi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//call Rest Api
new HttpReqTask().execute();
}
});
}
private class HttpReqTask extends AsyncTask<Void, Void, Value[]> {
@Override
protected Value[] doInBackground(Void... params){
try{
String apiUrl = "https://gturnquist-quoters.cfapps.io/api/random";
RestTemplate rest = new RestTemplate();
rest.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
Value[] quotes = rest.getForObject(apiUrl, Value[].class);
return quotes;
}catch (Exception ex){
Log.e("Could not get Quotes",ex.getMessage());
}
return null;
}
protected void onPostExecute(Value[] quotes){
super.onPostExecute(quotes);
for(Value v:quotes){
Log.i("id: ", String.valueOf(v.getId()));
Log.i("quote: ", v.getQuote());
}
}
}
}
引用.java
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
@Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
价值.java
public Value() {
}
public Long getId() {
return this.id;
}
public String getQuote() {
return this.quote;
}
public void setId(Long id) {
this.id = id;
}
public void setQuote(String quote) {
this.quote = quote;
}
@Override
public String toString() {
return "Value{" +
"id=" + id +
", quote='" + quote + '\'' +
'}';
}
解决方案
您正在尝试对触发 a 的空数组执行循环NPE
,尝试使用try/catch
子句处理它
protected void onPostExecute(Value[] quotes){
super.onPostExecute(quotes);
try {
for(Value v:quotes){
Log.i("id: ", String.valueOf(v.getId()));
Log.i("quote: ", v.getQuote());
}
} catch (NullPointerException e) {
System.out.print("Caught the NullPointerException");
}
编辑新问题:
我认为您错误地阅读了 JSON OBJECT !
推荐阅读
- regex - 用随机字符串向后看 - 解决方法?
- webrtc-android - Android webrtc SIGSEGV 错误
- javascript - 从以编程方式注入的 Chrome 扩展程序中的弹出窗口链接到选项页面
- azure - netcoreapp2.1升级到3.1导致502.5错误
- java - 这是我的代码中的错误还是 cellfactory 的问题
- c# - 如何在 Blazor 的 .razor 文件中使用 Html Helper 方法
- c - 将数据从一个指针复制到另一个指针,但未在 c 中复制完整数据
- git - Git:删除目录并使更改对所有当前分支可见
- office-addins - 从 Sharepoint 读取 Word 文档并在 Word 中显示
- nuxt.js - 如何更新嵌套的 Apollo Cache 3+ 级别?