how to fetch image from RSS feed

2019-06-04 00:49发布

I am trying to fetch RSS news from a URL http://timesofindia.indiatimes.com/rssfeeds/1945062111.cms But I have a problem in displaying the images from this URL. Only the Title and the date are displaying but not the image.

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

My second question is how can I edit the description fetched from RSS because it is displaying some and tag. I don't want to show them in my news. Only the data should be displayed.

please show me where I should edit in this code.

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

}
*/

I am also writing a NewsListAdapter code

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

3条回答
戒情不戒烟
2楼-- · 2019-06-04 01:20

Hi It seems they are rendering the image by writing binary data to the body. So try to download and save the image to your local folder first then bind it to image view. Below is the sample download code.

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

}

Hope it will help.

查看更多
做自己的国王
3楼-- · 2019-06-04 01:28

Your image URL have type : http://timesofindia.indiatimes.com/photo/507610.cms. You must be replace .cms to .jpeg before display

查看更多
淡お忘
4楼-- · 2019-06-04 01:34

I solved it myself and there is no need to download any images to the user's device. Although they are rendering the image by writing binary data to the body. but I can get the image-URL from the string.

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

In this code I just find the right URL of image that is between "src=" and a closing tag "/>". And return this clean image to the method.

This Solved my problem. :)

查看更多
登录 后发表回答