使用AsyncTask未显示RSS提要图像

时间:2014-02-09 21:23:28

标签: android image url android-asynctask rss

我正在使用AsyncTask尝试显示rss Feed的图片。我正在从url抓取RSSHandler这些图片,我希望图片能够显示在我的自定义ListView中,但没有任何内容。你可以帮帮我吗?我坚持这个。 这是LogCat中的消息:

FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:299)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
        at java.util.concurrent.FutureTask.run(FutureTask.java:239)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
        at java.lang.Thread.run(Thread.java:856)
 Caused by: java.lang.NullPointerException: println needs a message
        at android.util.Log.println_native(Native Method)
        at android.util.Log.d(Log.java:138)
        at com.riccardo.myapplication.DownloadImagesTask.download_Image(DownloadImagesTask.java:42)
        at com.riccardo.myapplication.DownloadImagesTask.doInBackground(DownloadImagesTask.java:20)
        at com.riccardo.myapplication.DownloadImagesTask.doInBackground(DownloadImagesTask.java:13)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask.run(FutureTask.java:234)

这是我的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);

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

这是我的自定义ListView已编辑):

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;

    }


  }

1 个答案:

答案 0 :(得分:0)

问题出现在这里:

@Override
protected Bitmap doInBackground(ImageView... imageViews) {
    this.imageView = imageViews[0];
    return download_Image((String)imageView.getTag());
}

download_Image将网址作为字符串参数,为什么要传递imageView.getTag();

将您的asyncTask更改为以下内容:

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

ImageView imageView = null;

public DownloadImagesTask(ImageView imageView){
//Put logic you need in the constructor
this.imageView = imageView;
}


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

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

}

因此,当您调用它时,您会将imageView传递给构造函数,然后将string url传递给asyntask的执行方法:

DownloadImagesTask downloadImages = new DownloadImagesTask(someImageView);
downloadImages.execute("http://www.yoururl.com/api/");

编辑:

在获得url和imageview之后立即运行任务。

public CustomList(Activity context, List<RSSItem> web, String url) {
    super(context, R.layout.list_item, web);
    this.context = context;
    this.web = web;
    this.url = url;
}

DownloadImagesTask downloadImages = new DownloadImagesTask(img);
downloadImages.execute(url);

确保您有一个网址Log.d(log, "url= " + url);