2016-07-19 2 views
1

Я пытаюсь получить новости RSS по URL-адресу http://timesofindia.indiatimes.com/rssfeeds/1945062111.cms Но у меня есть проблема с отображением изображений с этого URL-адреса. Отображаются только название и дата, но не изображение.Как получить изображение из RSS-ленты

In this image description have some tags, I don't to show them. Only content should display

Мой второй вопрос, как я могу изменить описание сгружен с RSS, потому что он отображает некоторые и тег. Я не хочу показывать их в своих новостях. Должны отображаться только данные.

, пожалуйста, покажите мне, где я должен редактировать этот код.

package com.tandon.mynewsapp.fragments; 

import android.content.Intent; 
import android.graphics.Color; 
import android.os.Build; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v4.widget.SwipeRefreshLayout; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.AdapterView; 
import android.widget.ListView; 
import android.widget.Toast; 

import com.android.volley.NetworkError; 
import com.android.volley.NoConnectionError; 
import com.android.volley.ParseError; 
import com.android.volley.Request; 
import com.android.volley.Response; 
import com.android.volley.ServerError; 
import com.android.volley.TimeoutError; 
import com.android.volley.VolleyError; 
import com.android.volley.toolbox.StringRequest; 
import com.tandon.mynewsapp.R; 
import com.tandon.mynewsapp.activity.DetailNewsActivity; 
import com.tandon.mynewsapp.activity.MainActivity; 
import com.tandon.mynewsapp.adapters.NewsListAdapters; 
import com.tandon.mynewsapp.app.AppController; 
import com.tandon.mynewsapp.models.News; 

import org.xmlpull.v1.XmlPullParser; 
import org.xmlpull.v1.XmlPullParserException; 
import org.xmlpull.v1.XmlPullParserFactory; 

import java.io.ByteArrayInputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.MalformedURLException; 
import java.nio.charset.Charset; 
import java.nio.charset.StandardCharsets; 
import java.util.ArrayList; 


public class LatestFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener { 

    private ListView listView; 
    private ArrayList<News> newsdata = new ArrayList<News>(); 
    private NewsListAdapters newsAdapter; 

    SwipeRefreshLayout swipeRefreshLayout; 
    private boolean IsLoading=false; 
    //private int totalPages=1; 
    //private int currentPage =1; 

    private String[] newsUrl; 

    @Override 
    public void onRefresh() { 

    } 

    private enum RSSXMLTag { 
     TITLE, DATE, LINK, CONTENT, GUID, IGNORETAG,DESCRIPTION,IMAGE; 
    } 

    public LatestFragment() { 
     // Required empty public constructor 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_one, container, false); 

     newsUrl=this.getResources().getStringArray(R.array.en_latest); 

     listView = (ListView) rootView.findViewById(R.id.newsList); 
     newsAdapter = new NewsListAdapters(getActivity(),newsdata); 
     listView.setAdapter(newsAdapter); 

     listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
      @Override 
      public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 
       News news = newsdata.get(i); 
       Intent intent = new Intent(getActivity(), DetailNewsActivity.class); 
       intent.putExtra("title",news.title); 
       intent.putExtra("description",news.description); 
       intent.putExtra("image",news.image); 
       intent.putExtra("date",news.postDate); 
       startActivity(intent); 
      } 
     }); 
     for(int i=0;i<newsUrl.length;i++) 
     { 
      getNewsPosts(false,newsUrl[i]); 
     } 


     swipeRefreshLayout=(SwipeRefreshLayout) rootView.findViewById(R.id.swipereferesh); 
     swipeRefreshLayout.setOnRefreshListener(
       new SwipeRefreshLayout.OnRefreshListener() { 
        @Override 
        public void onRefresh() { 
         newsdata.clear(); 
         for(int i=0;i<newsUrl.length;i++) 
         { 
          getNewsPosts(false,newsUrl[i]); 
         } 
        } 
       } 
     ); 
     swipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN); 


//  News news1 = new News(); 
//  news1.setTitle("Title 1"); 
//  news1.setDescription("This is Description of news title 1 to check in program"); 
//  newsdata.add(news1); 
// 
//  News news2 = new News(); 
//  news2.setTitle("Title 2"); 
//  news2.setDescription("Description 2 for title 2 goes here"); 
//  newsdata.add(news2); 
     //getNewsPosts(); 



     // Inflate the layout for this fragment 
     return rootView; 
    } 

    public void getNewsPosts(final boolean isRefresh,String url) 
    { 
     if(!isRefresh) { 
      ((MainActivity) getActivity()).showPDialog(); 
     } 

     // String url = "http://www.oneindia.com/rss/news-india-fb.xml"; 
     StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { 
      @Override 
      public void onResponse(String response) { 
       Log.d("News_World",response); 
       ((MainActivity)getActivity()).hidePDialog(); 
       //newsdata.clear(); 
       RSSXMLTag currentTag = null; 

       IsLoading = false; 
       if(isRefresh) 
       { 
        //newsdata.clear(); 
        swipeRefreshLayout.setRefreshing(false); 
        //currentPage = 1; 
       } 
       else 
       { 
        ((MainActivity)getActivity()).hidePDialog(); 
       } 
       try{ 
        // parse xml after getting the data 
        XmlPullParserFactory factory = XmlPullParserFactory 
          .newInstance(); 
        factory.setNamespaceAware(true); 
        XmlPullParser xpp = factory.newPullParser(); 

        //Abhishek Tandon Here 
        int currentapiVersion = android.os.Build.VERSION.SDK_INT; 
        if (currentapiVersion >= Build.VERSION_CODES.KITKAT) { 
         InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8)); 
         xpp.setInput(stream, null); 
        } 
        else{ 
         InputStream stream = new ByteArrayInputStream(response.getBytes(Charset.forName("UTF-8"))); 
         xpp.setInput(stream, null); 
        } 

        int eventType = xpp.getEventType(); 
        News newsItem = null; 
        //SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, DD MMM yyyy HH:mm:ss"); 
        while (eventType != XmlPullParser.END_DOCUMENT) { 
         if (eventType == XmlPullParser.START_DOCUMENT) { 

         } else if (eventType == XmlPullParser.START_TAG) { 
          if (xpp.getName().equals("item")) { 
           newsItem = new News(); 
           currentTag = RSSXMLTag.IGNORETAG; 
          } else if (xpp.getName().equals("title")) { 
           currentTag = RSSXMLTag.TITLE; 
          } else if (xpp.getName().equals("link")) { 
           currentTag = RSSXMLTag.LINK; 
          } else if (xpp.getName().equals("pubDate")) { 
           currentTag = RSSXMLTag.DATE; 
          } 
          else if(xpp.getName().equals("enclosure")||xpp.getName().equals("img")){ 
           currentTag = RSSXMLTag.IMAGE; 
           newsItem.image=xpp.getAttributeValue(0); 
          } 
          else if(xpp.getName().equals("description")){ 
           currentTag = RSSXMLTag.DESCRIPTION; 
          } 
         } else if (eventType == XmlPullParser.END_TAG) { 
          if (xpp.getName().equals("item")) { 
           // format the data here, otherwise format data in 
           // Adapter 
           // Date postDate = dateFormat.parse(newsItem.postDate); 
           // pdData.postDate = dateFormat.format(postDate); 
           newsdata.add(newsItem); 
          } else { 
           currentTag = RSSXMLTag.IGNORETAG; 
          } 
         } else if (eventType == XmlPullParser.TEXT) { 
          String content = xpp.getText(); 
          content = content.trim(); 
          Log.d("NEWS_WORLD","Content ="+ content); 
          //Log.d("NEWS_WORLD","date ="+ newsItem.postDate); 
          if (newsItem != null) { 
           switch (currentTag) { 
            case TITLE: 
             if (content.length() != 0) { 
              if (newsItem.getTitle() != null) { 
               newsItem.title += content; 
              } else { 
               newsItem.title = content; 
              } 
             } 
             break; 
            case DESCRIPTION: 
             if (content.length() != 0) { 
              if (newsItem.description != null) { 
               newsItem.description += content; 
              } else { 
               newsItem.description = content; 
              } 
             } 
             break; 
            case LINK: 
             if (content.length() != 0) { 
              if (newsItem.linkUrl != null) { 
               newsItem.linkUrl += content; 
              } else { 
               newsItem.linkUrl = content; 
              } 
             } 
             break; 
            case DATE: 
             if (content.length() != 0) { 
              if (newsItem.postDate != null) { 
               newsItem.postDate += content; 
              } else { 
               newsItem.postDate = content; 
              } 
             } 
             break; 
            default: 
             break; 
           } 
          } 
         } 

         eventType = xpp.next(); 
        } 
        Log.v("tst", String.valueOf((newsdata.size()))); 
       } catch (MalformedURLException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } catch (XmlPullParserException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

       newsAdapter.notifyDataSetChanged(); 

      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       ((MainActivity)getActivity()).hidePDialog(); 

       IsLoading = false; 
       swipeRefreshLayout.setRefreshing(false); 
       if (error instanceof TimeoutError) { 
        Toast.makeText(getActivity(), "Request Time out error. Your internet connection is too slow to work", Toast.LENGTH_LONG).show(); 
       } else if (error instanceof ServerError) { 
        Toast.makeText(getActivity(),"Connection Server error", Toast.LENGTH_LONG).show(); 
       } else if (error instanceof NetworkError || error instanceof NoConnectionError) { 
        Toast.makeText(getActivity(),"Network connection error! Check your internet Setting", Toast.LENGTH_LONG).show(); 
       }else if (error instanceof ParseError){ 
        Toast.makeText(getActivity(), "Parsing error", Toast.LENGTH_LONG).show(); 
       } 
      } 
     }); 

     AppController.getInstance().addToRequestQueue(request); 

    } 

} 

    /* 
    public void getNewsPosts() 
    { 
     ((MainActivity)getActivity()).showPDialog(); 
     String url = "http://rss.jagran.com/local/uttarakhand/almora.xml"; 
     StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { 
      @Override 
      public void onResponse(String response) { 
       Log.d("News_World",response); 
       ((MainActivity)getActivity()).hidePDialog(); 
       newsdata.clear(); 
       RSSXMLTag currentTag = null; 
       try{ 
       // parse xml after getting the data 
       XmlPullParserFactory factory = XmlPullParserFactory 
         .newInstance(); 
       factory.setNamespaceAware(true); 
       XmlPullParser xpp = factory.newPullParser(); 
       InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8)); 
       xpp.setInput(stream, null); 

       int eventType = xpp.getEventType(); 
       News newsItem = null; 
       SimpleDateFormat dateFormat = new SimpleDateFormat(
         "EEE, DD MMM yyyy HH:mm:ss"); 
       while (eventType != XmlPullParser.END_DOCUMENT) { 
        if (eventType == XmlPullParser.START_DOCUMENT) { 

        } else if (eventType == XmlPullParser.START_TAG) { 
         if (xpp.getName().equals("item")) { 
          newsItem = new News(); 
          currentTag = RSSXMLTag.IGNORETAG; 
         } else if (xpp.getName().equals("title")) { 
          currentTag = RSSXMLTag.TITLE; 
         } else if (xpp.getName().equals("link")) { 
          currentTag = RSSXMLTag.LINK; 
         } else if (xpp.getName().equals("pubDate")) { 
          currentTag = RSSXMLTag.DATE; 
         } 
         else if(xpp.getName().equals("img")){ 
          currentTag = RSSXMLTag.IMAGE; 
         } 
         else if(xpp.getName().equals("description")){ 
          currentTag = RSSXMLTag.DESCRIPTION; 
         } 
        } else if (eventType == XmlPullParser.END_TAG) { 
         if (xpp.getName().equals("item")) { 
          // format the data here, otherwise format data in 
          // Adapter 
          // Date postDate = dateFormat.parse(newsItem.postDate); 
          // pdData.postDate = dateFormat.format(postDate); 

          int start = newsItem.description.indexOf("http"); 
          int end = newsItem.description.indexOf(">"); 
          String img = newsItem.description.substring(start, end); 
          Log.d("Image", img); 
          newsItem.image=img; 

          end = newsItem.description.indexOf(">"); 
          newsItem.description= newsItem.description.substring(end + 1); 

          newsdata.add(newsItem); 
         } else { 
          currentTag = RSSXMLTag.IGNORETAG; 
         } 
        } else if (eventType == XmlPullParser.TEXT) { 
         String content = xpp.getText(); 
         content = content.trim(); 
         Log.d("NEWS_WORLD","Content ="+ content); 
         if (newsItem != null) { 
          switch (currentTag) { 
           case TITLE: 
            if (content.length() != 0) { 
             if (newsItem.getTitle() != null) { 
              newsItem.title += content; 
             } else { 
              newsItem.title = content; 
             } 
            } 
            break; 
           case IMAGE: 
            if (content.length() != 0) { 
             if (newsItem.image != null) { 
              newsItem.image += content; 
             } else { 
              newsItem.image = content; 
             } 
            } 
            break; 
           case DESCRIPTION: 
            if (content.length() != 0) { 
             if (newsItem.description != null) { 
              newsItem.description += content; 
             } else { 
              newsItem.description = content; 
             } 
            } 
            break; 
           case LINK: 
            if (content.length() != 0) { 
             if (newsItem.linkUrl != null) { 
              newsItem.linkUrl += content; 
             } else { 
              newsItem.linkUrl = content; 
             } 
            } 
            break; 
           case DATE: 
            if (content.length() != 0) { 
             if (newsItem.postDate != null) { 
              newsItem.postDate += content; 
             } else { 
              newsItem.postDate = content; 
             } 
            } 
            break; 
           default: 
            break; 
          } 
         } 
        } 

        eventType = xpp.next(); 
       } 
       Log.v("tst", String.valueOf((newsdata.size()))); 
      } catch (MalformedURLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } catch (XmlPullParserException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      newsAdapter.notifyDataSetChanged(); 

      } 
     }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       ((MainActivity)getActivity()).hidePDialog(); 

       if (error instanceof TimeoutError) { 
        Toast.makeText(getActivity(), "Request Time out error. Your internet connection is too slow to work", Toast.LENGTH_LONG).show(); 
       } else if (error instanceof ServerError) { 
        Toast.makeText(getActivity(),"Connection Server error",Toast.LENGTH_LONG).show(); 
       } else if (error instanceof NetworkError || error instanceof NoConnectionError) { 
        Toast.makeText(getActivity(),"Network connection error! Check your internet Setting",Toast.LENGTH_LONG).show(); 
       }else if (error instanceof ParseError){ 
        Toast.makeText(getActivity(),"Parsing error",Toast.LENGTH_LONG).show(); 
       } 
      } 
     }); 

     AppController.getInstance().addToRequestQueue(request); 
    } 

} 
*/ 

Я также пишу код NewsListAdapter

package com.tandon.mynewsapp.adapters; 

import android.content.Context; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.TextView; 

import com.android.volley.toolbox.NetworkImageView; 
import com.tandon.mynewsapp.R; 
import com.tandon.mynewsapp.app.AppController; 
import com.tandon.mynewsapp.models.News; 

import java.util.List; 

/** 
* Created by Abhishek Tandon on 09-07-2016. 
*/ 
public class NewsListAdapters extends BaseAdapter { 

    private List<News> newsdata; // bring news list data with id, title and data 
    private Context context; //where to display 

    public NewsListAdapters(Context context, List<News> list){ 
     this.context = context; 
     this.newsdata = list; 
    } 

    @Override 
    public int getCount() { 

     return newsdata.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return null; 
    } 

    @Override 
    public long getItemId(int position) { 
     return 0; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     View view; 

     if(convertView == null){ 
      LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
      view = inflater.inflate(R.layout.news_row, null); 
     } 
     else{ 
      view = convertView; 
     } 

     News news = newsdata.get(position); 
     TextView title = (TextView) view.findViewById(R.id.title); 
     TextView description = (TextView) view.findViewById(R.id.pub_date_time); 
     NetworkImageView image = (NetworkImageView) view.findViewById(R.id.imgview); 

     //Log.d("NEWS_WORLD",news.image); 
     image.setImageUrl(news.getImage(), AppController.getInstance().getImageLoader()); 
     title.setText(news.getTitle()); 
     description.setText(news.postDate); 
     return view; 
    } 
} 
+0

Не могли бы вы использовать библиотеку 'Picasso' для установки образа и' Html.fromHtml() 'метод для установки текста? –

+0

Для решения этой проблемы нет необходимости в использовании дополнительных библиотек. Я не использовал библиотеку Picasso, но попытаюсь найти точный URL-адрес изображения из описания, полученного на сайте. –

ответ

2

Я решил это самостоятельно, и нет необходимости загружать изображения на устройство пользователя. Хотя они отображают изображение, записывая двоичные данные в тело. но я могу получить URL-адрес изображения из строки.

public String getImage() { 
    if (description.startsWith("<a ")) {    
     String cleanUrl = description.substring(description.indexOf("src=") + 5, description.indexOf("/>") - 2); 
     return cleanUrl; 
    } else { 
     return image; 
    } 
} 

В этом коде я просто найти правильный URL изображения, который находится между «SRC =» и закрывающим тегом «/>». И верните это чистое изображение в метод.

Это решило мою проблему. :)

-2

Ваш URL изображения имеют тип: http://timesofindia.indiatimes.com/photo/507610.cms. Вы должны быть заменить .CMS на .jpeg перед отображением

+0

Это не работает. – Dotnetpickles

+0

Вы убедитесь, что '' 'image.getImage()' '' соответствует URL-адресу в RSS. Если вы соответствуете, вы должны [читать официальное] (https://developer.android.com/training/volley/request.html) для отображения изображения с URL-адреса. Или замените Volley на Picasso, Glide ... –

+0

Чтобы решить эту проблему, мне просто нужно найти точный URL-адрес между «src =» и «/>». поэтому я использую indesOf в коде android и его работе. см. мой ответ ниже этой страницы. –

-1

Привет Кажется, что они оказывают изображение путем записи двоичных данных в теле. Поэтому сначала попробуйте загрузить и сохранить изображение в свою локальную папку, а затем привязать его к представлению изображения. Ниже приведен пример кода загрузки.

public void downloadFile(String uRl) { 
    File direct = new File(Environment.getExternalStorageDirectory() 
      + "/FolderName"); 

    if (!direct.exists()) { 
     direct.mkdirs(); 
    } 

    DownloadManager mgr = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE); 

    Uri downloadUri = Uri.parse(uRl); 
    DownloadManager.Request request = new DownloadManager.Request(
      downloadUri); 

    request.setAllowedNetworkTypes(
      DownloadManager.Request.NETWORK_WIFI 
        | DownloadManager.Request.NETWORK_MOBILE) 
      .setAllowedOverRoaming(false).setTitle("Demo") 
      .setDescription("Something useful. No, really.") 
      .setDestinationInExternalPublicDir("/FolderNameFiles", "fileName.jpg"); 

    mgr.enqueue(request); 

} 

Надеюсь, это поможет.

+0

Я не хочу сохранять изображения на локальном устройстве. и если я использую другой URL-адрес, подобный этому http://www.oneindia.com/rss/feature-fb.xml, я получаю изображения без каких-либо изменений в моем вышеприведенном коде. –

+0

В одном индийском корте они непосредственно дают URL-адрес изображения, но во время подачи в Индию они пишут двоичные данные. Попробуйте использовать библиотеку picasso для рендеринга изображения. Это будет работать, а также нет необходимости загружать изображение. – Dotnetpickles

+0

Спасибо за ваш ответ, но я нашел URL-адрес изображения из описания между «src =» и «/>». и передать правильный URL-адрес изображения методу getImage(), и его работа прекрасна. :) –

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