简体   繁体   English

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

[英]execute a task after finishing another task

I have a method "getUrls" that read data from a json file in internet by volley and return a string array that contain some urls in onCreate method first I invoke this method to get urls then pass urls to my view pager adapter to download image by picasso but there is problem getUrls method is trying to download json file may string array is empty and I pass empty array to adapter so reading code should be stoped until getUrls coming finish here is my onCreate method:我有一个方法“getUrls”,它通过 volley 从 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);
}

here is getUrls method:这是 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;
}

and here is my adapter:这是我的适配器:

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

The problem is that you are not waiting the request finish, it's need to use the urls only when the request is finished问题是您不是在等待请求完成,只有在请求完成时才需要使用 url

After the request is created will be needed to call it back the result请求创建后需要回调结果

First create a callback interface首先创建一个回调接口

//package your.package.utils;

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

Receive the callback as parameter接收回调作为参数

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

After, only use the list of strings when the request is finished之后,仅在请求完成时使用字符串列表

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 - Also, open this link to know how to create singleton for your request queue 1 - 另外,打开此链接以了解如何为您的请求队列创建单例

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

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