【问题标题】:How to load an image from url in a listview using asynctask如何使用 asynctask 从列表视图中的 url 加载图像
【发布时间】:2015-12-11 07:09:41
【问题描述】:

到目前为止,我已经做了很多。请你帮我在列表视图中加载图像下一步该怎么做。我已经使用 xml 解析解析了 url。我只想在列表视图中加载图像。请高手帮帮我!!

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);

        Bundle b = getIntent().getExtras();

        m_brandName = b.getString("Brand_Name");
        m_modelName = b.getString("Model_Name");
        m_categoryName = b.getString("Category_Name");

        actAppChartCatList = this;
        //String url = "http://www.bitstechnologies.in/HellaWebserviceV2/Service1.asmx/populateBrandModelCategory?brandName=\" + m_brandName + \"&\" + \"modelName=\" + m_modelName + \"&\" + \"categoryName=\" + m_categoryName";
        String url = "http://www.bitstechnologies.in/HellaWebserviceV2/Service1.asmx/populateBrandModelCategory?brandName=" + m_brandName + "&modelName=" + m_modelName + "&categoryName=" + m_categoryName;
        String urlFinal = "";
        if (url.contains(" "))
            urlFinal = url.replace(" ", "%20");
        else
            urlFinal = url;

        //new DownloadTaskCV().execute("http://www.bitstechnologies.in/HellaWebserviceV2/Service1.asmx/populateBrandModelCategory?brandName=" + m_brandName + "&" + "modelName=" + m_modelName + "&" + "categoryName=" + m_categoryName);
        new DownloadTaskCV().execute(urlFinal);
        pdGettingProducts = ProgressDialog.show(ActivityAppChartToCategoryList.this, "", "Getting Products.......");
        setContentView(R.layout.activity_activity_app_chart_to_category_list);
        mListView = (ListView) findViewById(R.id.showProductLists);
    }

    public static ActivityAppChartToCategoryList getInstance() {
        return actAppChartCatList;
    }

    public void progDialogDownloadingDismiss() {
        if (pdGettingProducts != null) {
            pdGettingProducts.dismiss();
        }

    }

    public void showEmptyMessage() {

        progDialogDownloadingDismiss();
        adb = new AlertDialog.Builder(this);
        adb.setTitle("");
        adb.setMessage("No products");
        adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                onBackPressed();
            }
        });
        adb.show();

    }

    /*
     * A method to download json data from url
     */
    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        try {

            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();


            Log.e("Response code : ", "" + urlConnection.getResponseCode());

            // Reading data from url
            iStream = urlConnection.getInputStream();


            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            data = sb.toString();
            br.close();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            iStream.close();
        }

        //pdDownloadingList.dismiss();
        return data;
    }

    private class DownloadTaskCV extends AsyncTask<String, Integer, String> {
        String data = null;
        Product product = null;
        ArrayList<Product> productslist = null;
        @Override
        protected String doInBackground(String... url) {
            try {
                data = downloadUrl(url[0]);

            } catch (Exception e) {
                e.printStackTrace();
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
            //super.onPostExecute(result);
            try {
                if ((result.equalsIgnoreCase("[]")) || (result == null)) {
                    showEmptyMessage();
                    this.cancel(true);
                }

                parseXmlResponse(result);

            } catch (Exception e) {
                showEmptyMessage();
                this.cancel(true);
            }
        }

        private String parseXmlResponse(String xmlResponse) {
            if (xmlResponse != null) {
                XmlPullParser myParser;
                XmlPullParserFactory xmlFactoryObject;

                try {

                    xmlFactoryObject = XmlPullParserFactory.newInstance();
                    myParser = xmlFactoryObject.newPullParser();
                    myParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);

                    int event;
                    String text = null;

                    event = myParser.getEventType();
                    while (event != XmlPullParser.END_DOCUMENT) {
                        String name = myParser.getName();
                        switch (event) {
                            case XmlPullParser.START_TAG:
                                if (name.equalsIgnoreCase("ProductList")) {
                                    // instantiate Arraylist of "Products"
                                    productslist = new ArrayList<>();
                                }
                                if (name.equalsIgnoreCase("Product_Name")) {
                                    // instantiate object of Product
                                    product = new Product();
                                }
                                break;

                            case XmlPullParser.TEXT:
                                text = myParser.getText();
                                break;

                            case XmlPullParser.END_TAG:

                                if (name.equalsIgnoreCase("Product_Name")) {
                                    // prodObj.setProductName(text)
                                    product.setProducts_name(text);
                                }

                                if (name.equalsIgnoreCase("Product_Image_Left")) {
                                    // prodObj.setProductImageLeft(text)
                                    product.setProducts_image(text);
                                    // add the product object to the array List
                                    productslist.add(product);
                                }
                                break;

                            default:
                                break;

                        } // end of switch
                        event = myParser.next();
                    }

                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return xmlResponse;
        }
    }

【问题讨论】:

  • 为什么你不能使用像 Picasso 这样的 ImageLoading 库 ....
  • 谢谢@RameshBhupathi....这是一个简单的方法吗?
  • 我还需要为那个写异步任务吗?
  • 不,它将处理默认值。
  • 你能告诉我在上面给出的文件中我应该把毕加索的代码行放在哪里吗?

标签: android listview android-asynctask


【解决方案1】:

您还可以使用开放资源Universal Image Loader.UIL 旨在为图像加载、缓存和显示提供强大、灵活和高度可定制的工具。它提供了很多配置选项以及对图像加载和缓存过程的良好控制。

就这样(用起来这么简单):

ktvIconImg = (RoundImageView) convertView
                    .findViewById(R.id.ktv_icon_img);


ImageLoader.getInstance().displayImage(url, ktvIconImg, mOptions,new ImageLoadingListener() {

            @Override
            public void onLoadingStarted(String arg0, View arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onLoadingCancelled(String arg0, View arg1) {
                // TODO Auto-generated method stub

            }});

【讨论】:

    【解决方案2】:

    在你的 gradle 中添加这个

     compile "com.squareup.picasso:picasso:2.4.0"
    

    在您的适配器或活动中

    Picasso.with(this)
     .load("YOUR IMAGE URL HERE")        
     .placeholder(R.drawable.ic_placeholder)   // optional        
     .error(R.drawable.ic_error_fallback)      // optional        
     .resize(250, 200)                        // optional        
     .rotate(90)                             // optional        
     .into(imageView);
    

    【讨论】:

      【解决方案3】:

      我建议您使用Picasso 库。使用起来非常简单。

       Picasso.
                with(YourActivityName).
                load("Your image url").
                into(YourImageView); 
      

      这是一篇非常好的文章。 https://www.bignerdranch.com/blog/solving-the-android-image-loading-problem-volley-vs-picasso/

      参考:

      1. Why use Android Picasso library to download images?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多