java在完成另一个任务后执行一个任务
我有一个方法“getUrls”,它可以通过截取从internet上的json文件中读取数据,并在onCreate方法中返回一个字符串数组,其中包含一些URL。首先,我调用此方法获取URL,然后将URL传递给我的视图寻呼机适配器,以下载毕加索的图像,但getUrls方法尝试下载json文件时出现问题。字符串数组可能是empty,我将空数组传递给适配器,所以在GetURL完成之前应该停止读取代码 以下是我的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 楼答案
问题是您没有等待请求完成,只需要在请求完成时使用URL
创建请求后,将需要调用它以返回结果
首先创建一个回调接口
作为参数接收回调
之后,仅在请求完成时使用字符串列表
1-另外,打开this link了解如何为您的请求队列创建单例