storing transactions in an OrderedList - java

I'm a Java noob so please bear with me.
I'm having an issue with a java project I have to complete. We have to sort a list of 10,000 customer transactions, pick the top three customers that spent the most, then give five random customers gift cards, five of them starting at $20 and ending at $100, increasing in $20 increments. So far I have the following:
public static void main(String[] args) throws IOException {
BufferedReader inputStream = new BufferedReader (new FileReader("Transactions.txt"));
BufferedWriter outputStream = new BufferedWriter (new FileWriter("output.txt"));
Scanner trans = null;
try {
trans = new Scanner(new BufferedReader(new FileReader("Transactions.txt")));
trans.useDelimiter("s*");
while (trans.hasNext()) {
System.out.println(trans.next());
}
}
finally {
if (trans !=null) {
trans.close();
I'm confused as to how I would put this information into an OrderedList so it'll sort them in ascending order according to the amount they spent.
EDIT: Here are some lines from the transaction.txt file:
Order # Date First name Middle Initial Last name Address City State Zip Email Transaction Amount
1 8/26/2012 Kristina H Chung 947 Martin Ave. Muncie CA 46489 khchung#business.com $593
2 11/16/2012 Paige H Chen 15 MainWay Rd. Dallas HI 47281 phchen#business.com $516
3 11/10/2012 Sherri E Melton 808 Washington Way Brazil CA 47880 semelton#business.com $80
4 9/20/2012 Gretchen I Hill 56 Washington Dr. Atlanta FL 47215 gihill#business.com $989
5 3/11/2012 Karen U Puckett 652 Maplewood Ct. Brazil FL 46627 kupuckett#business.com $826
My apologies, but I have no idea how to make this look neat.

Related

Java: Looping issue within my file reading program

I've only been coding for a couple months so I'm still fairly new.
I'm writing a program using Java in Eclipse IDE that reads a file containing data about the changing popularity of various baby names over time and displays the data about a particular name (which is entered via keyboard by the user). Each line of the file stores a name followed by integers representing the name's popularity in each decade: 1900, 1910, 1920, and so on. My program prompts the user for a name, searchs the file for that name, and displays the data for that name from the file to the screen.
Example of data from txt file: Sam 58 69 99 131 168 236 278 380 467 408 466
Example of what should be displayed on screen:
Statistics on name "Sam"
1900: 58
1910: 69
1920: 99
1930: 131
...
This is my program:
public class fileAndExceptionHanding {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
FileInputStream fileByteStream = null;
Scanner inFS = null;
String userName = "";
String fileName = "";
File file = new File("names.txt");
List<Integer> numNamesOfYear = new ArrayList<Integer>();
boolean repeatSearch = true;
boolean repeatNameSearch = true;
int startingYear = 1900;
int yearCounter = startingYear;
char userKey;
fileByteStream = new FileInputStream("names.txt");
inFS = new Scanner(fileByteStream);
if (!file.exists()) {
file.createNewFile();
}
System.out.println("This program allows you to search through the data from the Social
Security Administration to see how popular a particular name has been since 1900.");
do {
System.out.println("Name? ");
userName = keyboard.next();
do {
while (!(fileName.equals(userName)) && inFS.hasNextLine()) {
fileName = inFS.next();
}
if (!(fileName.equals(userName))) {
System.out.println("Error! Name was not found. Please enter another name for our
system to search.");
userName = keyboard.next();
repeatNameSearch = true;
}
else {
repeatNameSearch = false;
}
} while (repeatNameSearch);
while (inFS.hasNextInt()) {
numNamesOfYear.add(inFS.nextInt());
}
System.out.println("Statistics on name " + "\"" + userName + "\"");
yearCounter = startingYear;
for (int i = 0; i < numNamesOfYear.size(); ++i) {
System.out.println(" " + yearCounter + ": " + numNamesOfYear.get(i));
yearCounter += 10;
}
numNamesOfYear.clear();
System.out.println("If you would like to search another name for popularity data,
please enter \"y\" to continue.");
System.out.println("If you wish to exit, please press any other key.");
userKey = keyboard.next().charAt(0);
if (!(userKey == 'y' || userKey == 'Y')) {
repeatSearch = false;
}
}while (repeatSearch);
fileByteStream.close(); // Closing file and input stream.
keyboard.close(); // Closing keyboard scanner.
inFS.close(); // Closing file scanner.
}
}
My program is running perfectly at first until the prompt for the user to enter "y" to continue or any other key to exit. When I enter "Y/y" and enter another name to search, my program doesn't repeat the name search and instead displays my "error invalid name, please enter a different name to search" message even though the name I entered is valid and inside the txt file.
Example of another name and data within the txt file that I tried to repeat search for:
Abbey 0 0 0 0 0 0 0 0 537 451 428
If you would like to search another name for popularity data, please enter "y"
to continue.
If you wish to exit, please press any other key.
y
Name?
Abbey
Error! Name was not found. Please enter another name for our system to search.
Entering "Sam" gives me correct data but if I press y to repeat loop and enter "Sam" again, it prints the following (Skips year data output):
This program allows you to search through the data from the Social Security Administration to see how popular a particular name has been since 1900.
Name?
Sam
Statistics on name "Sam"
1900: 58
1910: 69
1920: 99
1930: 131
1940: 168
1950: 236
1960: 278
1970: 380
1980: 467
1990: 408
2000: 466
If you would like to search another name for popularity data, please enter "y"
to continue.
If you wish to exit, please press any other key.
y
Name?
Sam
Statistics on name "Sam"
If you would like to search another name for popularity data, please enter "y"
to continue.
If you wish to exit, please press any other key.
I assume the problem lies somewhere within my loops, however it's proving difficult for me to find.
Any help or advice on where my looping problem lies would be greatly appreciated!
Thank you in advance.

How do I fix a NumberFormatException (from text file input)?

I was wondering if I could have some help with this NumberFormatException with code using a text input.
The result should be it being able to run properly and be able to first put 50 strings into the hashTable and then remove 10 afterwards.
I have tried placing the removeLine.next() inside a String datatype and then placing the String back inside the Integer.parseInt which didn't work.
Here is the class:
import java.io.*;
import java.util.*;
public class hashTest {
public static void main(String args[]) throws FileNotFoundException {
HashTable hashTable = new HashTable();
Scanner insert = new Scanner(new File("data1.txt"));
while(insert.hasNext()) {
String line = insert.nextLine();
Scanner insertLine = new Scanner(line);
insertLine.next();
insertLine.next();
int index = Integer.parseInt(insertLine.next());
String data = insertLine.nextLine();
hashTable.put(index, data);
}
Scanner remove = new Scanner(new File("data2.txt"));
while(remove.hasNext()) {
String line = remove.nextLine();
Scanner removeLine = new Scanner(line);
removeLine.next();
removeLine.next();
int index = Integer.parseInt(removeLine.next());
hashTable.remove(index);
}
}
}
data1.txt :
003 : 68682774 MALIK TULLER
004 : 24248685 FRANCE COELLO
005 : 25428367 DUSTY BANNON
006 : 79430806 MELVINA CORNEJO
007 : 98698743 MALIA HOGSTRUM
008 : 20316453 TOMASA POWANDA
009 : 39977566 CHONG MCOWEN
010 : 86770985 DUSTY CONFER
011 : 92800393 LINNIE GILMAN
012 : 31850991 WANETA DEWEES
013 : 81528001 NEAL HOLSTEGE
014 : 46531276 BRADLY BOMBACI
data2.txt :
92800393 LINNIE GILMAN
86770985 DUSTY CONFER
31850991 WANETA DEWEES
46531276 BRADLY BOMBACI
25428367 DUSTY BANNON
68682774 MALIK TULLER
18088219 PENNY JOTBLAD
48235250 KENNITH GRASSMYER
20316453 TOMASA POWANDA
54920021 TYSON COLBETH
22806858 LAVERNE WOLNIK
32244214 SHEMEKA HALLOWAY
81528001 NEAL HOLSTEGE
24248685 FRANCE COELLO
23331143 JUSTIN ADKIN
79430806 MELVINA CORNEJO
59245514 LESLEE PHIFER
64357276 SCOT PARREIRA
50725704 GENARO QUIDER
52298576 AUDIE UNCAPHER
54657809 MARTY ENOCHS
54526749 TOBI HEATLEY
24903965 ALONSO GILSTAD
84936051 DEONNA STRAZZA
62522327 AHMAD THAYER
90572271 ELIJAH METEVIER
88999386 ISMAEL ELKAN
NumberFormatExceptions with Integer.parseInt() are most often caused by attempting to read something into an int that is not actually an int. Try printing each line as it is read in. If you have a line that is not purely an int (e.g., Hello123), you will get this exception with Integer.parseInt(). A cleaner debugging method (and better coding practice) would be to catch the exception and print the problematic line. You will probably see right away what's causing the issue. When reading text input from anywhere, it's never good to assume that the data is of the format you're expecting.
When your input contains data other than the int values you need, you can read each line's values into an array and extract the proper value(s). Here's an example of how you might extract the values from a single line in your second data file. Keep in mind that this still makes assumptions about the input format and therefore, is not completely fool-proof.
try {
// Split the line by whitespace, saving the values into an array
String[] singleLineVals = someLine.split("\\s+");
// Extract the first value
int firstValue = Integer.parseInt(singleLineVals[0]);
} catch (NumberFormatException nfe) {
// Handle the exception
}

Retrieving data from nested href from jsoup

I would like retrieving data from nested href from jsoup, i mean:
i have href:
https://www.sherdog.com/news/rankings/2/Sherdogs-Official-Mixed-Martial-Arts-Rankings-164999
and i want to take each data from this 10 fighers, e.g.:
1.
STIPE MIOCIC
AGE: 37
or
ASSOCIATION:
STRONG STYLE FIGHT TEAM
2.
DANIEL CORMIER
AGE: 40
or
ASSOCIATION:
AMERICAN KICKBOXING ACADEMY
etc..
How to do this?
String url = "https://www.sherdog.com/news/rankings/2/Sherdogs-Official-Mixed-Martial-Arts-Rankings-164999";
Document document = Jsoup.connect(url).get();
Elements allH1 = document.select("h2");
for (Element href : allH1) {
Elements allAge = document.select("div.birth_info");
for (Element age : allAge) {
System.out.println(href.select("a[href]").text().toString());
System.out.println(age.select() // something there?);
}
The data you are looking for is present on seperate pages - each fighter has his own page, so you must crawl all the pages one by one to get the data.
First you have to get the link for each page, with the selector h2 > a[href]:
String url = "https://www.sherdog.com/news/rankings/2/Sherdogs-Official-Mixed-Martial-Arts-Rankings-164999";
Document document = Jsoup.connect(url).get();
Elements fighters = document.select("h2 > a[href]");
for (Element fighter : fighters) {
System.out.println(fighter.text() + " " + fighter.attr("href"));
}
After that, you can load each page and extract the data:
String fighterUrl = "https://www.sherdog.com" + fighter.attr("href");
Document doc = Jsoup.connect(fighterUrl).get();
Element fighterData = doc.select("div.data").first();
System.out.println(fighterData.text());
Combined together, you get:
String url = "https://www.sherdog.com/news/rankings/2/Sherdogs-Official-Mixed-Martial-Arts-Rankings-164999";
Document document = Jsoup.connect(url).get();
Elements fighters = document.select("h2 > a[href]");
for (Element fighter : fighters) {
System.out.println(fighter.text());
String fighterUrl = "https://www.sherdog.com" + fighter.attr("href");
Document doc = Jsoup.connect(fighterUrl).get();
Element fighterData = doc.select("div.data").first();
System.out.println(fighterData.text());
System.out.println("---------------");
}
And the (partial) output is:
Stipe Miocic
Born: 1982-08-19 AGE: 37 Independence, Ohio United States Height 6'4" 193.04 cm Weight 245 lbs 111.13 kg Association: Strong Style Fight Team Class: Heavyweight Wins 19 15 KO/TKO (79%) 0 SUBMISSIONS (0%) 4 DECISIONS (21%) Losses 3 2 KO/TKO (67%) 0 SUBMISSIONS (0%) 1 DECISIONS (33%)
Daniel Cormier
Born: 1979-03-20 AGE: 40 San Jose, California United States Height 5'11" 180.34 cm Weight 251 lbs 113.85 kg Association: American Kickboxing Academy Class: Heavyweight Wins 22 10 KO/TKO (45%) 5 SUBMISSIONS (23%) 7 DECISIONS (32%) Losses 2 1 KO/TKO (50%) 0 SUBMISSIONS (0%) 1 DECISIONS (50%) N/C 1
If you want to get the age, association and so as seperate fields, you'll have to extract them with regex.

Read tab delimited file and ignore empty space

I am working on a simple project in which a tab delimited text file is read into a program.
My problem:
When reading the text file there are regularly empty data spaces. This lack of data is causing an unexpected output. For lines that do not have data in the token[4] position all data read is ignored and "4" is displayed when I run a System.out.println(Just a test that the data is being read properly). When I incorporate a value in the token[4] position the data reads fine. It is not acceptable that I input a value in the token[4] position. See below for file and code.
2014 Employee Edward Rodrigo 6500
2014 Salesman Patricia Capola 5600 5000000
2014 Executive Suzy Allen 10000 55
2015 Executive James McHale 12500 49
2015 Employee Bernie Johnson 5500
2014 Salesman David Branch 6700 2000000
2015 Salesman Jonathan Stein 4600 300000
2014 Executive Michael Largo 17000 50
2015 Employee Kevin Bolden 9200
2015 Employee Thomas Sullivan 6250
My code is:
// Imports are here
import java.io.*;
import java.util.*;
public class EmployeeData {
public static void main(String[] args) throws IOException {
// Initialize variables
String FILE = "employees.txt"; // Constant for file name to be read
ArrayList<Employee> emp2014; // Array list for 2014 employees
ArrayList<Employee> emp2015; // Array list for 2015 employees
Scanner scan;
// Try statement for error handling
try {
scan = new Scanner(new BufferedReader(new FileReader(FILE)));
emp2014 = new ArrayList();
emp2015 = new ArrayList();
// While loop to read FILE
while (scan.hasNextLine()) {
String l = scan.nextLine();
String[] token = l.split("\t");
try {
String year = token[0];
String type = token[1];
String name = token[2];
String monthly = token[3];
String bonus = token[4];
System.out.println(year + " " + type + " " + name + " " + monthly + " " + bonus);
} catch (Exception a) {
System.out.println(a.getMessage());
}
}
} catch(Exception b) {
System.out.println(b.getMessage());
}
}
}
The output I receive for lines with "Employee" returns in an unexpected way.
Output:
run:
4
2014 Salesman Patricia Capola 5600 5000000
2014 Executive Suzy Allen 10000 55
2015 Executive James McHale 12500 49
4
2014 Salesman David Branch 6700 2000000
2015 Salesman Jonathan Stein 4600 300000
2014 Executive Michael Largo 17000 50
4
4
BUILD SUCCESSFUL (total time: 0 seconds)
I tried to use an if-then to test for null value in token[4] position but that didn't really help me. I've done quite a bit of searching with no success.
I am still very new to the programming world, so please pardon my coding inefficiencies. Any support and general feedback to improve my skills is greatly appreciated!
Thank you,
Bryan
Java Devil is right that the underlying issue because of an ArrayOutOfBoundsException. But it's also worth exploring why you didn't see that. As we discussed in the comments your "Try statement for error handling" is in fact not handling your errors at all, instead it is suppressing them, which is generally a poor plan as it allows your program to continue running even after your assumption (that it works correctly) has been violated.
Here's a slightly cleaned up version of your code. The underlying problem that causes the ArrayOutOfBoundsException is still there, but the issue would be immediately apparent if you'd structured your code this way instead. There's a few comments calling out issues inline.
public class EmployeeData {
// constants should be declared static and final, and not inside main
private static final String FILE = "employees.txt";
// If you have an exception and you don't know how to handle it the best thing
// to do is throw it higher and let the caller of your method decide what to do.
// If there's *nothing* you want to do with an exception allow main() to throw
// it as you do here; your program will crash, but that's a good thing!
public static void main(String[] args) throws IOException {
// Notice the <> after ArrayList - without it you're defining a "raw type"
// which is bad - https://stackoverflow.com/q/2770321/113632
ArrayList<Employee> emp2014 = new ArrayList<>();
ArrayList<Employee> emp2015 = new ArrayList<>();
// A try-with-resources block automatically closes the file once you exit the block
// https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
try (Scanner scan = new Scanner(new BufferedReader(new FileReader(FILE)))) {
while (scan.hasNextLine()) {
String l = scan.nextLine();
String[] token = l.split("\t");
// The code below this line assumes that token has at least five indicies;
// since that isn't always true you need to handle that edge case before
// accessing the array indicies directly.
String year = token[0];
String type = token[1];
String name = token[2];
String monthly = token[3];
String bonus = token[4];
System.out.println(year + " " + type + " " + name + " " + monthly + " " + bonus);
}
}
}
}
This is happening because you are actually getting an ArrayOutOfBoundsException and the message for that is '4'. Because the index of 4 is greater than the length of the array. You should put in your catch statement b.printStackTrace() as this will give you greater details when ever the caught exception occurs.
You can get around this by adding the following:
String bonus = "";
if(token.length > 4)
bonus = token[4];

How to parse nested json arrays in a single object in android

I have a json which has a number of nested JSONARRAY. here is the snippet.
{
"location": [
{
"name": "Perth",
"conferencelocation": [
{
"locationname":"Stage 1" ,
"guests": [
{
"guestid":"4074513426041094",
"guestname":"Keegan Connor Tracy",
"time":"9am",
"largeimg":"http://ozcomiccon.com/images/banner/Keegan.jpg",
"smallimg":"http://ozcomiccon.com/images/banner/Keeganresized.jpg",
"biotext": "Born in Windsor, Ontario, Canada, Tracy attended Wilfrid Laurier University in Waterloo, Ontario, Canada, where she orginally studied business. She later switched to psychology. She spent a year in Europe working in Dublin, Paris and Nice, where she was supposed to be completing her 4th year of study. She later returned to WLU to finish her degree. She moved to Vancouver, B.C. where she has had all of her acting jobs.",
"autographs":"$30 each (an 8x10 photograph will be included with each signature, or you may choose to have an appropriate personal item signed).",
"photographs":"Photo with Keegan $40.",
"genre":"acting",
"links": [
{"linkname":"Twitter", "url":"https://twitter.com/keegolicious" },
{"linkname":"IMDB", "url":"http://www.imdb.com/name/nm0870535/" }
]
},
{
"guestid":"1054713366041913",
"guestname":"Matthew Clark",
"time":"10am",
"largeimg":"http://ozcomiccon.com/images/banner/matthewclark.jpg",
"smallimg":"http://ozcomiccon.com/images/banner/matthewclarkresized.jpg",
"biotext": "Matthew Clark is a comic book artist living and working in Portland, Oregon. Having worked on art of some of the most well-known DC characters in comic book history, he recently did pencils for DC’s latest version of the Doom Patrol. Matthew is currently working on Ghost Rider for Marvel Comics, with whom he has signed an exclusive two-year deal.<br /><br />Matthew has lived in Portland for the past 13 years, just above an art gallery in the heart of downtown. He loves to walk around this fair city (mainly because he sold his car and needed to force himself to exercise). He’s a native Oregonian and that’s saying something. For the past 11 years he’s met Greg Rucka for coffee every Wednesday pretty much without fail at the same place (we pretty much carved our names in the table). Matthew was also one of the original founders of Mercury Studio (now Periscope Studio); he got his start at Studiosaurus.<br /><br />He still reads comics, loves what he does, and works very hard. Loves to meet new people, but is really quiet (and has great hair).",
"autographs":"Complimentary at guest's discretion.(Twitter)",
"photographs":"",
"genre":"comic",
"links": [
{"linkname":"Website", "url":"http://www.matthewclarkartist.com/" },
{"linkname":"Twitter", "url":"https://twitter.com/emceeartist" }
]
}
]
},
{
"locationname":"Stage 2" ,
"guests": [
{
"guestid":"106146633306036834",
"guestname":"Sean Williams",
"time":"8am",
"largeimg":"http://ozcomiccon.com/images/banner/seanwilliams.jpg",
"smallimg":"http://ozcomiccon.com/images/banner/seanwilliamsresized.jpg",
"biotext": "Sean Williams was born in the dry, flat lands of South Australia, where he still lives with his wife and family. He has been called many things in his time, including “the premier Australian speculative fiction writer of the age†(Aurealis), the “Emperor of Sci-Fi†(Adelaide Advertiser), and the “King of Chameleons†(Australian Book Review) for the diversity of his output. That award-winning output includes thirty-five novels for readers all ages, seventy-five short stories across numerous genres, the odd published poem, and even a sci-fi musical.<br /><br />He is a multiple recipient of the Aurealis and Ditmar Awards in multiple categories and has been nominated for the Philip K. Dick Award, the Seiun Award, and the William Atheling Jr. Award for criticism. He received the “SA Great†Literature Award in 2000 and the Peter McNamara Award for contributions to Australian speculative fiction in 2008.<br /><br />On the sci-fi front, he is best-known internationally for his original award-winning space opera series as well as several novels set in the Star Wars universe, many co-written with fellow-Adelaidean Shane Dix. These include the Astropolis, Evergence, Orphans and Geodesica series, and the computer game tie-in The Force Unleashed–the first such adaptation ever to debut at #1 on the New York Times bestseller list. A series for young readers, The Fixers, pitted an increasingly lost protagonist against zombies, cyborgs, and vampires across numerous universes. His most recent releases in the Star Wars universe are The Old Republic: Fatal Alliance and The Force Unleashed II.",
"autographs":"Complimentary at guest's discretion.",
"photographs":"",
"genre":"comic",
"links": [
{"linkname":"website", "url":"http://www.seanwilliams.com" }
]
},
{
"guestid":"17148603639603876",
"guestname":"Richard Dean Anderson",
"time":"10am",
"largeimg":"http://ozcomiccon.com/images/banner/richarddeananderson.jpg",
"smallimg":"http://ozcomiccon.com/images/banner/richarddeanandersonresized.jpg",
"biotext": "Richard Dean Anderson is probably best known as MacGyver, the clever and inventive nonviolent hero who solved problems in his own unique way for seven successful seasons on ABC. In his roles before and since, this gifted actor has continued to demonstrate his remarkable talent and versatility.<br /><br />Richard was born on January 23, 1950 in Minneapolis, Minnesota. His father, Stuart Anderson, taught English, drama, and humanities at a local high school, and is an accomplished jazz bassist. His mother, Jocelyn, is an artist, talented in both painting and sculpture. Richard is the eldest of four sons. He and his brothers, Jeffrey Scott, Thomas John, and James Stuart, grew up in the Minneapolis suburb of Roseville, where Richard developed early interests in sports, the arts, music, and acting.<br /><br />Like many boys growing up in Minnesota, Richard dreamed of becoming a professional hockey player. However, at the age of 16, he broke both arms, in separate accidents three weeks apart, while playing in high school hockey games. He put aside his dreams of playing professionally, though he still harbors a deep love for the sport. Richard talks of his restlessness growing up, his early desire to explore, and his adventures hitchhiking and hopping freight trains. At the age of 17, he took a 5641 mile bicycle trip from his home in Minnesota through Canada and Alaska, an experience which was sparked by his sense of adventure and discovery, but which also gave him a more centered sense of direction.",
"autographs":"Autograph from Richard $50.",
"photographs":"Photograph with Richard $80. SG1 double shot with Richard and Teryl Rothery $150. SG1 triple shot with Richard, Teryl Rothery and Corin Nemec $200.",
"genre":"acting",
"links": [
{"linkname":"Website", "url":"http://www.rdanderson.com/" },
{"linkname":"Twitter", "url":"https://twitter.com/andersonrdean" }
]
}
]
}
]
}
]
I have object class named Name, and I want to put all the data of the name(perth) jsonobject as a single object of the Name class. But it is not adding data in the arraylist correctly, more clearly the guestid, guestname etc tag values are being saved but overwrites the previous one. Here is my parsing code:
public ArrayList<Guest> parseInitiator() throws ClientProtocolException,
IOException, JSONException {
InputStream is = new FileInputStream(new File(Url));
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String mResponse = new String(buffer);
JSONObject first = new JSONObject(mResponse);
JSONArray firstarray = first.getJSONArray("location");
ArrayList<Guest> parsedData = new ArrayList<Guest>();
for (int i = 0; i < firstarray.length(); i++) {
JSONObject jonj = firstarray.getJSONObject(i);
name = jonj.getString("name");
JSONArray confarray = jonj.getJSONArray("conferencelocation");
locationname = new String[confarray.length()];
for (int j = 0; j < confarray.length(); j++) {
JSONObject conobbj = confarray.getJSONObject(j);
locationname[j] = conobbj.getString("locationname");
JSONArray guestarray = conobbj.getJSONArray("guests");
guestid= new String[guestarray.length()];
guestname= new String[guestarray.length()];
time= new String[guestarray.length()];
largeimg= new String[guestarray.length()];
smallimg= new String[guestarray.length()];
biotext= new String[guestarray.length()];
autographs= new String[guestarray.length()];
photographs= new String[guestarray.length()];
genre= new String[guestarray.length()];
for (int k = 0; k < guestarray.length(); k++) {
JSONObject guestobbj = guestarray.getJSONObject(k);
guestid[k] = guestobbj.getString("guestid");
guestname[k] = guestobbj.getString("guestname");
time[k] = guestobbj.getString("time");
largeimg[k] = guestobbj.getString("largeimg");
smallimg[k] = guestobbj.getString("smallimg");
biotext[k] = guestobbj.getString("biotext");
autographs[k] = guestobbj.getString("autographs");
photographs[k] = guestobbj.getString("photographs");
genre[k] = guestobbj.getString("genre");
JSONArray linkar = guestobbj.getJSONArray("links");
arlink= new String[linkar.length()];
arurl= new String[linkar.length()];
for (int l = 0; l < linkar.length(); l++) {
JSONObject linkobj = linkar.getJSONObject(l);
arlink[l] = linkobj.getString("linkname");
arurl[l] = linkobj.getString("url");
}
}
}
parsedData.add(new Guest(name,locationname, guestid, guestname, time, largeimg, smallimg, biotext,
autographs, photographs, genre,arlink, arurl));
}
return parsedData;
}
Can anyone make me clear about the mistake I have made?
So here is my solution:
JSONObject first = new JSONObject(mResponse);
JSONArray locArr = first.getJSONArray("location"); // contains one object
JSONObject locArrObj = locArr.getJSONObject(0); // cotains one "out" array
JSONArray conferenceLocArr = locArrObj.getJSONArray("conferencelocation");
// this array has two objects and each object has array
JSONObject o = null;
JSONArray arr = null;
for (int i = 0; i < conferenceLocArr.length(); i++) {
o = conferenceLocArr.getJSONObject(i); // it has one array
arr = o.getJSONArray("guests");
// do your work with Stage 1 and guests
// and for second object for Stage 2 and guests.
}

Categories