应用程序在以慢速连接下载图像时在一段时间后停止



在我的应用程序中,我从服务器获取图像和数据。当互联网连接时,图像已正确加载。当互联网连接速度减慢时,应用程序会继续运行,过了一段时间就会突然停止。

这是AsyncTask,用于从服务器获取图像和数据

public void getPendingList() {
    new AsyncTask<Void, Void, String>() {
        protected void onPreExecute() {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setTitle("Loading....");
            progressDialog.setMessage("Please Wait...");
            progressDialog.setCancelable(true);
            progressDialog.show();
        }
        protected String doInBackground(Void... params) {
            prepareList();
            getRegistrationDetails();
            getStateList();
            for (int i = 0; i < districts.size(); i++) {
                JSONObject jsonObject;
                try {
                    jsonObject = new JSONObject(districts.get(i));
                    String val1 = jsonObject.getString("OptionalParameter");
                    int val2 = jsonObject.getInt("ItemID");
                    String val3 = jsonObject.getString("Item_Description");
                    double val4 = jsonObject.getDouble("Item_Price");
                    String val5 = jsonObject.getString("Item_Code");
                    String val6 = jsonObject.getString("Item_Name");
                    String val7 = jsonObject.getString("ImageFinal");
                    String ItemCode = jsonObject.getString("Item_Code");
                    val7.replace("/", "");
                    listmodel.add(new Item_Master(val2, val3, val4, val6, val7, ItemCode));
                    listCountry.add("u20B9" + val4);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return "response";
        }
        protected void onPostExecute(String result) {
            if (result != null) {
                if (!result.equals("NO_NETWORK")) {
                    mAdapter = new GridviewAdapter_Item_Master(FaramentView.getContext(), listmodel);
                    gridview.setAdapter(mAdapter);
                }
                dismissDialog();
            }
        }.execute(null, null);
    }
}

在得到这些数据后,我在这个数据中设置了GridView适配器,并设置了图像。我使用Picasso库下载图像并设置以下代码:

Picasso.with(context).load(list.get(position).getImagePath()).centerCrop()
    .resize(150, 150).error(R.drawable.ic_launcher).into(view.imgViewFlag);

如何加载图像,即使在缓慢的互联网连接?

您可能会得到一个ANR,这意味着您会收到一个
UI超时,因为您试图在和AsyncTask中更新UI的应用程序组件(但请记住,要用doInBackground()方法管理后台网络处理);要更新UI应用程序组件,可以使用Handlers或通过runOnUiThread() 进行更新

最新更新