Parse an RSS feed for Android app ? Is jsoup the answer? - android

I am reading the Head First Android development book. In the third chapter where they try to make an app from NASA RSS feed from here . In the book the author uses SAX parser for Java. I looked online and some of the answers here on SO suggest that SAX is outdated and there are newer solutions.
However I'm not sure what the easier to use ones are for Java. I have used Nokogiri for Ruby and something similar would be awesome. I looked at jsoup and it looked alright, but I am wondering what suggestions you guys might have.

I'm the author of Head First Android Development, so just wanted to chime in with a few thoughts. SAX is definitely a bit cumbersome, but straightforward and was built into Android for a while (hence the decision to use that in the book). I'm also a rails developer and I'm a big fan of nokogiri and use it often. Looking at jsoup, I could definitely see that being useful. That said, I haven't tried it out, so I can't give any first hand experience with it.
Another option to look at is the XML PullParser built into Android. It's still pretty SAX-like, but a bit more full featured.
Hope this helps.

The code on the chapter 3 halts because Android doesn't support networking in it's main thread.
So you can use any parser like XmlPullParser but make sure you do the networking(downloading the feed etc.) off of it's main thread. You can use AsyncTask to take the networking outside the main thread.. or create a new Thread() and do the networking in that thread (Recommended)
Actually, in the 4th chapter they actually DID create a new thread to do the networking. So if you use the chapter4 code instead then it will work.
Another problem you might face is of OutOfMemoryError because Nasa daily images are really big these days. So you'll have to decode the image with inSampleSize. You can check other questions on decoding an image right to get what you want. Good luck. ))

I'm a big fan of Jsoup. I only recently started using it and its amazing. I used to write some super hairy regex patterns to do pattern matching with because I wanted to avoid SAX like the plague... and that was quite tedious as you can imagine. Jsoup let me parse out specific items from a <table> in just a few lines of code.
Let's say I want to take the first 7 rows of a table where the <tr class=...> is GridItem or GridAltItem. Then, lets say we want to print the 1st, 2nd, and 3rd columns as text and then the first <a href> link that appears in the row. Sounds goofy, but I had to do this and I can do this easily:
String page = "... some html markup fetched from somewhere ...";
Document doc = Jsoup.parse(page);
for(int x=0; x< 7; x++) {
Element gridItem = doc.select("tr[class$=Item]").select("tr").get(x);
System.out.println("row: " + gridItem.select("td").get(0).text() + " " + gridItem.select("td").get(1).text() + " " + gridItem.select("td").get(4).text() + " " + gridItem.select("a").get(0).attr("href"));
}
Its that simple with Jsoup. Make sure you add the Jsoup jar file to your project as a library and import those classes which you need: you don't want to import the wrong Document or Element class...
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
Enjoy!

I think SAX is a default way to acheive it, no boundations on trying something new though :)

Since version 1.6.2, Jsoup officially also supports XML parsing. This thus allows you to parse XML and select elements using jQuery-like CSS selectors. To create a XML document with Jsoup, you need the following instead of Jsoup#parse() method:
Document document = Parser.xmlParser().parseInput(xmlString, "");
// ...
This way the input won't implicitly be treated as HTML5 (so, no auto-included <html><head> tags and so on).

Related

Render image using srcset property in React Native

I am having following JSON feed from one of my Wordpress blog, and I would like to render images within the content of the blog as the JSON feed shows.
There is only one image in the feed, however you will notice one tag and within that a few srcset as well. For some reason is giving a relative URL which is no good for me to render an image outside of the Wordpress blog, however I could use the property of tag which is srcset which is providing an absolute path to the image.
Could someone suggest me how I can ignore the src of the tag and rather should be able to use srcset? The platform I am using is React Native.
<p>Can you spare a few minutes to look at some terrible and completely ridiculous life tips? Well then you’ve come to the right place!</p>\n<p>Some of them come from a sub-Reddit called /r/ShittyLifeProTips, and while they won’t actually help you to achieve much, they are at least useful when it comes to making us laugh. From using ketchup as a bookmark, to saving yourself precious time by adding toothpaste to meals, these “pro” life tips are sure to put a smile on your face while completely failing to help you in any practical way.</p>\n<p>P.S.: These tips are a joke and may be dangerous, don’t try them yourself!</p>\n<p><strong>#1 Use a toilet seat to put your plate on while watching TV</strong></p>\n<p><img class=\"alignnone size-medium wp-image-2098\" src=\"/wp-content/uploads/2017/11/1-Use-a-toilet-seat-to-put-your-plate-on-while-watching-TV-284x300.jpg\" alt=\"\" width=\"284\" height=\"300\" srcset=\"https://vinth.azurewebsites.net/wp-content/uploads/2017/11/1-Use-a-toilet-seat-to-put-your-plate-on-while-watching-TV-284x300.jpg 284w, https://vinth.azurewebsites.net/wp-content/uploads/2017/11/1-Use-a-toilet-seat-to-put-your-plate-on-while-watching-TV-545x575.jpg 545w, https://vinth.azurewebsites.net/wp-content/uploads/2017/11/1-Use-a-toilet-seat-to-put-your-plate-on-while-watching-TV.jpg 605w\" sizes=\"(max-width: 284px) 100vw, 284px\" /></p>\n<p> </p>\n

xml to sqlitle loop in android

Hello all my second question here so be gentle :)
I'm still learning java and android, I'm learning it on my little project but I hit kind of logical wall.
I have XML file
<shift_plan>
<plan>
<agent data="John Smith"/>
<date data="6 Jan"/>
<shift data="M-3"/>
</plan>
<plan>
<agent data="John Smith"/>
<date data="7 Jan"/>
<shift data="M-3"/>
</plan>
<plan>
<agent data="John Smith"/>
<date data="8 Jan"/>
<shift data="M-3"/>
</plan>
</shift_plan>
on a web and I want to make a loop that would paste each data to function that put it to db. I have the function and working db so it looks like updateBD(agent, date, shift ) but how would I go about parsing the xml but to parse the 3 variables than put them in that function and than go again for the next 3 etc...until end of xml
I might be not making much sense I know, this must be something very simple I'm sure but I need really kick in the right direction..
Thanks for any answer,
Vlad
Android supports the XmlPullParser API right out of the box. It is an excellent solution for parsing XML documents in Android apps because you can start pulling information from the document right away (it's a streaming XML parser) and its pull-style API is a lot easier to use than that of a push-style streaming XML parser when all you need to do is parse the document into objects.
I am not sure if this is still true in Android 3 and 4, but the Android 2.3.x and earlier implementation of XmlPullParser (from the Apache Harmony project) does not support getPrefix() or getAttributePrefix(int index). Though, this shouldn't affect you because you are not using XML namespaces.
EDIT: Examining the git trees corresponding to the platform_frameworks_base tags, it appears that Android 3.2.4 and earlier have the XmlPullParser implementation from the Harmony project whereas beginning with Android 4.0, the implementation switched to kXML2.

What is the equivalent of Android's Html.fromHtml() in WP7?

Is there a quick and dirty way to render HTML in a textblock in a fashion similar to Android's Html.fromHtml()? I am aware of how to manually parse it with something like the HtmlAgilityPack, but all I really want is for it to render like its source in the textblock.
If not naively then perhaps with a custom control of some sort and, no I don't want to render it as a web page.
Ok sorry it took so long. I all but forgot how to use git correctly and hadn't had the time to upload till now. This HtmlTextBlock offers a similar level of functionality as to that of its silverlight counterpart which is pretty close to the android equivalent. Its still a bit buggy at times when dealing with more complex tags like the html dtd tag but does the job....
WP7 Html Text Block. The design is largely based on this guy's Bringing-a-bit-of-html-to-silverlight-htmltextblock-makes-rich-text-display-easy. and rewriting the web browser related classes using html agility. One day I'll post the details but, blah... Not right now. lol
Update
Example of usage:
<local:HtmlTextBlock x:Name="htmlTextBlock" Canvas.Left="2" Canvas.Top="2" TextWrapping="Wrap" UseDomAsParser="true" Text="&ltp&gtYour Html here &lt/p&gt" />
Note: Your html will have to be escaped such that &lt = < and &gt = >
For detailed usage see:
https://github.com/musicm122/WP7HtmlTextBlock-/blob/master/HtmlTextBlockTest/HtmlTextBlockTest/MainPage.xaml

Android - Getting data from XML file on the web

I need to get data from an XML file in Android. On the iPhone environment, my code is:
NSURL *thisURL = [[NSURL alloc] initWithString:#"http://www.xxx.com/file.xml"];
NSArray *myArray = [[NSArray alloc] initWithContentsOfURL:providerURL];
myArray is now an array of dictionary items initialized with contents from file.xml.
Is there any way to do this in Android? Can someone point me to doc or sample code?
I'm new to the Android environment and just need some direction.
Thanks,
Kevin
See Working with XML in Android for a variety of methods for dealing with XML. Which method to use depends on how big your XML is, and what you want to do with it. '
I'm not sure how it makes any sense to turn XML into an array, so no, none of the methods do that. If you want something similar to that, use Json instead of XML.
After a bit of research, it appears to me that using the Simple XML Serialization framework is going to be my best bet, especially since I do have a relatively simple XML file to read. The result will be a 'list' class with several 'entry' classes which seems like a viable way to handle this...probably better than having an array of classes as was done in the iPhone app.

Parse JSON into a ListView friendly output

So I have this JSON, which then my activity retrieves to a string:
{"popular":
{"authors_last_month": [
{
"url":"http://activeden.net/user/OXYLUS",
"item":"OXYLUS",
"sales":"1148",
"image":"http://s3.envato.com/files/15599.jpg"
},
{
"url":"http://activeden.net/user/digitalscience",
"item":"digitalscience",
"sales":"681",
"image":"http://s3.envato.com/files/232005.jpg"
}
{
...
}
],
"items_last_week": [
{
"cost":"4.00",
"thumbnail":"http://s3.envato.com/files/227943.jpg",
"url":"http://activeden.net/item/christmas-decoration-balls/75682",
"sales":"43",
"item":"Christmas Decoration Balls",
"rating":"3",
"id":"75682"
},
{
"cost":"30.00",
"thumbnail":"http://s3.envato.com/files/226221.jpg",
"url":"http://activeden.net/item/xml-flip-book-as3/63869",
"sales":"27",
"item":"XML Flip Book / AS3",
"rating":"5",
"id":"63869"
},
{
...
}],
"items_last_three_months": [
{
"cost":"5.00",
"thumbnail":"http://s3.envato.com/files/195638.jpg",
"url":"http://activeden.net/item/image-logo-shiner-effect/55085",
"sales":"641",
"item":"image logo shiner effect",
"rating":"5",
"id":"55085"
},
{
"cost":"15.00",
"thumbnail":"http://s3.envato.com/files/180749.png",
"url":"http://activeden.net/item/banner-rotator-with-auto-delay-time/22243",
"sales":"533",
"item":"BANNER ROTATOR with Auto Delay Time",
"rating":"5",
"id":"22243"},
{
...
}]
}
}
It can be accessed here as well, although it because it's quite a long string, I've trimmed the above down to display what is needed.
Basically, I want to be able to access the items from "items_last_week" and create a list of them - originally my plan was to have the 'thumbnail' on the left with the 'item' next to it, but from playing around with the SDK today it appears too difficult or impossible to achieve this, so I would be more than happy with just having the 'item' data from 'items_last_week' in the list.
Coming from php I'm struggling to use any of the JSON libraries which are available to Java, as it appears to be much more than a line of code which I will need to deserialize (I think that's the right word) the JSON, and they all appear to require some form of additional class, apart from the JSONArray/JSONObject script I have which doesn't like the fact that items_last_week is nested (again, I think that's the JSON terminology) and takes an awful long time to run on the Android emulator.
So, in effect, I need a (preferably simple) way to pass the items_last_week data to a ListView. I understand I will need a custom adapter which I can probably get my head around but I cannot understand, no matter how much of the day I've just spent trying to figure it out, how to access certain parts of a JSON string..
originally my plan was to have the
'thumbnail' on the left with the
'item' next to it, but from playing
around with the SDK today it appears
too difficult or impossible to achieve
this
It is far from impossible, but it will be tedious to get right, unless you use something that already wraps up that pattern for you (and that hopefully is reasonably "right"). On the Web, performance/bandwidth issues were the user's problem -- in mobile, they're your problem.
as it appears to be much more than a
line of code which I will need to
deserialize (I think that's the right
word) the JSON
new JSONObject(data) is one line of code. Now, fetching the JSON, which I presume you are doing from the aforementioned URL, will be several lines of code. Neither the parsing of the JSON nor the fetching of it off the Internet is unique to Android -- all of that would look the same on a desktop Java app, or a Java servlet, or whatever.
apart from the JSONArray/JSONObject
script I have which doesn't like the
fact that items_last_week is nested
I have not had a problem parsing JSON with structures like your file exhibits. Moreover, this is hardly unique to Android -- the JSON parser is used in many other Java-based projects.
and takes an awful long time to run on
the Android emulator
The speed of the emulator is tied to the speed of your development machine. For me, the emulator is usually slower than actual phone hardware...and my desktop is a quad-core. Bear in mind that the emulator is pretending to be an ARM chipset running on your PC, converting ARM opcodes into x86 opcodes on the fly, so it's not going to be fast and won't leverage multiple cores very well.
So, in effect, I need a (preferably
simple) way to pass the
items_last_week data to a ListView.
There is nothing really built into Android to take an arbitrary JSON structure, with arbitrary data, and directly pour it into a ListView. This is not unique to JSON -- XML would exhibit similar phenomenon.
Your choices are:
Create a custom ListAdapter that wraps the parsed JSON.
Convert the parsed JSON into a MatrixCursor (think 2D array of data) and use a SimpleCursorAdapter.
Convert the parsed JSON into an ArrayList<String> and use an ArrayAdapter.
For the short term, option #3 is probably the simplest.
I understand I will need a custom
adapter which I can probably get my
head around but I cannot understand,
no matter how much of the day I've
just spent trying to figure it out,
how to access certain parts of a JSON
string..
And that question is too vague for much in the way of assistance. You might consider opening up a separate question, tagged for Java and JSON, where you get into the details of where you are having problems with the json.org parser.

Categories

Resources