【发布时间】:2021-10-12 03:22:54
【问题描述】:
我尝试将回调函数中的值放入类全局变量(posterPath)中...但是当我放入并打印类变量(posterPath)时,它输出'null'...请问什么是正确的方法将值存储在类全局变量中
类全局变量:public String posterPath;
值:posterPath = result.getResults().get(0).getPosterPath();
完整代码:
public void callListOfMoviesApi(Context context) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(credentials.BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
MovieApi movieApi = retrofit.create(MovieApi.class);
Call<PopularMovieModel> call = movieApi.listOfMovies(category, credentials.ApiKey);
call.enqueue(new Callback<PopularMovieModel>() {
@Override
public void onResponse(Call<PopularMovieModel> call, Response<PopularMovieModel> response) {
PopularMovieModel result = response.body();
posterPath = result.getResults().get(0).getPosterPath();
// Toast.makeText(context, "response" + posterPath, Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<PopularMovieModel> call, Throwable t) {
t.printStackTrace();
}
});
}
更新:我研究了很多,发现我的全局变量输出 null 因为全局变量在主线程中被调用,并且改造还没有为变量赋值。 (我使用了 Thread.sleep() 并且值不为空)。但我怀疑这是一种不好的做法。等待将改造结果分配给全局变量的最佳方法是什么?
【问题讨论】:
-
这表明你的服务器响应给你空值。
result.getResults().get(0).getPosterPath()- 您确认您的 API 响应实际上是您认为应该的吗? -
@dominicoder 是的,我已经使用 Toast 确认了服务器响应,它给出了预期的结果..
-
另外,当我隐式添加诸如: posterPath = "hello" ... 然后打印 posterPath 全局变量时,我仍然得到 null。
标签: java android android-studio oop retrofit