我正在尝试将AutoCompleteTextView与Json一起使用,并且正在使用本教程:this
当我尝试向列表中添加数据时出现问题: foreach不适用于类型'com.example.program.model.Result'。下面是AutoCompleteTextView的模型数据和代码,我为Example模型添加了代码。
private void DownloadGames() {
final AlertDialog alertDialog = new SpotsDialog.Builder()
.setContext(MainActivity.this)
.setTheme(R.style.CustomDialog)
.build();
alertDialog.setMessage("Loading Data... Please wait...");
alertDialog.setCancelable(true);
alertDialog.show();
Retrofit retrofit = GamesClient.getRetrofitClient();
GamesInterface gamesInterface = retrofit.create(GamesInterface.class);
Call call = gamesInterface.getGamesbyName(gameTitle.getText().toString(), SPINNER_POSITION);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
alertDialog.dismiss();
if (response.body() != null) {
Example example = (Example) response.body();
List<String> strings= new ArrayList<String>();
for(Result result: ((Example) response.body()).getResult()){
strings.add(result.getTitle());
}
ArrayAdapter<String> adapteo = new ArrayAdapter<String>(getBaseContext(),
android.R.layout.simple_dropdown_item_1line, strings.toArray(new String[0]));
storeTV.setAdapter(adapteo);
contentTitle.setText(example.getResult().getReleaseDate());
...
}
模型
public class Result {
@SerializedName("title")
@Expose
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
public class Example {
@SerializedName("result")
@Expose
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
}
答案 0 :(得分:0)
您希望看到对象列表,但在示例类中观察单个对象。如果您的API抛出结果列表,请使用
更改Example类public class Example {
@SerializedName("result")
@Expose
private List<Result> result;
public List<Result> getResult() {
return result;
}
public void setResult(List<Result> result) {
this.result = result;
}
}
并更改此行
for(Result result: ((Example) response.body()).getResult()){
strings.add(result.getTitle());
}
与
for(Result result: example.getResult()){
strings.add(result.getTitle());
}