【问题标题】:How to save the value of a variable inside a Retrofit call?如何在 Retrofit 调用中保存变量的值?
【发布时间】:2016-12-15 03:30:02
【问题描述】:

我正在尝试使用 Retrofit 调用从标头中检索某个字段的值,以将其发送回服务器。我成功地获取了 try 块中的值,并立即将其发送回 try 块中。但是当我在调用实例之外尝试相同的操作时,abc 的值(这是我分配响应标头值的位置)丢失了。我已经将 String abc 声明为全局变量。如何保存字符串的值?

public class MainActivity extends AppCompatActivity {
    private static final String LOG_TAG = "MainActivityClass";
    String abc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);

        Call<List<TrendingModel>> call = apiService.getAllTodos();
        call.enqueue(new Callback<List<TrendingModel>>() {
            @Override
            public void onResponse(Call<List<TrendingModel>> call, Response<List<TrendingModel>> response) {
                try {

                    List<TrendingModel> todoModels = response.body(); // WHERE WE GET THE RESPONSE BODY
                    abc = response.headers().get("Tanand"); // WHERE WE GET THE RESPONSE HEADER AND ASSIGN IT TO abc, WHICH WE DECLARED GLOBALLY

                    ApiClient.getClient(abc).create(ApiInterface.class); // PASSING THE abc VARIABLE TO THE GETCLIENT(TOKEN) METHOD WITHIN
                                    // THE SAME TRY BLOCK WHICH WORKDS

                } catch (Exception e) {
                    Log.d("onResponse", "There is an error");
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<List<TrendingModel>> call, Throwable t) {
                Log.d("onFailure", t.toString());
            }
        });

        ApiClient.getClient(abc).create(ApiInterface.class); // VALUE OF abc IS NOT PERSISTED HERE (abc IS NULL) ALTHOUGH WE DECLARED IT GLOBALLY
    }
}

【问题讨论】:

    标签: java android oop retrofit retrofit2


    【解决方案1】:

    尝试在 OnResponse 方法中调用方法。

    因为onResponse() 方法在后台运行,直到获取数据。

    如果您想访问响应数据,请在其中调用您的方法

    并且在所有语句之外响应数据完成之前被调用,这就是它不给你实际数据的原因。 作为良好实践,请使用以下方法。

    只需在类中创建一个方法,然后在其中调用所有语句

    现在在 onResponse 方法中调用你的方法

    【讨论】:

      【解决方案2】:

      您可以在 Retrofit 的 onResponse 方法中使用 setter 方法。 这个答案解释了你可以如何去做https://stackoverflow.com/a/63060520/10123715

      【讨论】:

        猜你喜欢
        • 2013-10-07
        • 1970-01-01
        • 2019-02-26
        • 1970-01-01
        • 2020-04-26
        • 1970-01-01
        • 2012-01-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多