使用getter setter初始化列表

问题描述 投票:0回答:1

当我收到响应时,我试图在同一类中使用setter方法初始化一个List,但是当我从其他类中调用getter时,它返回一个空列表。从技术上讲,我试图达到的目标是否可行?

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


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


public void getAllCatagory()
{
    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.catagoriesItem(endUrl,token).enqueue(new Callback<List<CatagoryCommonResponse>>() {
        @Override
        public void onResponse(Call<List<CatagoryCommonResponse>> call, Response<List<CatagoryCommonResponse>> response)
        {
            if (response.isSuccessful())
            {
                List<CatagoryCommonResponse> item = response.body();
                Toast.makeText(context, "Iam called", Toast.LENGTH_SHORT).show();
                setItem(item);




            }
        }

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


        }
    });



}


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

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

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

以及我在哪里叫它

CatagoryCommonAPI commonAPI=new CatagoryCommonAPI(this,endUrl,list);
      commonAPI.getAllCatagory();
      list=commonAPI.getItemq();

当我使用Toast或Log.d检查list.size()时,它显示0个项目。

java android
1个回答
0
投票
由于它是异步调用,并且您试图在列表之后立即检索列表,所以一种可能的方法是从getAllCatagory()方法本身设置后返回列表。
© www.soinside.com 2019 - 2024. All rights reserved.