2014-09-27 5 views
1

В основном я использую DOM Parser для извлечения заголовка, описания, pubDate и миниатюр из RSS-ленты в виде списка. Вот мой пример кода.Невозможно декодировать поток: fileNotFoundException

public ArrayList<HashMap<String, String>> processXML(
       InputStream inputStream) throws Exception { 
       DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory 
       .newInstance(); 
       DocumentBuilder documentBuilder = documentBuilderFactory 
       .newDocumentBuilder(); 
       Document xmlDocument = documentBuilder.parse(inputStream); 
       Element rootElement = xmlDocument.getDocumentElement(); 
       L.m("" + rootElement.getTagName()); 
       NodeList itemsList = rootElement.getElementsByTagName("item"); 
       NodeList itemChildren = null; 
       Node currentItem = null; 
       Node currentChild = null; 
       NamedNodeMap mediaThumbnailAttr = null; 
       Node currentAttribute=null; 
       int count = 0; 
       ArrayList<HashMap<String, String>> results = new ArrayList<>(); 
       HashMap<String, String> currentMap = null; 
       for (int i = 0; i < itemsList.getLength(); i++) { 
       currentItem = itemsList.item(i); 
       itemChildren = currentItem.getChildNodes(); 
       currentMap = new HashMap<>(); 
       for (int j = 0; j < itemChildren.getLength(); j++) { 
       currentChild = itemChildren.item(j); 
       if (currentChild.getNodeName().equalsIgnoreCase("title")) { 
       // L.m(currentChild.getTextContent()); 
       currentMap.put("title", currentChild.getTextContent()); 
       } 
       if (currentChild.getNodeName().equalsIgnoreCase("pubDate")) { 
       // L.m(currentChild.getTextContent()); 
       currentMap 
       .put("pubDate", currentChild.getTextContent()); 
       } 
       if (currentChild.getNodeName().equalsIgnoreCase(
       "description")) { 
       // L.m(currentChild.getTextContent()); 
       currentMap.put("description", 
       currentChild.getTextContent()); 
       } 

       if(currentChild.getNodeName().equalsIgnoreCase("media:thumbnail")){ 
        //L.m(""+currentChild.getTextContent()); 
        mediaThumbnailAttr = currentChild.getAttributes(); 
        for(int k=0;k<mediaThumbnailAttr.getLength(); 
          k++){ 
         currentAttribute = mediaThumbnailAttr.item(k); 
         if(currentAttribute.getNodeName() 
           .equalsIgnoreCase("url")){ 
          count++; 

          //L.m(currentChild.getAttributes().item(0).getTextContent()); 

         } 
         //L.m(); 
         currentMap.put("imageURL", currentChild 
       .getAttributes().item(0).getTextContent()); 
        } 
        count=0; 
       } 
       } 
       if (currentMap != null && !currentMap.isEmpty()) { 
       results.add(currentMap); 
       } 
       count = 0; 
       } 
       return results; 
       } 
       } 
     } 

Первые три метки считываются правильно мой parser..But эскиз дает мне проблему, и бросает мне исключение ...

 Unable to decode stream: java.io.FileNotFoundException: 
      /http:/i.dailymail.co.uk/i/pix/2014/09/27/1411832985119_Puff_Image_galleryImage_SUNDERLAND_ENGLAND_SEPTEM.JPG: open failed: ENOENT (No such file or directory). 

Есть ли какие-либо проблемы с setImageURI (Uri.parse (currentItem.get ("ImageUrl")));

+0

Только одно, что я могу заметить: дополнительные «/» в начале URL. Это должно быть «http://i.dailymail.co.uk/i/pix/2014/09/27/1411832985119_Puff_Image_galleryImage_SUNDERLAND_ENGLAND_SEPTEM.JPG». Не "/http://i.dailymail.co.uk/i/pix/2014/09/27/1411832985119_Puff_Image_galleryImage_SUNDERLAND_ENGLAND_SEPTEM.JPG" –

+0

Я знаю. Если я удалю файл holder.articleImage.setImageURI (Uri.parse (currentItem.get ("imageURL"))); внутри метода getView моего адаптера я не вижу никаких исключений. Но опять-таки изображение не отображается в списке. – Theo

+0

Правильно .. Но вы получаете неправильный URL-адрес. Пожалуйста, проверьте это. Для целей тестирования вы можете попробовать hardcoded url, например: 'holder.articleImage.setImageURI (Uri.parse (" http: /i.dailymail.co.uk/i/pix/2014/09/27/1411832985119_Puff_Image_galleryImage_SUNDERLAND_ENGLAND_SEPTEM.JPG ")) ; 'и проверьте, отображается ли изображение или нет. @ Theo –

ответ

1

Ошибка:

Unable to decode stream: java.io.FileNotFoundException: 
     /http:/i.dailymail.co.uk/i/pix/2014/09/27/1411832985119_Puff_Image_galleryImage_SUNDERLAND_ENGLAND_SEPTEM.JPG: open failed: ENOENT (No such file or directory). 

Смотрите "/" перед началом URL. Это вызывает FileNotFoundException. Итак, во-первых, убедитесь, что вы получили правильный URL-адрес в своем ответе.

И для тестирования, попробуйте с закодированным URL:

holder.articleImage.setImageURI(Uri.parse("http:/i.dailymail.co.uk/i/pix/2014/0‌​9/27/1411832985119_Puff_Image_galleryImage_SUNDERLAND_ENGLAND_SEPTEM.JPG")); 

Я думаю, что должно работать нормально. Так что просто сделайте исправление в ответ, и вам хорошо идти.

+0

Если я прокомментирую Lm (currentChild.getAttributes(). item (0) .getTextContent()); который находится внутри if (currentChild.getNodeName(). equalsIgnoreCase («media: thumbnail»)) {}, я читаю изображения в файле журнала. Эта часть в порядке. Я установил ссылку изображения изображения внутри Uri.parse(), как вы показали мне, но пока не повезло. – Theo

+0

любая ошибка с этим? или изображение не показано? –

+0

изображение не показано .. Также исключение ..... resolveUri не удалось на плохой растровый uri: http: /i.dailymail.uk/i/pix/2014/0 ?? 9/27/1411832985119_Puff_Image_galleryImage_SUNDERLAND_ENGLAND_SEPTEM.JPG – Theo

1

Да. Ты был прав!!! Мне пришлось создать отдельный AsyncTask для загрузки изображений ..

public class ImageDownloader extends AsyncTask<String, String, Bitmap> { 

    private MyAdapter parentActivity; 


    public ImageDownloader(MyAdapter parentActivity) { 
    super(); 

    this.parentActivity = parentActivity; 
} 

    protected Bitmap doInBackground(String... args) { 
    try { 
     Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent()); 
     return bitmap; 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 

    protected void onPostExecute(Bitmap image) { 
    if(image != null){ 
     parentActivity.updateBitmap(image); 

    } 
    } 
} 

А также

new ImageDownloader(MyAdapter.this).execute(currentItem.get("imageURL")); 

, чтобы получить изображения и показать их в списке. Спасибо за ваши идеи. Они мне очень помогли!

Смежные вопросы