【问题标题】:AsyncTask is still not getting images from rssAsyncTask 仍然没有从 rss 获取图像
【发布时间】:2014-02-14 22:02:03
【问题描述】:

对于Android Studio,我正在尝试显示feed 的图像,但直到现在我还没有做到这一点,我还没有找到解决方案。你能帮我吗? 那是我的Handler

public class RSSHandler extends DefaultHandler {

final int state_unknown = 0;
final int state_title = 1;
final int state_description = 2;
final int state_link = 3;
final int state_pubdate = 4;
int currentState = state_unknown;
ImageView imm;

RSSFeed feed;
RSSItem item;

boolean itemFound = false;

RSSHandler(){
}

RSSFeed getFeed(){
    return feed;
}

@Override
public void startDocument() throws SAXException {
// TODO Auto-generated method stub
    feed = new RSSFeed();
    item = new RSSItem();

}

@Override
public void endDocument() throws SAXException {
// TODO Auto-generated method stub
}

@Override
public void startElement(String uri, String localName, String qName,
                         Attributes attributes) throws SAXException {

// TODO Auto-generated method stub

    if (localName.equalsIgnoreCase("item")){
        itemFound = true;
        item = new RSSItem();
        currentState = state_unknown;
    }
    if ("enclosure".equals(qName)) {
        int i;
        for (i = 0; i < attributes.getLength(); i++)
            if (attributes.getQName(i).equals("url")) ;
        String url = attributes.getValue(i);
        Log.d("mylog", "url= " + url);

        DownloadImagesTask downloadImages = new DownloadImagesTask(imm);
        downloadImages.execute(url);
    }
    else if (localName.equalsIgnoreCase("title")){
        currentState = state_title;
    }
    else if (localName.equalsIgnoreCase("description")){
        currentState = state_description;
    }
    else if (localName.equalsIgnoreCase("link")){
        currentState = state_link;
    }
    else if (localName.equalsIgnoreCase("pubdate")){
        currentState = state_pubdate;
    }
    else{
        currentState = state_unknown;
    }

}

@Override
public void endElement(String uri, String localName, String qName)
        throws SAXException {
// TODO Auto-generated method stub
    if (localName.equalsIgnoreCase("item")){
        feed.addItem(item);
    }
}

@Override
public void characters(char[] ch, int start, int length)
        throws SAXException {
 // TODO Auto-generated method stub

    String strCharacters = new String(ch,start,length);

    if (itemFound==true){
 // "item" tag found, it's item's parameter
        switch(currentState){
            case state_title:
                item.setTitle(strCharacters);
                break;
            case state_description:
                item.setDescription(strCharacters);
                break;
            case state_link:
                item.setLink(strCharacters);
                break;
            case state_pubdate:
                item.setPubdate(strCharacters);
                break;
            default:
                break;
        }
    }
    else{
 // not "item" tag found, it's feed's parameter
        switch(currentState){
            case state_title:
                feed.setTitle(strCharacters);
                break;
            case state_description:
                feed.setDescription(strCharacters);
                break;
            case state_link:
                feed.setLink(strCharacters);
                break;
            case state_pubdate:
                feed.setPubdate(strCharacters);
                break;
            default:
                break;
        }
    }

    currentState = state_unknown;
}

这是我的AsyncTask 班级:

public class DownloadImagesTask extends AsyncTask<String, Void, Bitmap> {

ImageView imageView = null;
String log = null;

public DownloadImagesTask(ImageView imageView){
    this.imageView = imageView;
}


@Override
protected Bitmap doInBackground(String... Urls) {
    return download_Image(Urls[0]);
}

private Bitmap download_Image(String url) {

    Bitmap bmp =null;
    try{
        URL ulrn = new URL(url);
        HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
        InputStream is = con.getInputStream();
        bmp = BitmapFactory.decodeStream(is);
        if (null != bmp)
            return bmp;

    }
    catch(Exception e){
        e.printStackTrace();
        Log.d(log, "url= " + url);
    }
    return bmp;}


@Override
protected void onPostExecute(Bitmap result) {
    imageView.setImageBitmap(result);
}

最后是我的CustomListView

public class CustomList extends ArrayAdapter<RSSItem> {

    private final Activity context;
    private final List<RSSItem> web;
    private String url;
    private AssetManager assets;



    public CustomList(Activity context, List<RSSItem> web) {
        super(context, R.layout.list_item, web);
        this.context = context;
        this.web = web;
        this.url = url;
    }
    @Override
    public View getView(int position, View view, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        final View rowView = inflater.inflate(R.layout.list_item, null, true);


        Typeface myTypeface = Typeface.createFromAsset(context.getAssets(), "BPreplay.otf");


        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        final TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
        txtTitle.setText(web.get(position).getTitle());
        txtTitle.setTypeface(myTypeface);

        final TextView txtTitle2 = (TextView) rowView.findViewById(R.id.item2);
        txtTitle2.setText(web.get(position).getDescription() + "...");
        txtTitle2.setTypeface(myTypeface);

        TextView txtTitle3 = (TextView) rowView.findViewById(R.id.pub);
        txtTitle3.setText(web.get(position).getPubdate());
        txtTitle3.setTypeface(myTypeface);

        final TextView txtTitle4 = (TextView) rowView.findViewById(R.id.linke);
        txtTitle4.setText("vai all'articolo completo -->  " + web.get(position).getLink());
        txtTitle4.setTypeface(myTypeface);

        Button btn = (Button)rowView.findViewById(R.id.btn_share);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, "Leggi " +"''" + txtTitle.getText().toString()
                        + ": " + txtTitle2.getText().toString()
                        + txtTitle4.getText().toString() + "''  " + "Condiviso da Active News");
                sendIntent.setType("text/plain");
                context.startActivity(Intent.createChooser(sendIntent, rowView.getResources().getText(R.string.chooser_title)));
            }
        });
        ImageView img = (ImageView)rowView.findViewById(R.id.immagine_feed);
        DownloadImagesTask downloadImages = new DownloadImagesTask(img);
        downloadImages.execute(url);
        return rowView;

    }

你能帮帮我吗?我真的需要这件事的帮助

【问题讨论】:

    标签: android image android-asynctask rss


    【解决方案1】:

    您应该将 Volley 与 ImageLoader 一起使用,请查看 Volley Tutorial。这是显示从 url 下载的图像的一个非常好的解决方案。如果它已经下载/缓存,它将从缓存中获取,而不是再次下载。

    【讨论】:

    • 我不需要只显示一张图片。我需要展示每篇文章的每一张图片
    • 您使用 getView(...),这意味着您每个列表项显示一个图像。您必须在您的 R.layout.list_item NetworkImageView 中使用,在 getView 中您必须通过图像加载器传递 Volley 的 Url。大多数应用程序都使用这种技术在列表视图中显示图像。
    • 感谢您的建议,无论如何我想知道这段不显示图像的代码有什么问题。
    • 问题是,你的代码不显示图像,每次下载显示图像都需要很多时间。当您缓存它时,它会查看该图像之前是否已下载并从设备获取它,而不是下载它。特别是当你快速滚动时,asyntask 仍然会做它的工作,但是 imageview 已经消失了。
    • 最简单的是什么?我需要快速完成,因为我必须继续使用我的应用程序!我不是很擅长导入其他库
    【解决方案2】:

    您的 DownloadImageTask 很好,尽管您从中引用了 ImageView,但在任务完成时它不再存在。解码位图时,您应该检查解码选项以尽量减少内存使用,例如http://developer.android.com/training/displaying-bitmaps/index.html

    此外,您在适配器上的 getView() 期间没有回收视图,这会减慢 listView 中的滚动速度。正如@Luser_k 指出的那样,检查像 Volley 或 Picasso 这样的库,它们可以为您管理图像下载、正确显示和缓存。非常容易使用。

    例子:

    检查它是否回收了视图,因此从 xml 资源中膨胀视图的次数很少(基本上对于可以放入窗口的 listItems 的数量)。如果您向后滚动或滚动非常快,它将仅使用不同的底层数据重用该视图。您不需要保存对上下文的引用,适配器也有它。删除 asynctask 并使用我的示例 Picasso 中的库。在加载图像之前,还要检查 RssItem.getUrl() 上的空值。相同的适配器可能看起来像这样。不过我没有测试。

    public class CustomList extends ArrayAdapter<RSSItem> {
    
        private final LayoutInflater inflater;
        private final List<RSSItem> data;
        private AssetManager assets;
        Typeface myTypeface;
    
        private final class ViewHolder {
            TextView txt1, txt2, txt3;
            ImageView imageView;
            Button btn;
        }
    
    
    
        public CustomList(Context context, List<RSSItem> data) {
            super(context, R.layout.list_item, data);
            this.inflater = LayoutInflater.from(context);
            this.myTypeface  = Typeface.createFromAsset(context.getAssets(), "BPreplay.otf");
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
    
            final RssItem item = getItem(position);
    
            ViewHolder holder;
    
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.list_item, null, true);
                holder = new ViewHolder();
    
                holder.txt1 = (TextView) convertView.findViewById(R.id.item);
                holder.txt1.setTypeface(myTypeface);
    
                holder.txt2 = (TextView) convertView.findViewById(R.id.item2);
                holder.txt2.setTypeface(myTypeface);
    
                holder.txt3 = (TextView) convertView.findViewById(R.id.pub);
                holder.txt3.setTypeface(myTypeface);
    
                holder.imageView = (ImageView) convertView.findViewById(R.id.immagine_feed);
    
                holder.btn = (Button) convertView.findViewById(R.id.btn_share);
    
                holder.btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent sendIntent = new Intent();
                        sendIntent.setAction(Intent.ACTION_SEND);
                        sendIntent.putExtra(Intent.EXTRA_TEXT, "extra text from holder.txt1,2 etc.");
                        sendIntent.setType("text/plain");
                        getContext().startActivity(Intent.createChooser(sendIntent, convertView.getResources().getText(R.string.chooser_title)));
                    }
                });
    
                convertView.setTag(holder);
    
            }
    
    
            holder = (ViewHolder) convertView.getTag();
            holder.txt1.setText("some text");
            holder.txt2.setText("something else");
            holder.txt3.setText("another text from current item");
    
            Picasso.with(getContext())
                    .load(item.getUrl())
                    .resizeDimen(80, 80)
                    .centerCrop()
                    .error(R.drawable.some_placeholder_image)
                    .placeholder(R.drawable.some_placeholder_image)
                    .into(holder.imageView);
    
    
            return convertView;
        }
    
    }
    

    【讨论】:

    • 也许问得太多了,但你能告诉我如何更改我的代码以适应这些库吗?
    猜你喜欢
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 2019-03-05
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多