完成另一个任务后执行任务

时间:2018-09-11 16:30:50

标签: java android

我有一个方法“ getUrls”,它通过凌空抽空从Internet中的json文件中读取数据,并在onCreate方法中返回一个包含一些URL的字符串数组,首先我调用此方法以获取URL,然后将URL传递给我的视图寻呼机适配器通过Picasso下载图像,但是有问题getUrls方法正在尝试下载json文件,可能字符串数组为空,并且我将空数组传递给适配器,因此应该停止读取代码,直到getUrls完成 这是我的onCreate方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_production);
    ViewPager viewPager = findViewById(R.id.view_pager);
    ArrayList<String> urls = ImageReader.getImagesUrls(this, "https://myrstcco.000webhostapp.com/productionData.json");
    PagerAdapter adapter = new ProductionViewPagerAdapter(this, urls);
}

这是getUrls方法:

public static  ArrayList<String> getImagesUrls(Context context, String url) {
    final ArrayList<String> urls = new ArrayList<>();
    RequestQueue queue = Volley.newRequestQueue(context);
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray jsonArray = response.getJSONArray("productImagesUrl");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject item = jsonArray.getJSONObject(i);
                            urls.add(item.getString("item"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });

    queue.add(request);

    return urls;
}

这是我的适配器:

public class ProductionViewPagerAdapter extends PagerAdapter {
private Context context;
private ArrayList<String> urls;

public ProductionViewPagerAdapter(Context context, ArrayList<String> urls) {
    this.context = context;
    this.urls = urls;
}

@Override
public int getCount() {
    return urls.size();
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == object;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    ImageView imageView = new ImageView(context);
    Picasso.with(context)
            .load(urls.get(position))
            .fit()
            .centerCrop()
            .placeholder(R.drawable.unknown_person)
            .into(imageView);
    container.addView(imageView);
    return imageView;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView((View) object);
}

1 个答案:

答案 0 :(得分:1)

问题是您没有等待请​​求完成,仅在请求完成时才需要使用网址

创建请求后,需要将其回叫给结果

首先创建一个回调接口

//package your.package.utils;

public interface ICallback<T>{
     void onSucess(T result);
     void onError(String error, int code);
}

将回调作为参数接收

public static void getImagesUrls(final Context context, final String url, final ICallback<ArrayList<String>> callback) {
    RequestQueue queue = Volley.newRequestQueue(context); //Note, improve this using singleton ¹
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        JSONArray jsonArray = response.getJSONArray("productImagesUrl");
                        ArrayList<String> urls = new ArrayList<String>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject item = jsonArray.getJSONObject(i);
                            urls.add(item.getString("item"));
                        }
                        callback.onSucess(urls); //returns the result
                    } catch (JSONException e) {
                        e.printStackTrace();
                        callback.onError(e.toString(),0); //error with the json
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();

            //When get a request error
            callback.onError(error.toString(),error.networkResponse.statusCode);
        }
    });

    queue.add(request);
}

之后,仅在请求完成后使用字符串列表

ImageReader.getImagesUrls(this, "https://myrstcco.000webhostapp.com/productionData.json", new ICallback<ArrayList<String>>() 
{
            @Override
            public void onSucess(ArrayList<String> urls) {
                 PagerAdapter adapter = new ProductionViewPagerAdapter(this, urls);
                 //continue here...
            }
            @Override
            public void onError(String message, int code) {
                 throw new RuntimeException("Error not treated: "+message + " " + code);
            }
}
);

1-另外,打开this link以了解如何为您的请求队列创建单例