简体   繁体   English

使用 getter setter 初始化 List

[英]Initialize List using getter setter

I am trying to initialize a List using setter method in same class when I will receive a response but when I called getter from other class its returning an empty list.我正在尝试在相同的 class 中使用 setter 方法初始化列表,当我收到响应时,但是当我从其他 class 调用 getter 时,它返回一个空列表。 Is it technically possible what I'm trying to achieve?我想要达到的目标在技术上是否可行?

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;
}
}

and where I'm calling it is我叫它的地方是

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

When I checked the list.size() using toast or Log.d it show 0 item.当我使用 toast 或 Log.d 检查 list.size() 时,它显示 0 项。

Since its an asynchronous call and you are trying to retrieve the list immediately after it then one possible way is to return the list after setting from the getAllCategory() method itself.由于它是一个异步调用,并且您试图在它之后立即检索列表,因此一种可能的方法是在从 getAllCategory() 方法本身设置后返回列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM