I am trying to replace routeName and routeDurationInMinutes but the rpelace method is not working. It was working when i had it outside the run function but inside it does not work. Any ideas? I have added all my code that I am trying to run. Im sorry that this is so back and forth. I tried to shorten it to make it easier for others to read.
The Value g = {"routes":[{"routeName":"I-190 N; Electric Ave","routeDurationInMinutes":70,"routeLengthKM":83.865,"routeLengthMiles":52.111278915,"toll":false},{"routeName":"I-190 N; Greenville Rd","routeDurationInMinutes":82,"routeLengthKM":92.569,"routeLengthMiles":57.519692099000004,"toll":false}],"startPoint":"street address","endPoint":"destination","startLatitude":"42.20115054203528","startLongitude":"-71.85038140607858","endLatitude":"42.201220801535","endLongitude":"-71.849075146695"}
final Runnable rundatapoll = new Runnable() {
#Override
public void run() {
String g;
try {
g = new apicall().execute().get().getBody().toString();
System.out.println(g);
String route1;
String route2;
String time1;
String time2;
String time3;
ArrayList parse= new ArrayList();
ArrayList route= new ArrayList();
ArrayList time= new ArrayList();
Pattern p= Pattern.compile("routeName?.+?routeLengthKM");
Matcher m = p.matcher(g);
Pattern p2= Pattern.compile("routeName?.+?routeDurationInMinutes");
Pattern p3= Pattern.compile("routeDurationInMinutes?.+?routeLengthKM");
Matcher m3= p3.matcher(g);
while (m.find()) {
parse.add(m.group());
}
while (m3.find()){
time.add(m3.group());
}
int l=0;
while (l<parse.size()){
Matcher m2 =p2.matcher((CharSequence) parse.get(l));
while(m2.find()){
route.add(m2.group());
}
l++;
}
//////////////////////////////////////////////////////////////////////////////////////
route1= (String) route.get(0);
route2= (String) route.get(1);
route1= route1.replace(",routeDurationInMinutes","");
route1= route1.replace("routeName:","");
route2= route2.replace(",routeDurationInMinutes","");
route2= route2.replace("routeName:","");
time1= (String) time.get(0);
time2= (String) time.get(1);
time1= time1.replace("routeDurationInMinutes:","");
time1= time1.replace(",routeLengthKM","");
time2= time2.replace("routeDurationInMinutes:","");
time2= time2.replace(",routeLengthKM","");
t1.setValue(time1);
t2.setValue(time2);
r1.setValue(route1);
r2.setValue(route2);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
};
>>>routeName":"I-190 N; Electric Ave","routeDurationInMinutes
Looks like the thread might not be being executed as suggested in the comments.
This worked for me:
package example;
public class Example {
final String g="routeName:I-190 N; Electric Ave,routeDurationInMinutes";
final Runnable rundatapoll = new Runnable() {
#Override
public void run() {
String route1=g;
System.out.println("BEFORE THREAD");
System.out.println(route1);
route1= route1.replace(",routeDurationInMinutes","");
route1= route1.replace("routeName:","");
System.out.println("AFTER RUNNING THREAD:");
System.out.println(route1);
System.out.println("DONE");
}
};
public static void main(String[] args) {
Example example = new Example();
Thread thread = new Thread(example.rundatapoll);
thread.start();
}
}
Output:
BEFORE THREAD
routeName:I-190 N; Electric Ave,routeDurationInMinutes
AFTER RUNNING THREAD:
I-190 N; Electric Ave
DONE
Or you could use a JSON parser. Something like this:
package example;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonExample {
public static void main(String[] args) {
try {
String json = "{\"routes\":[{\"routeName\":\"I-190 N; Electric Ave\",\"routeDurationInMinutes\":70,\"routeLengthKM\":83.865,\"routeLengthMiles\":52.111278915,\"toll\":false},{\"routeName\":\"I-190 N; Greenville Rd\",\"routeDurationInMinutes\":82,\"routeLengthKM\":92.569,\"routeLengthMiles\":57.519692099000004,\"toll\":false}],\"startPoint\":\"street address\",\"endPoint\":\"destination\",\"startLatitude\":\"42.20115054203528\",\"startLongitude\":\"-71.85038140607858\",\"endLatitude\":\"42.201220801535\",\"endLongitude\":\"-71.849075146695\"}";
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(json);
JSONArray routes = (JSONArray) obj.get("routes");
System.out.println("ROUTES: ");
for(Object route : routes) {
JSONObject routeObj = (JSONObject) route;
String routeName = routeObj.get("routeName") + "";
System.out.println("Route name: " + routeName);
}
} catch (Exception exp) {
throw new RuntimeException(exp);
}
}
}
Output:
ROUTES:
Route name: I-190 N; Electric Ave
Route name: I-190 N; Greenville Rd
Related
So I got this piece of code:
public static ArrayList<Vehicle> readVehicles() throws IOException {
ArrayList<Vehicle> out = new ArrayList<Vehicle>();
JSONParser parser = new JSONParser();
JSONObject jsonObject = new JSONObject();
try {
jsonObject = (JSONObject) parser.parse(new FileReader("Vehicles.json"));
} catch (ParseException e) {
e.printStackTrace();
}
JSONArray jsonvehicles = (JSONArray) jsonObject.get("Vehicles");
Iterator i = jsonvehicles.iterator();
while (i.hasNext()) {
JSONObject v = (JSONObject) i.next();
/*
* Engines(); Chassis(); Tires();
*/
// out.add(new Vehicle(...);
}
return out;
}
public static ArrayList<Engine> readEngines() throws IOException {
ArrayList<Engine> out = new ArrayList<Engine>();
JSONParser parser = new JSONParser();
JSONObject jsonObject = new JSONObject();
try {
jsonObject = (JSONObject) parser.parse(new FileReader("Engines.json"));
} catch (ParseException e) {
e.printStackTrace();
}
JSONArray jsonengines = (JSONArray) jsonObject.get("Engines");
Iterator i = jsonengines.iterator();
while (i.hasNext()) {
JSONObject v = (JSONObject) i.next();
String name = (String) v.get("name");
int price = (int) v.get("price");
int quality = (int) v.get("quality");
int maxSpeed = (int) v.get("maxSpeed");
int maxAccelaration = (int) v.get("maxAcceleration");
out.add(new Engine(name, price, quality, maxSpeed, maxAccelaration));
}
return out;
}
and so on, regarding at tires(), and chassis.
My question is, how do I get the output of for example, engine, into vehicle?
See, a vehicle consists of engines, chassis and tires. And a engine as the properties quality, name, price and so on. How do I kinda add this to a new vehicle?
It's probably already been asked, but I really don't know how to ask this (native language isn't English). Sorry if I sound really vague, but to be honest, I'm not sure what I'm asking.
As Kevin Esche said, you can do it by something like this (For example) :
Car.java class file
private class Car{
private Engine engine;
private ArrayList<Tire> tires;
public void setEngine(Engine carEngine){
this.engine = carEngine;
}
public Engine getEngine(){
return this.engine;
}
public void addTire(Tire carTire){
this.tires.add(carTire);
}
}
Engin java class file
private class Engine{
private int horsepower;
public int getHorsepower() {
return horsepower;
}
public void setHorsepower(int horsepower) {
this.horsepower = horsepower;
}
}
Tire.java file
private class Tire{
private int size;
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
In addition, something is missing in your "readVehicle()" method code.
You need to write how to build a Vehicule from your Json Object.
So if your json file looks like :
{
"carType": "Mercedes Classe B"
}
you will need to write in your code (readVehicle() method for example):
Vehicule vehicule = new Vehicle();
vehicule.setType(object.getString("carType"));
I am new at Java and I am having a little trouble:
I am trying to read chemical samples to represent them at a X-Y graph.
The input file looks like this:
La 0.85678
Ce 0.473
Pr 62.839
...
...
My code stocks only the unpair lines value (0.85678, jumps line, 62.839 at the example), and I cannot realize what is the problem:
public class Procces {
public void readREE() throws IOException {
try{
rEE = new BufferedReader (new FileReader ("src/files/test.txt"));
while ( (currentLine = rEE.readLine() ) != null) {
try {
for (int size = 3;size<10;size++) {
String valueDec=(currentLine.substring(3,size));
//char letra =(char)c;
if ((c=rEE.read()) != -1) {
System.out.println("Max size");
} else
valueD = Double.parseDouble(valueDec);
System.out.println(valueDec);
}
}
catch (Exception excUncertainDecimals) {
}
}
}finally {
try { rEE.close();
} catch (Exception exc) {
}
}
}
String line;
int c = 0;
int counter = 0;
String valueS = null;
String valueSimb = null;
Double valueD = null;
Double logValue = null;
Double YFin=450.0;
String currentLine;
BufferedReader rEE;
}
Thank you in advance, as I can't see why the program jumps the pair lines.
use Java Scanner class.
import java.io.*;
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) throws IOException {
try (Scanner s = new Scanner(new BufferedReader(new FileReader("file.txt"))){
while (s.hasNext()) {
System.out.println(s.next());
}
}
}
}
Please have a look at Scanner.
In general is Java a well established language and in most cases you do not have to re-implemented "common" (e.g. reading custom text files) stuff on a low level way.
I get it. Thank you.
Here the code:
import java.io.*
import java.util.Scanner;
public class Process implements Samples{
public void readREE() throws IOException {
try
(Scanner rEE = new Scanner(new BufferedReader(new FileReader("src/files/test.txt")))){
while (rEE.hasNext()) {
element = rEE.next();
if (element.equals("La")) {
String elementValue = rEE.next();
Double value = Double.parseDouble(elementValue);
Double valueChond = 0.237;
Double valueNorm= value/valueChond;
Double logValue = (Math.log(valueNorm)/Math.log(10));
Double yLog = yOrd - logValue*133.33333333;
Sample NormedSampleLa=new Sample("La",yLog);
sampleREE.add(NormedSampleLa);
}
}
} finally {
}
}
public String LaS, CeS, PrS, NdS, PmS, SmS, EuS, GdS, TbS, DyS, HoS, ErS, TmS, YbS, LuS;
public String element, elementValue;
public Double yOrd=450.0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
In the first method, I just want to create a thread for each URL in the array and parse it:
public void readFriendData(String[] urls) {
Thread[] urlThreads = new Thread[urls.length];
for (int x = 0; x < urls.length; x++) {
Runobject input = new Runobject(urls[x], this);
Thread one = new Thread(input);
urlThreads[x] = one;
}
for(int x = 0; x< urls.length; x++){
urlThreads[x].start();
}
}
And then I made a separate class for my runnable object, where the run method creates a bufferedReader to scan the html file and parses it.
package twitbook;
public class Runobject implements Runnable {
public String address;
public Twitbook net;
public Runobject(String theAdress, Twitbook net) {
address = theAdress;
this.net = net;
}
#Override
public void run() {
try {
URL url = new URL(address);
URLConnection urlConnection = url.openConnection();
BufferedReader scanner = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String input = scanner.readLine();
while (!input.equals("</body>")) {
if (input.startsWith("<tr> <td>addperson</td>")) {
input.replaceAll("<tr> <td>addperson</td>", "");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.addUser(input);
} else if (input.startsWith("<tr> <td>addfriend</td>")) {
String[] bits = new String[2];
input.replaceAll("<tr> <td>addfriend</td>", "");
bits = input.split("</td> <td>");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.friend(bits[0], bits[1]);
net.friend(bits[1], bits[0]);
}
input = scanner.readLine();
}
scanner.close();
} catch (IOException e) {
System.out.println("bad URL");
}
}
}
I know when the first method is called, even though I started the threads, it doesn't go through the run method in the runObject class. Why is this?
Your code works perfectly. You simply do not realize it. Add few logging/output messages and you will see it. Oh, by the way, anticipate end of input. Here is simplified code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Runobject implements Runnable {
public String address;
public static void main(String a[]) {
System.out.println("Start");
readFriendData(new String[] { "http://google.com", "http://yahoo.com" });
System.out.println("End");
}
public static void readFriendData(String[] urls) {
Thread[] urlThreads = new Thread[urls.length];
for (int x = 0; x < urls.length; x++) {
Runobject input = new Runobject(urls[x]);
Thread one = new Thread(input);
urlThreads[x] = one;
}
for (int x = 0; x < urls.length; x++) {
urlThreads[x].start();
}
}
public Runobject(String theAdress) {
address = theAdress;
System.out.println(address);
}
#Override
public void run() {
try {
URL url = new URL(address);
URLConnection urlConnection = url.openConnection();
BufferedReader scanner = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
int countOfLines = 0;
String input = scanner.readLine();
while (input != null && !input.equals("</body>")) {
countOfLines++;
if (input.startsWith("<tr> <td>addperson</td>")) {
input.replaceAll("<tr> <td>addperson</td>", "");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
// net.addUser(input);
} else if (input.startsWith("<tr> <td>addfriend</td>")) {
String[] bits = new String[2];
input.replaceAll("<tr> <td>addfriend</td>", "");
bits = input.split("</td> <td>");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
// net.friend(bits[0], bits[1]);
// net.friend(bits[1], bits[0]);
}
input = scanner.readLine();
}
scanner.close();
System.out.println(address + " has " + countOfLines + " lines");
} catch (IOException e) {
System.out.println("bad URL");
}
}
}
and here is output:
Start
http://google.com
http://yahoo.com
End
http://google.com has 8 lines
http://yahoo.com has 63 lines
Pay attention that your main thread is already finished when your readers just started yet. One word - multithreading.
Though, I don't like the quality of it. I know I am not code reviewer. Please try this!
public static void main(String[] args) {
Twitbook twitbook = new Twitbook();
String[] urls = new String[2];
urls[0] = "www.google.com";
urls[0] = "www.yahoo.com";
twitbook.readFriendData(urls);
}
public void readFriendData(String[] urls) {
CountDownLatch latch = new CountDownLatch(urls.length);
for (int x = 0; x < urls.length; x++) {
Runobject input = new Runobject(urls[x], this, latch);
input.run();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
public synchronized void addUser(String input) {
return;
}
public synchronized void friend(String bits1, String bits2) {
return;
}
RunObject class here
public class Runobject implements Runnable {
public String address;
public Twitbook net;
public CountDownLatch latch;
public Runobject(String theAdress, Twitbook net, CountDownLatch latch) {
address = theAdress;
this.net = net;
}
#Override
public void run() {
try {
URL url = new URL(address);
URLConnection urlConnection = url.openConnection();
BufferedReader scanner = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String input = scanner.readLine();
while (!input.equals("</body>")) {
if (input.startsWith("<tr> <td>addperson</td>")) {
input.replaceAll("<tr> <td>addperson</td>", "");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.addUser(input);
} else if (input.startsWith("<tr> <td>addfriend</td>")) {
String[] bits = new String[2];
input.replaceAll("<tr> <td>addfriend</td>", "");
bits = input.split("</td> <td>");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.friend(bits[0], bits[1]);
net.friend(bits[1], bits[0]);
}
input = scanner.readLine();
}
scanner.close();
} catch (IOException e) {
System.out.println("bad URL");
} finally {
latch.countDown();
}
}
Please consider better design. These links may help you to do better coding.
Thread pool is a good option.
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
CountDownLatch for finish all threads http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html
Runobject can be a private inner class as well.
Wait until child threads completed : Java
disclaimer :- Answered with help of other question and answers.
Can you please explain me where i am going wrong, am able to traverse each node but getting exceptions..
Have written code recursively to traverse through the jsonstring,
public static void main(String [] args) {
String jsonString = "{ \"developers\": [{ \"firstName\":\"Linus\" , \"lastName\":\"Torvalds\" }, " +
"{ \"firstName\":\"John\" , \"lastName\":\"von Neumann\" } ]}";
parse(jsonString);
}
public static void parse(Object jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString.toString());
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
Object value = jsonObject.get(key);
System.out.println(key+"==>"+value);
parse(value);
}
} catch (JSONException e) {
try {
JSONArray jsonArray = new JSONArray(jsonString.toString());
for (int i = 0; i < jsonArray.length(); i++)
{
Object value = jsonArray.get(i);
System.out.println("**"+value);
parse(value);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
JSON string is a key value pairs and many libraries gives access to traverse through...
Here is one of the example.
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
class JsonDecodeDemo
{
public static void main(String[] args)
{
JSONParser parser=new JSONParser();
String s = "[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
System.out.println("The 2nd element of array");
System.out.println(array.get(1));
System.out.println();
JSONObject obj2 = (JSONObject)array.get(1);
System.out.println("Field \"1\"");
System.out.println(obj2.get("1"));
s = "{}";
obj = parser.parse(s);
System.out.println(obj);
s= "[5,]";
obj = parser.parse(s);
System.out.println(obj);
s= "[5,,2]";
obj = parser.parse(s);
System.out.println(obj);
}catch(ParseException pe){
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
}
}
Find it really interesting here.
The same example, I have formatted the JSON string which you published,
public static void main(String[] args) {
String jsonString = "{\"developers\":[{\"firstName\":\"Linus\",\"lastName\":\"Torvalds\"},{\"firstName\":\"John\",\"lastName\":\"von Neumann\"}]}";
parse(jsonString);
}
public static void parse(Object jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString.toString());
Iterator<String> iter = jsonObject.keys();
while (iter.hasNext()) {
String key = iter.next();
Object value = jsonObject.get(key);
System.out.println(key + "==>" + value);
parse(value);
}
}
catch (JSONException e) {
try {
JSONArray jsonArray = new JSONArray(jsonString.toString());
for (int i = 0; i < jsonArray.length(); i++)
{
Object value = jsonArray.get(i);
System.out.println("**" + value);
parse(value);
}
}
catch (JSONException e1) {
// e1.printStackTrace();
}
// e.printStackTrace();
}
}
Output:
developers==>[{"lastName":"Torvalds","firstName":"Linus"},{"lastName":"von Neumann","firstName":"John"}]
**{"lastName":"Torvalds","firstName":"Linus"}
lastName==>Torvalds
firstName==>Linus
**{"lastName":"von Neumann","firstName":"John"}
lastName==>von Neumann
firstName==>John
Summary:
My Jsoup parser works perfectly on its own, but fails to gather any values once copy-pasted into one of my Android application's AsyncTask task classes. The 2d array is returned filled with nothing but nulls.
Long version:
I have been working on an application that uses page-scraping via Jsoup to pull and display content from various blogs. I have written a few parsers so far, and all seem to work as expected. Unfortunately, my most recent parser (written for nyc-shows.brooklynvegan.com), has been having issues.
Here is the parser method itself, invoked by a main method with print statements added. Run this yourself. It works (not perfectly, but it works).
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Main {
static String TAG_EVENT = "li.ds-entry";
static String TAG_TITLE = ".ds-entry-title";
static String TAG_LOCATION = ".location";
static String TAG_DATE_AND_TIME = ".ds-date";
static String TAG_TICKET_URL = ".ds-buy-tickets";
static String FEED_URL = "http://nyc-shows.brooklynvegan.com/";
public static void main(String[] args) throws IOException {
String values[][] = new String[50][6];
values = getFeedItems();
for (int i=0; i<values.length; i++) {
for (int j=0; j<6; j++) {
System.out.println(values[i][j]);
}
System.out.println("-----------------");
}
}
public static String[][] getFeedItems() throws IOException {
Document doc = null;
String values[][] = new String[50][6];
try{
doc = Jsoup.connect(FEED_URL).timeout(0).get();
Elements events = doc.select(TAG_EVENT);
String delimSpace = "[ ]";
int i = 0;
for (Element event : events) {
//Set event title
Element title = event.select(TAG_TITLE).first();
String titleString = title.text();
if (title != null) {
boolean isFake = checkFake(titleString);
if (!isFake) {
values[i][0] = titleString;
}
else {
continue;
}
}
//Set event date and time i guess
Element dateAndTime = event.select(TAG_DATE_AND_TIME).first();
if (dateAndTime != null) {
String[] dateAndTimeTokens = dateAndTime.text().split(delimSpace);
String date = dateAndTimeTokens[1];
String time = dateAndTimeTokens[3];
values[i][1] = date;
values[i][2] = time;
}
//Set price (tbd)
values[i][3] = "See Ticket";
//Set location
Element location = event.select(TAG_LOCATION).first();
if (location != null) {
values[i][4] = location.text();
}
//Set ticket urls
Element ticketContainer = event.select(TAG_TICKET_URL).first();
if (ticketContainer != null) {
String ticket = ticketContainer.select("a").attr("href");
values[i][5] = ticket;
}
else {
values[i][3] = "Free";
}
i++;
} //End of event loop
} //End of try clause
catch (IOException e) {
e.printStackTrace();
}
return values;
}
public static boolean checkFake(String s) {
boolean isFake = false;
String[] days = {"Today", "Tomorrow", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
for (int i=0; i<days.length; i++) {
if (s.contains(days[i])) {
isFake = true;
return isFake;
}
}
return isFake;
}
}
Now, here is the same exact method transported into an AsyncTask to be run in the background by my application while a loading screen is displayed.
package com.example.nylist;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class BVParser extends AsyncTask<Void, Void, String[][]> {
static String TAG_EVENT = "li.ds-entry";
static String TAG_TITLE = ".ds-entry-title";
static String TAG_LOCATION = ".location";
static String TAG_DATE_AND_TIME = ".ds-date";
static String TAG_TICKET_URL = ".ds-buy-tickets";
static String FEED_URL = "http://nyc-shows.brooklynvegan.com/";
Context context;
Activity activity;
public BVParser(Activity context) {
this.context = context.getApplicationContext();
this.activity = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(context, "Fetching...", Toast.LENGTH_LONG).show();
}
#Override
protected String[][] doInBackground(Void... param) {
String values[][] = new String[50][6];
try {
values = getFeedItems();
}
catch (IOException e) {
Log.d("ASSERT", "Exception occured during doInBackground", e);
e.printStackTrace();
}
Log.d("ASSERT", ("values successfully returned by doInBackground, first title is: "+values[0][0]));
return values;
}
protected void onPostExecute(String[][] result) {
super.onPostExecute(result);
int eventCount = result.length;
Log.d("ASSERT", ("event count in onPostExecute is: "+eventCount));
ListRow[] listrow_data = new ListRow[eventCount];
ListRow temp;
for (int i=0; i<eventCount; i++) {
if (result[i] != null) {
temp = new ListRow(context, result[i][0], result[i][1], result[i][2],
result[i][3], result[i][4], result[i][5], i);
listrow_data[i] = temp;
}
}
((EventList) activity).setList(listrow_data);
}
public String[][] getFeedItems() throws IOException {
Document doc = null;
String values[][] = new String[50][6];
int i = 0;
try{
Log.d("ASSERT","Made it to try block");
doc = Jsoup.connect(FEED_URL).timeout(0).get();
Elements events = doc.select(TAG_EVENT);
Log.d("ASSERT","printing events, whatever it is: "+events);
String delimSpace = "[ ]";
//******THIS LOOP NEVER BEGINS*****//
for (Element event : events) {
Log.d("ASSERT","Made it to getFeedItems's main for loop");
//Set event title
Element title = event.select(TAG_TITLE).first();
String titleString = title.text();
Log.d("ASSERT","This title is: "+titleString);
boolean isFake = checkFake(titleString);
if (!isFake) {
values[i][0] = titleString;
}
else {
continue;
}
//Set event date and time i guess
Element dateAndTime = event.select(TAG_DATE_AND_TIME).first();
if (dateAndTime != null) {
String[] dateAndTimeTokens = dateAndTime.text().split(delimSpace);
String date = dateAndTimeTokens[1];
String time = dateAndTimeTokens[3];
values[i][1] = date;
values[i][2] = time;
}
//Set price
values[i][3] = "See Ticket";
//Set location
Element location = event.select(TAG_LOCATION).first();
if (location != null) {
values[i][4] = location.text();
}
//Set ticket urls
Element ticketContainer = event.select(TAG_TICKET_URL).first();
if (ticketContainer != null) {
String ticket = ticketContainer.select("a").attr("href");
values[i][5] = ticket;
}
else {
values[i][3] = "Free";
}
i++;
} //End of event loop
} //End of try clause
catch (IOException e) {
Log.d("ASSERT","Exception during getFeedItems");
e.printStackTrace();
}
Log.d("ASSERT","The first title in getFeedItems before returning is: "+values[0][0]);
return values;
}
private static boolean checkFake(String s) {
boolean isFake = false;
String[] days = {"Today", "Tomorrow", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
for (int i=0; i<days.length; i++) {
if (s.contains(days[i])) {
isFake = true;
return isFake;
}
}
return isFake;
}
}
Debugging Attempts:
I added log statements throughout the code in order to debug the problem. If you run this, you will see that the problem seems to occur somewhere within getFeedItems() itself, specifically within the "try" block. Although the log statement at the beginning of the try statement appears, the for loop that runs through events isn't running at all, because the log statement at it's beginning never prints.
Question:
Can someone explain why the loop through events doesn't begin? Is events null, and if so, why? Why is there a discrepancy between the method running on it's own and the method running within my AsyncTask? I have been tearing my hair out. The logic in this parser is almost identical to the logic in the (working) others that I have written, and yet this is returning a 2d array with nothing but nulls. I have trouble even beginning to understand where the logic error might be, and yet I just can't seem to find the typo.
PS:
If comparing this with my other parser would help, let me know and I'll post the source. Thanks in advance.