简体   繁体   中英

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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