String.contains doing opposite Jsoup Android - android

I may be misunderstanding what String.contains does. I am now trying to pull a specific link using Jsoup in Android. I'm trying to just get the faceBook one as an example. Ive tried a few things. this one It Seems to be outputting got it on the ones that do not contain the facebook url and leaving the facebook ones blank. How do I just get the FaceBook ones and stop the loop.
protected Void doInBackground(Void... params) {
Document doc = null;
try {
doc = Jsoup.connect("http://www.homedepot.com").get();
Elements link = doc.select("a[href]");
String stringLink = null;
for (int i = 0; i < link.size(); i++) {
stringLink = link.toString();
if (stringLink.contains("https://www.facebook.com/")){
System.out.println(stringLink+"got it");
}
else{
//System.out.println(stringLink+"not it");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

The following line is causing the problem:
stringLink = link.toString();
The link variable is a collection of Elements (in this case every link on the page), so by calling link.toString() you're getting the String representation of every single link on the page all at once! That means stringLink will always contain the facebook link!
Change the line to:
stringLink = link.get(i).toString();
This line gets only the link at index i on each iteration and checks whether or not it contains the facebook link.

Related

Retrieving information from google page

I'm thinking about making my first android app, It'd be about movies, I found an excellent data source, it is "http://www.google.com/movies?" but I wanted to know how could I extract this information and put it in my app,
I've searched but I don't know which is the optimal way to do this? does google have an API for this? is that what I want? is it better with the source code?what could I read or see to learn to do this?
thanks a lot guys, Is my first time as well programming retrieving information from the cloud,
cheers
Yup. Here is one way to do it.
First, you need to find the source of the SQL. The Yahoo Developer Console is a great place to look for this sort of stuff. It has EVERYTHING. The way these resources work is that you have a long link, like this....
developer.yahoo.com/blah/this . . . &q=KEYWORD_HERE+blah/ . . .
To access the information you are looking for, you stick whatever the correct keyword is where "KEYWORD_HERE" is, and the link will give you info in SQL format. I'll be doing the example as a stocks app.
First you create an Activity and define both sides of your link as strings. It'll look a bit like this:
public class InfoActivity extends Activity {
String firstHalf = "http://query.yahooapis.com/v1/public/blahblahblah&q=";
String secondHalf = "+blah/blah&blah . . . ";
Then, in your onCreate, you'll need to start an aSync task to do the actual pulling and parsing:
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.id.layout_name);
final String yqlURL = firstHalf + KEYWORD_HERE + secondHalf;
new MyAsyncTask().execute(yqlURL);
}
Then to define our MrAsyncTask:
private class MyAsyncTask extends AsyncTask<String, String, String>{
protected String doInBackground(String... args) {
try {
URL url = new URL(args[0]);
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
// Tests if responseCode == 200 Good Connection
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("nodeName1");
if (nl != null && nl.getLength() > 0) {
for (int i = 0 ; i < nl.getLength(); i++) {
//Parse the node here with getTextValue(n1, "Name of element")
//ex: String movieName = getTextValue(n1, "MovieName");
}
}
}
} catch (MalformedURLException e) {
Log.d(TAG, "MalformedURLException", e);
} catch (IOException e) {
Log.d(TAG, "IOException", e);
} catch (ParserConfigurationException e) {
Log.d(TAG, "Parser Configuration Exception", e);
} catch (SAXException e) {
Log.d(TAG, "SAX Exception", e);
}
finally {
}
return null;
}
I hope that gives you some idea of how to do this sort of thing. I'll go see if I can quickly spot a good resource on the yahoo apis to get the movie times at a certain location.
Good luck :) Let me know if you need anything clarified.
EDIT:
Looks like this is EXACTLY what you need (resource wise):
https://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select+*+from+google.igoogle.movies+where+movies%3D'68105'%3B
Check that out. Using that, your two halves of the link would be:
String firstHalf = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20google.igoogle.movies%20where%20movies%3D'"
String secondHalf = "'%3B&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
And then to get your final link, you would just do
String yqlURL = firstHalf + "ZIP CODE OF YOUR LOCATION" + secondHalf;
And you would have all of the movies playing near you returned!
Make your life a lot easier and choose the api that is right for you. Choose one of these:
http://www.programmableweb.com/news/52-movies-apis-rovi-rotten-tomatoes-and-internet-video-archive/2013/01/22
Make your decision not only based on the content, but also ease of use and documentation. Documentation is a biggy.
Good luck!
well i would rather advice you to use an TheMovieDB.com API it is simple and provides every info of movies.

Jsoup doesnt find the specified element

I'm trying to write a little android program (don't mind the messiness) that shows the last "Did you know?" from Wikipedia. But for some reason Jsoup doesn't find it.
What is the problem?
Part of the code:
Document document = null;
try {
document = Jsoup.connect("https://en.wikipedia.org/wiki/Portal:Mathematics/Did_you_know/1").get();
} catch (IOException e) {
e.printStackTrace();
}
//Document document = Jsoup.parse("test.html");
if (document != null) {
Element element = document.select("div#mw-content-text").first();
if (element == null) {
message = "empty";
} else {
message = element.html();
}
}
Part of the wikipedia source code:
<div id="mw-content-text" lang="en" dir="ltr" class="mw-content-ltr"><p>...that outstanding mathematician Grigori Perelman was offered a Fields Medal in 2006, in part for his proof of the Poincaré conjecture, which he declined?</p>
https://en.wikipedia.org/wiki/Portal:Mathematics/Did_you_know/1
Your code works fine on a desktop. Check your android settings according to internet access rights. Also it's a good idea to check where's the real problem.
Some hints:
replace e.printStackTrace(); with a logger
write the value of message variable to a logger too
are you using an AsyncTask?
Are there any errors, exception or something similar?

Android JSoup not working

I want to extract information from the web and show that value in my Android app. When I try to write the following code, nothing gets initialized to my textView. I can't see the data I wanted. Can you please tell me whats wrong?
EDIT: Android is now not even going past the line:
Document doc = Jsoup.connect("http://movies.ign.com/articles/100/1002569p1.html").get();
When I run the emulator, it just exits the App. Why is this happening??
Here is my code:
public class Search extends Activity {
private static final String TAG = "TVGuide";
String outputtext;
Parser parser;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
TextView outputTextView = (TextView) findViewById(R.id.outputTextView);
String id = "main-article-content";
try {
Document doc = Jsoup.connect("http://movies.ign.com/articles/100/1002569p1.html").get();
Elements elementsHtml = doc.getElementsByAttributeValue("id", "main-article-content");
for (Element element : elementsHtml) {
Log.i("PARSED ELEMENTS:", URLDecoder.decode(element.text(), HTTP.UTF_8));
outputTextView.setText(element.text());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I think you imported the class org.w3c.dom.Document instead of the required one, org.jsoup.nodes.Document by mistake.
EDIT: Android is now not even going past the line:
Jsoup cant connect to the site? Try to add timeout on the connect:
Document doc = Jsoup.connect("http://movies.ign.com/articles/100/1002569p1.html").timeout(10000).get();

Android: Need help, trying to parse a HTML page using JSoup parser

Here is the code so far I am trying but it is showing me error:
URL url = null;
try {
url = new URL("http://wap.nastabuss.se/its4wap/QueryForm.aspx?hpl=Teleborg+C+(V%C3%A4xj%C3%B6)");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("1");
Document doc = null;
try {
System.out.println("2");
doc = Jsoup.parse(url, 3000);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("3");
Element table = doc.select("table[title=Avgångar:]").first();
System.out.println("4");
Iterator<Element> it = table.select("td").iterator();
//we know the third td element is where we wanna start so we call .next twice
it.next();
it.next();
while(it.hasNext()){
// do what ever you want with the td element here
System.out.println(it.next());
//iterate three times to get to the next td you want. checking after the first
// one to make sure
// we're not at the end of the table.
it.next();
if(!it.hasNext()){
break;
}
it.next();
it.next();
}
It prints System.out.println("3");
then it stops in this line
Element table = doc.select("table[title=Avgångar:]").first();
How can i solve this problem,
Thanks
It looks like the website you're trying to parse the HTML from has an error and doesn't have any tables on it. This is what's causing the null pointer exception. doc.select("table[title=Avgångar:]") isn't returning an element and then you're trying to call a method on it. To prevent this error from happening again, you could do something like this:
Elements foundTables = doc.select("table[title=Avgångar:]");
Element table = null;
if(!foundTables.isEmpty()){
table = tables.first();
}
Now, if any table was found, the table variable won't be null. You'll just have to alter the code to adapt in case no tables are found.
You're not checking the result of doc.select() before calling .first(). If there are no elements in the document that match the specified query, doc.select() could return null. Then you are calling .first() on a null pointer which, of course, will throw an exception. There is no table tag with the title you have specified in the document that you are using in your example. So, the result is not surprising.

Dynamically populating an expandableListView

So All I'm trying to do is create a dynamic expandableListView Currently It works if I just do the groupViews. The problem comes in when I have to populate the children of those groupViews.. I don't know if I'm doing something wrong, or if theres another better way to do it. If anyone knows please let me know. I'm open to anything.
Currently I'm pulling my data off a server and the error I'm getting is java null pointer exception. So I'm thinking it might have something to do with how big I specified my array sizes?
private static String[][] children = new String[7][4];
private static String[] groups = new String[7];
Here is the rest of the code when I try to populate the View.
public void getData(){
try {
int tempGroupCount = 0;
URL food_url = new URL (Constants.SERVER_DINING);
BufferedReader my_buffer = new BufferedReader(new InputStreamReader(food_url.openStream()));
temp = my_buffer.readLine();
// prime read
while (temp != null ){
childrenCount = 0;
// check to see if readline equals Location
//Log.w("HERasdfsafdsafdsafE", temp);
// start a new location
if (temp.equalsIgnoreCase("Location"))
{
temp = my_buffer.readLine();
groups[tempGroupCount] = temp;
tempGroupCount++;
Log.w("HERE IS TEMP", temp);
}
temp = my_buffer.readLine();
while (temp.equalsIgnoreCase("Location") == false){
Log.w("ONMG HEHREHRHERHER", temp);
children[groupCount][childrenCount] = "IAJHSDSAD";
childrenCount++;
temp = my_buffer.readLine();
}
groupCount++;
}
my_buffer.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IO EXCEPTION", "Exception occured in MyExpandableListAdapter:" + e.toString());
}
}
to me it looks like an error in the loop - as you are reading another line without checking is it null
your while loop should look something like this methinks:
// prime read
while (temp != null ){
int childrenCount = 0;
// check to see if readline equals Location
// start a new location
//Log.w("HERasdfsafdsafdsafE", temp);
if (temp.equalsIgnoreCase("Location"))
{
temp = my_buffer.readLine();
groups[tempGroupCount] = temp;
tempGroupCount++;
Log.w("HERE IS TEMP", temp);
}
//>>remove following line as that one isn't checked and
//>>you are loosing on a line that is potentialy a child
//temp = my_buffer.readLine();
//>>check do you have first item to add subitems
else if (tempGroupCount>0){
while (temp.equalsIgnoreCase("Location") == false){
Log.w("ONMG HEHREHRHERHER", temp);
children[tempGroupCount-1][childrenCount] = "IAJHSDSAD";
childrenCount++;
temp = my_buffer.readLine();
}
//>>next counter is probably not need but can't see if you're using it somewhere else
//groupCount++;
}
I would first replace strings array to some 2d collection for example arraylist2d ( you can google it ) so you could easally add and remove data from list. If you created adapter that extends BaseExpandableListAdapter everything should be handled without any problems.
About NULLPointer, could you paste stacktrace or more info on which line it occurs ?

Categories

Resources