簡體   English   中英

使用 getter setter 初始化 List

[英]Initialize List using getter setter

我正在嘗試在相同的 class 中使用 setter 方法初始化列表,當我收到響應時,但是當我從其他 class 調用 getter 時,它返回一個空列表。 我想要達到的目標在技術上是否可行?

public class CategoryCommonAPI
{
    private Context context;
    private String endUrl;
    private UserAccessToken userAccessToken;
    private String ITV_BASE_URL;
    private  List<CategoryCommonResponse> itemq;


    public CategoryCommonAPI(Context context, String endUrl, List<CategoryCommonResponse> itemq)
    {
         this.context = context;
         this.endUrl = endUrl;
         this.itemq = itemq;
         ITV_BASE_URL = context.getString(R.string.baseUrl);
         userAccessToken = new UserAccessToken(context);
    }

    public void getAllCategory()
    {
        Toast.makeText(context, "Iam thanos", Toast.LENGTH_SHORT).show();

        String token ="Bearer "+userAccessToken.getAccessToken();
        final ITV_API_Service itvApiService = RetrofitClient.getClient(ITV_BASE_URL).create(ITV_API_Service.class);
        itvApiService.categoriesItem(endUrl,token).enqueue(new Callback<List<CategoryCommonResponse>>() {
        @Override
        public void onResponse(Call<List<CategoryCommonResponse>> call, Response<List<CategoryCommonResponse>> response)
        {
            if (response.isSuccessful())
            {
                List<CategoryCommonResponse> item = response.body();
                Toast.makeText(context, "Iam called", Toast.LENGTH_SHORT).show();
                setItem(item);




            }
        }

        @Override
        public void onFailure(Call<List<CategoryCommonResponse>> call, Throwable t)
        {
            Toast.makeText(context, "Image response failed", Toast.LENGTH_SHORT).show();


        }
    });
}

private void setItem(List<CategoryCommonResponse> item)
{
    this.itemq= item;

    Log.d("List size", "setItem: "+item.size());
    Log.d("Return List", "setItem: "+itemq.size());
}

public List<CategoryCommonResponse> getItemq()
{
    return this.itemq;
}
}

我叫它的地方是

CategoryCommonAPI commonAPI = new CategoryCommonAPI(this, endUrl, list);
      commonAPI.getAllCategory();
      list=commonAPI.getItemq();

當我使用 toast 或 Log.d 檢查 list.size() 時,它顯示 0 項。

由於它是一個異步調用,並且您試圖在它之后立即檢索列表,因此一種可能的方法是在從 getAllCategory() 方法本身設置后返回列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM