【问题标题】:How to store variable from a callback to a global class variable如何将变量从回调存储到全局类变量
【发布时间】: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


【解决方案1】:

这个问题主要是因为网络请求是异步的。您想要做的是从 callListOfMoviesApi 返回 LiveData 并在您观察结果的调用者中。你可以有这样的东西

public LiveData<String> callListOfMoviesApi(Context context) { 

// declare you LiveData<String>
MutableLiveData<String> posterPath = new MutableLiveData<>();

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(); 
        if(result != null){ 
           // Add the result to your LiveData 
          posterPath.postValue(result.getResults().get(0).getPosterPath();); 
        } 
        // 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();
    }
});

return posterPath;}

在调用者中你可以观察到这样的结果

callListOfMoviesApi(context).observe(getViewLifecycleOwner(), posterPath -> {
                            // use your posterPath
                            if(posterPath != null)
                                Log.i("PosterPath", posterPath);
                        });

有关 LiveData 的更多信息,请参阅here

【讨论】:

    猜你喜欢
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多