当我在学习Dagger2
时,我创建了一个天真的服务类,它以异步方式提供数据(在这种情况下是来自funny api的笑话)但是我遇到了一个问题而且我有点困惑。我正在使用retrofit2
从网络请求数据。
但我无法弄清楚如何从网络中检索<{1}} joke
对象(通过response.body()
),从匿名内部类转移到joke
外部类的实例变量。我得到了NullPointerException
:
public class ChuckNorrisJokeService {
private Joke joke;
public String getJoke() {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://api.chucknorris.io")
.build();
JokeService jokeService = retrofit.create(JokeService.class);
Call<Joke> call = jokeService.provideJoke();
call.enqueue(new Callback<Joke>() {
@Override
public void onResponse(Call<Joke> call, Response<Joke> response) {
joke = response.body();
}
@Override
public void onFailure(Call<Joke> call, Throwable t) {
System.out.println(t.getMessage());
}
});
return joke.getContent();
}
}
Joke
类是一个简单的POJO:
public class Joke {
@SerializedName("value")
private String content;
public String getContent() {
return content;
}
}
P.S。同步调用时结果成功。 如何异步实现相同的功能?
P.S.S。我读过this但它对我不起作用而且太脏了。
堆栈跟踪是这样的:
Exception in thread "main" java.lang.NullPointerException
at com.alic.ChuckNorrisJokeService.getJoke(ChuckNorrisJokeService.java:41)
at com.alic.Application.run(Application.java:11)
at com.alic.Main.main(Main.java:6)
Application
和Main
类非常简单:
public class Application {
private ChuckNorrisJokeService chuckNorrisJokeService;
public Application() {
this.chuckNorrisJokeService = new ChuckNorrisJokeService();
}
public void run() {
System.out.println(chuckNorrisJokeService.getJoke());
}
}
和Main
类:
public class Main {
public static void main(String[] args) {
Application app = new Application();
app.run();
}
}