5

I am new to programming so please go easy on me, I have been messing around with a simple RSS Reader, trying to get the link to the artice to open in a webview when the user clicks on the article.

I have found the string that controls and stores the link but when I try to print the link in the toast the link appears but with the whole article publishing date ect... how can I get the link to print on it own and what commands do I need to use to pass the link to the webview once I have isolated it, here is some of the code I have

RSSActivity

public class RssActivity extends ListActivity {
    private RssListAdapter adapter; 

        /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        List<JSONObject> jobs = new ArrayList<JSONObject>();
        try {
            jobs = RssReader.getLatestRssFeed();
        } catch (Exception e) {
            Log.e("RSS ERROR", "Error loading RSS Feed Stream >> " + e.getMessage() + " //" + e.toString());
        }

        adapter = new RssListAdapter(this,jobs);
        setListAdapter(adapter);
    }
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        // Get the item that was clicked
        Object o = this.getListAdapter().getItem(position);
        adapter.getItem(position).toString();
        String link = o.toString();


        Toast.makeText(this, "You selected: " + link, Toast.LENGTH_LONG)
                .show();


    }

}

Article.class

    public class Article {

    private long articleId;
    private long feedId;
    private String title;
    private String description;
    private String pubDate;
    private URL url;
    private String encodedContent;
    private String link;


    public void setArticleId(long articleId) {
        this.articleId = articleId;
    }
    /**
     * @return the feedId
     */
    public long getFeedId() {
        return feedId;
    }
    /**
     * @param feedId the feedId to set
     */
    public void setFeedId(long feedId) {
        this.feedId = feedId;
    }
    public String getLink() {
        return link;
    }
    /**
     * @param title the title to set
     */
    public void setLink(String link) {
        this.link = link;
    }
    /**
     * @return the title
     */
    public String getTitle() {
        return title;
    }
    /**
     * @param title the title to set
     */
    public void setTitle(String title) {
        this.title = title;
    }
    /**
     * @return the url
     */
    public URL getUrl() {
        return url;
    }
    /**
     * @param url the url to set
     */
    public void setUrl(URL url) {
        this.url = url;
    }
    /**
     * @param description the description to set
     */
    public void setDescription(String description) {
        this.description = description;

        //parse description for any image or video links
        if (description.contains("<img ")){
            String img  = description.substring(description.indexOf("<img "));
            String cleanUp = img.substring(0, img.indexOf(">")+1);

            int indexOf = img.indexOf("'");
            if (indexOf==-1){

            }


            this.description = this.description.replace(cleanUp, "");
        }
    }
    /**
     * @return the description
     */
    public String getDescription() {
        return description;
    }
    /**
     * @param pubDate the pubDate to set
     */
    public void setPubDate(String pubDate) {
        this.pubDate = pubDate;
    }
    /**
     * @return the pubDate
     */
    public String getPubDate() {
        return pubDate;
    }
    /**
     * @param encodedContent the encodedContent to set
     */
    public void setEncodedContent(String encodedContent) {
        this.encodedContent = encodedContent;
    }
    /**
     * @return the encodedContent
     */
    public String getEncodedContent() {
        return encodedContent;
    }
}

RSS Handler

    public class RSSHandler extends DefaultHandler {

    // Feed and Article objects to use for temporary storage
    private Article currentArticle = new Article();
    private List<Article> articleList = new ArrayList<Article>();

    // Number of articles added so far
    private int articlesAdded = 0;

    // Number of articles to download
    private static final int ARTICLES_LIMIT = 15;

    //Current characters being accumulated
    StringBuffer chars = new StringBuffer();    

    public void startElement(String uri, String localName, String qName, Attributes atts) {
        chars = new StringBuffer();
    }

    public void endElement(String uri, String localName, String qName) throws SAXException {

        if (localName.equalsIgnoreCase("title"))
        {
            Log.d("LOGGING RSS XML", "Setting article title: " + chars.toString());
            currentArticle.setTitle(chars.toString());

        }
        else if (localName.equalsIgnoreCase("description"))
        {
            Log.d("LOGGING RSS XML", "Setting article description: " + chars.toString());
            currentArticle.setDescription(chars.toString());
        }
        else if (localName.equalsIgnoreCase("pubDate"))
        {
            Log.d("LOGGING RSS XML", "Setting article published date: " + chars.toString());
            currentArticle.setPubDate(chars.toString());
        }
        else if (localName.equalsIgnoreCase("encoded"))
        {
            Log.d("LOGGING RSS XML", "Setting article content: " + chars.toString());
            currentArticle.setEncodedContent(chars.toString());
        }
        else if (localName.equalsIgnoreCase("item"))
        {

        }
        else if (localName.equalsIgnoreCase("link"))
        {
            Log.d("LOGGING RSS XML", "Setting article link: " + chars.toString());
            currentArticle.setLink(chars.toString());
            try {
                Log.d("LOGGING RSS XML", "Setting article link url: " + chars.toString());
                currentArticle.setUrl(new URL(chars.toString()));
            } catch (MalformedURLException e) {
                Log.e("RSA Error", e.getMessage());
            }
        }

        // Check if looking for article, and if article is complete
        if (localName.equalsIgnoreCase("item")) {

            articleList.add(currentArticle);

            currentArticle = new Article();

            // Lets check if we've hit our limit on number of articles
            articlesAdded++;
            if (articlesAdded >= ARTICLES_LIMIT)
            {
                throw new SAXException();
            }
        }
    }

    public void characters(char ch[], int start, int length) {
        chars.append(new String(ch, start, length));
    }

    public List<Article> getLatestArticles(String feedUrl) {
        URL url = null;
        try {

            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            url = new URL(feedUrl);

            xr.setContentHandler(this);
            xr.parse(new InputSource(url.openStream()));


        } catch (IOException e) {
            Log.e("RSS Handler IO", e.getMessage() + " >> " + e.toString());
        } catch (SAXException e) {
            Log.e("RSS Handler SAX", e.toString());
        } catch (ParserConfigurationException e) {
            Log.e("RSS Handler Parser Config", e.toString());
        }

        return articleList;
    }

}

public class RssReader {

    private final static String BOLD_OPEN = "<B>";
    private final static String BOLD_CLOSE = "</B>";
    private final static String BREAK = "<BR>";
    private final static String ITALIC_OPEN = "<I>";
    private final static String ITALIC_CLOSE = "</I>";
    private final static String SMALL_OPEN = "<SMALL>";
    private final static String SMALL_CLOSE = "</SMALL>";
    private final static String WEB_LINK = "<A>";
    private final static String WEB_CLOSE = "<A/";

    public static List<JSONObject> getLatestRssFeed(){
        String feed = "http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/eng_prem/rss.xml";

        RSSHandler rh = new RSSHandler();
        List<Article> articles =  rh.getLatestArticles(feed);
        Log.e("RSS ERROR", "Number of articles " + articles.size());
        return fillData(articles);
    }


    private static List<JSONObject> fillData(List<Article> articles) {

        List<JSONObject> items = new ArrayList<JSONObject>();
        for (Article article : articles) {
            JSONObject current = new JSONObject();
            try {
                buildJsonObject(article, current);
            } catch (JSONException e) {
                Log.e("RSS ERROR", "Error creating JSON Object from RSS feed");
            }
            items.add(current);
        }

        return items;
    }

    private static void buildJsonObject(Article article, JSONObject current) throws JSONException {
        String link = article.getLink();
        String title = article.getTitle();
        String description = article.getDescription();
        String date = article.getPubDate();


        StringBuffer sb = new StringBuffer();
        sb.append(BOLD_OPEN).append(title).append(BOLD_CLOSE);
        sb.append(BREAK);
        sb.append(description);
        sb.append(BREAK);
        sb.append(SMALL_OPEN).append(ITALIC_OPEN).append(date).append(ITALIC_CLOSE).append(SMALL_CLOSE);
        sb.append(BREAK);
        sb.append(BREAK);
        sb.append(BOLD_OPEN).append(WEB_LINK).append(link).append(BOLD_CLOSE).append(WEB_CLOSE);
        current.put("link", link);

        current.put("text", Html.fromHtml(sb.toString()));

    }
}

RssListAdapter

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class RssListAdapter extends ArrayAdapter<JSONObject> {

    public RssListAdapter(Activity activity, List<JSONObject> imageAndTexts) {
        super(activity, 0, imageAndTexts);
    }


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

        Activity activity = (Activity) getContext();
        LayoutInflater inflater = activity.getLayoutInflater();

        // Inflate the views from XML
        View rowView = inflater.inflate(R.layout.image_text_layout, null);
        JSONObject jsonImageText = getItem(position);

        //////////////////////////////////////////////////////////////////////////////////////////////////////
        //The next section we update at runtime the text - as provided by the JSON from our REST call
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        TextView textView = (TextView) rowView.findViewById(R.id.job_text);

        try {
            Spanned text = (Spanned)jsonImageText.get("text");
            textView.setText(text);

        } catch (JSONException e) {
            textView.setText("JSON Exception");
        }

        return rowView;

    } 

}
MarcoS
  • 13,386
  • 7
  • 42
  • 63
JonniBravo
  • 1,051
  • 1
  • 11
  • 26

2 Answers2

2

Open URL in default browser Open URL with Android

If you have the URL or URI object at one point, probably one of the explanations in the links above will get you on your way.

-- Edit:

protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    // Get the item that was clicked
    Object o = this.getListAdapter().getItem(position);
    adapter.getItem(position).toString();
    String link = o.toString();
    Toast.makeText(this, "You selected: " + link, Toast.LENGTH_LONG)
            .show();
}

Guessing this is the code to show the link but if you don't supply us what the getListAdapter() method etc do then I'm afraid it's hard to help you out.

Community
  • 1
  • 1
Wivani
  • 2,036
  • 22
  • 28
  • I have my own webview, I want to open the link within that so these intents are not suitable for my needs, How do get the link? and should I use bundle to pass the url or put.extras getextras ect..... – JonniBravo May 27 '11 at 14:25
  • Many Apologies, I have provided the RSSListAdapter class above, this is the full code for the RSS reader – JonniBravo May 27 '11 at 15:59
  • I suggest you try to find out for yourself what kind of Object (which class) you get when at the line `Object o = this.getListAdapter().getItem(position);` Apparently it has a toString() implementation that show the entire RSS feed content. Possibly there's a method to to 'getUrl()' or anything .. – Wivani May 28 '11 at 13:47
  • @JonniBravo: -1: you provide a lot of code, but not the relevant portions! Where is the `getItem()` method of the `RssListAdapter`? – MarcoS Jun 01 '11 at 10:39
  • @MarcoS Clearly I have not thought out this one, I thought when I managed to get the link to print along with all the other info(Description Publishing date etc...) I thought it would just be a case of putting in a getLink command to get the position and link and then passing it to the Webview class, I can pass numbers from class to class and do intents but I cannot seem to get the hang of strings. – JonniBravo Jun 01 '11 at 14:18
  • @JonniBravo: you call `Object o = this.getListAdapter().getItem(position);` in your `RSSActivity`, so clearly you must have a `getItem()` method. What do you mean by "I have not thought out this one"? Passing a String as a parameter to a method, or returning it from a method is done in the same way as any other type. It is really unclear where your problem is. You should post a precise question with only relevant code to get some real help :) – MarcoS Jun 01 '11 at 15:20
  • @MarcoS: I thought I knew how getItem getUrl ect.. worked but clearly I dont have a full understanding, I guess its back to basics, the full code is printed, this is a method I need to try and understand better, thanks for you positive criticism, if you know of specific tutorial that may help me here I would be very greatful. Many thanks – JonniBravo Jun 02 '11 at 07:30
1

Try this

protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        // Get the item that was clicked
        JSONObject o = (JSONObject) this.getListAdapter().getItem(position);
        adapter.getItem(position).toString();
        String link = o.getString("NameOfLinkInJsonObject");


        Toast.makeText(this, "You selected: " + link, Toast.LENGTH_LONG)
                .show();

        mMyWebView.loadUrl(link);
    }

Be aware that you need to fix "NameOfLinkInJsonObject".

In your activity add a field like so

private WebView mMyWebView;

In your onCreate method add a

mMyWebView = (WebView) findViewById(R.id.webViewId);

You will have to change the R.id.webViewId to the appropriate id for your web view.

Justin Breitfeller
  • 13,737
  • 4
  • 39
  • 47
  • Thanks for your reply,in the line JSONObeject o = this.getlistAdapter I am getting error cannot convert from object to JSONObject in the webview method I am getting cannot make a static reference to the non static webview.loadurl(link); – JonniBravo Jun 07 '11 at 07:44
  • I edited my answer to be a little more exact. My first cut wasn't meant to be copy paste. Remember, you need to change the NameOfLinkInJsonObject to the field name in the JSON object that contains the link. – Justin Breitfeller Jun 07 '11 at 14:50
  • Thank you Justin I'm sure I will be able to get this working I appreciate it – JonniBravo Jun 08 '11 at 16:10