如何使用asynctask从列表视图中的URL加载图像

时间:2015-12-11 07:09:42

标签: android listview android-asynctask

到目前为止,我已经做了很多。请你帮我看一下在listview中加载图片后要做什么。我使用xml解析解析了url。我只想在listview中加载图像。请帮帮我专家!!

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

3 个答案:

答案 0 :(得分: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

            }});

答案 1 :(得分:0)

在你的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);

答案 2 :(得分:0)

我建议您使用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?