gpt4 book ai didi

java - Android/Java 改造 : Class cannot be converted to Callback

转载 作者:太空宇宙 更新时间:2023-11-03 12:50:11 27 4
gpt4 key购买 nike

我是改造新手,我正在尝试获取对名为 RootObject 的对象的 json 响应。我遇到的错误是:

"Error:(21, 44) error: incompatible types: NewsController cannot be converted to Callback>"

有人现在在这里犯了我的错误吗?谢谢你的问候!

public class NewsController {
public void getNews(){
Retrofit retrofit = new Retrofit.Builder().baseUrl("apilink").addConverterFactory(GsonConverterFactory.create()).build();
GetNewsService service = retrofit.create(GetNewsService.class);
try {
service.GetNewsItems().enqueue(this); //asynchronous
Response<List<RootObject>> response = service.GetNewsItems().execute(); //synchronous
}
catch (IOException e){

}
}
}

放置数据的类:

public class RootObject implements Serializable {
public ArrayList<Result> results ;
public int nextId;

public ArrayList<Result> getResults() { return results; }
public int getNextId() { return nextId; }

public String toString() {
return String.format("JEEJ" + nextId);
}
}

接口(interface):

public interface GetNewsService {
@GET("/Articles")
Call<List<RootObject>> GetNewsItems();
}

最佳答案

首先,将您的界面更改为:

public interface GetNewsService { 
@GET("/Articles")
void GetNewsItems(Callback<List<RootObject>> cb);
}

同时更改您的 newsController 类。

public class NewsController {
private RestAdapter restAdapter;
static final String API_URL = "[Enter your API base url here]";
public void getNews(){
OkHttpClient mOkHttpClient = new OkHttpClient();
mOkHttpClient.setConnectTimeout(15000,TimeUnit.MILLISECONDS);
mOkHttpClient.setReadTimeout(15000,TimeUnit.MILLISECONDS);
restAdapter = new RestAdapter.Builder().setEndpoint(API_URL).setClient(new OkClient(mOkHttpClient)).setLogLevel(RestAdapter.LogLevel.FULL) .build();
GetNewsService service = restAdapter.create(GetNewsService.class);

Callback<List<RootObject> cb = new Callback<List<RootObject>>() {
@Override
public void success(List<RootObject> rootObjectList, Response response) {
//whatever you want to do with the fetched news items
}

@Override
public void failure(RetrofitError error) {
//whatever you want to do with the error
}
};
service.GetNewsItems(cb);
}
}

您需要在 build.gradle 中添加以下依赖项:

compile 'com.squareup.retrofit:retrofit:1.9.0'
compile 'com.google.code.gson:gson:2.3.1'
compile 'com.squareup.okhttp:okhttp:2.4.0'

关于java - Android/Java 改造 : Class cannot be converted to Callback,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33168352/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com