cannot write in the file [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
good day guys, im creating a program that will write the data to a text file. the data is coming from an array list, it is a data that is solved from the array list e.g :
public double getGincome(){
gincome=rpd*dwork;
return gincome;
}
the problem is i cannot write to my txt file..here is my code in writing the data:
public static boolean payrollWriteToFile(String filename) {
boolean saved = false;
PrintWriter pw = null; // pw is a PrintWriter identifier
try {
// instantiate pw as PrintWriter, FileWriter
pw = new PrintWriter(new FileWriter(filename));
try {
// for each loop. each data from payrolls is
written to parameter
for (Person payroll : payrolls) {
pw.println(payroll.getName());
pw.println(payroll.getGincome());
pw.println(payroll.getSss());
pw.println(payroll.getPagibig());
pw.println(payroll.getPhil());
pw.println(payroll.getDeduc());
pw.println(payroll.getNincome());
}
saved = true;
} finally {
pw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return saved;
}
heres my array
public class Person {
private String name;
private String add;
private String gender;
private String status;
public double rpd;
public double dwork;
public static int EmployeeCount;
public double gincome;
public double nincome;
public double deduc;
public double sss;
public double pagibig;
public double phil;
public Person(double gincome, double nincome, double deduc, double sss, double
pagibig, double phil ) {
this.gincome = gincome ;
this.nincome = nincome;
this.deduc = deduc;
this.sss = sss;
this.pagibig= pagibig;
this.phil = phil;
}
Person( String name , double gincome, double sss, double pagibig, double phil,
double deduc, double nincome){
this.gincome = gincome;
this.nincome = nincome;
this.sss = sss;
this.pagibig = pagibig;
this.phil = phil;
this.deduc = deduc;
}
Person(String name, String add, String gender, String status, double dwork, double rpd)
{
this.name = name;
this.add = add;
this.gender = gender;
this.status = status;
this.rpd = rpd;
this.dwork = dwork;
}
public double getGincome(){
gincome=rpd*dwork;
return gincome;
}
public double getDeduc(){
double sss = gincome *.03 ;
double pagibig = gincome *.02;
double philhealth = gincome* .0125 ;
deduc= sss + pagibig +philhealth;
return deduc;
}
public double getNincome(){
return nincome;
}
public double getSss(){
return sss = getGincome() * .03;
}
public double getPagibig(){
return pagibig = getGincome() * .02;
}
public double getPhil(){
return phil = getGincome() * .0125;
}
public static int getEmployeeCount(){
return EmployeeCount;
}
public String getName() {
return name;
}
public String getAdd() {
return add;
}
public String getGender() {
return gender;
}
public String getStatus() {
return status;
}
public double getRpd(){
return rpd;
}
public double getDwork(){
return dwork;
}
public void setName(String name) {
this.name = name;
}
public void setAdd(String add) {
this.add = add;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setStatus(String status) {
this.status = status;
}
public void setRpd(double rpd){
this.rpd = rpd;
}
public void setdWork(double dwork){
this.dwork = dwork;
}
}
i hope you can help me guys.

Use a BufferedWriter instead, if you are allowed to (maybe you aren't for homework purposes or some other reason).
File file = new File(filename);
if (!file.exists())
{
try
{
file.createNewFile();
} catch (Exception e)
{
e.printStackTrace();
}
}
try
{
// Read to end of file for writing
BufferedReader read = new BufferedReader(new FileReader(file));
String complete = "";
String line = null;
while ((line = read.readLine()) != null)
{
complete += line + "\n";
}
// Write your data
BufferedWriter write = new BufferedWriter(new FileWriter(file));
for (Person payroll : payrolls)
{
write.append(payroll.getName());
write.append(Double.toString(payroll.getGincome()));
write.append(Double.toString(payroll.getSss()));
write.append(Double.toString(payroll.getPagibig()));
write.append(Double.toString(payroll.getPhil()));
write.append(Double.toString(payroll.getDeduc()));
write.append(Double.toString(payroll.getNincome()));
}
read.close();
write.close();
} catch (Exception e)
{
e.printStackTrace();
}
This should work if your for loop and all your getter methods are properly used.

Try pw.flush(); before pw.close(); in the finally block. It may solve the problem.
Otherwise the code looks correct to me.

Related

Java: Arraylist out of bounds when processing file [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am trying to create an ArrayList that reads a .csv file, processes the data into an ArrayList, and then print the list out.
My code so far.
The BankRecords class
import java.io.*;
import java.util.*;
public class BankRecords
{
String sex, region, married, save_act, current_act, mortgage, pep;
int children;
double income;
private String id;
private int age;
public BankRecords(String gender, String area, String marriage, String SaveAccount, String CurrentAccount, String HouseBill, String pepp, int minors, double paycheck, String identification, int years)
{
this.sex = gender;
this.region = area;
this.married = marriage;
this.save_act = SaveAccount;
this.current_act = CurrentAccount;
this.mortgage = HouseBill;
this.pep = pepp;
this.children = minors;
this.income = paycheck;
this.id = identification;
this.age = years;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getSex()
{
return sex;
}
public void setSex(String sex)
{
this.sex = sex;
}
public String getRegion()
{
return region;
}
public void setRegion(String region)
{
this.region = region;
}
public String getMarried()
{
return married;
}
public void setMarried(String married)
{
this.married = married;
}
public String getSave_act()
{
return save_act;
}
public void setSave_act(String save_act)
{
this.save_act = save_act;
}
public String getCurrent_act()
{
return current_act;
}
public void setCurrent_act(String current_act)
{
this.current_act = current_act;
}
public String getMortgage()
{
return mortgage;
}
public void setMortgage(String mortgage)
{
this.mortgage = mortgage;
}
public String getPep()
{
return pep;
}
public void setPep(String pep)
{
this.pep = pep;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public int getChildren()
{
return children;
}
public void setChildren(int children)
{
this.children = children;
}
public double getIncome()
{
return income;
}
public void setIncome(double income)
{
this.income = income;
}
}
The Client abstract class
import java.io.*;
import java.util.*;
public abstract class Client
{
static ArrayList<List<String>> BankArray = new ArrayList<>(25);
static BankRecords robjs[] = new BankRecords[600];
public static void readData()
{
try
{
BufferedReader br;
String filepath = "C:\\Users\\eclipse-workspace\\Bank_Account\\src\\bank-Detail.csv";
br = new BufferedReader(new FileReader (new File(filepath)));
String line;
while ((line = br.readLine()) != null)
{
BankArray.add(Arrays.asList(line.split(",")));
}
}
catch (Exception e)
{
e.printStackTrace();
}
processData();
}
public static void processData()
{
int idx=0;
for (List<String> rowData: BankArray)
{
robjs[idx] = new BankRecords(null, null, null, null, null, null, null, idx, idx, null, idx);
robjs[idx].setId(rowData.get(0));
robjs[idx].setAge(Integer.parseInt(rowData.get(1)));
idx++;
}
printData();
}
public static void printData()
{
System.out.println("ID\tAGE\tSEX\tREGION\tINCOME\tMORTGAGE");
int final_record = 24;
for (int i = 0; i < final_record; i++)
{
System.out.println(BankArray.get(i) + "\t ");
}
}
}
The BankRecordsTest class (extends Client)
import java.util.*;
import java.io.*;
public class BankRecordsTest extends Client
{
public static void main(String args [])
{
readData();
}
}
The error
And here is the error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at java.util.Arrays$ArrayList.get(Unknown Source)
at Client.processData(Client.java:33)
at Client.readData(Client.java:24)
at BankRecordsTest.main(BankRecordsTest.java:7)
I'm not sure what the index problem is. Do note that if you run the ReadData() and PrintData() functions separately, the code runs fine but the ProcessData() method causes issues.
I think your data is likely not clean and you are making assumptions about the length of your array. The error you are getting stems from this line:
robjs[idx].setAge(Integer.parseInt(rowData.get(1)));
Clearly, rowData doesn't have 2 items (or more). This is why you are getting ArrayIndexOutOfBoundsException. So you want to check where your variable was initialized. You quickly realize it comes from
for (List<String> rowData: BankArray)
So then, the following question is where BankArray gets initialized. That happens in 2 places. First of all
static ArrayList<List<String>> BankArray = new ArrayList<>(25);
You are creating an empty list. So far so good. Note that you don't need to (and therefore shouldn't) initialize with a size. Lists are not like arrays insofar as they can easily grow and you don't need to give their size upfront.
The second place is
BankArray.add(Arrays.asList(line.split(",")));
This is likely where the issue comes from. Your row variable contains the results of Arrays.asList(line.split(",")). So the size of that list depends on the number of commas in that string you are reading. If you don't have any commas, then the size will be 1 (the value of the string itself). And that's what leads me to concluding you have a data quality issue.
What you should really do is add a check in your for (List<String> rowData: BankArray) loop. If for instance, you expect 2 fields, you could write something along the lines of:
if (rowData.size()<2){
throw new Exception("hmmm there's been a kerfuffle');
}
HTH

Arraylist read from file outputs twice

I have an ArrayList of items - name, account number and balance read from a .txt file. Why is the output twice? (I've only 4 lines in my file each containing- name; account number; balance)
I want things above blue line only. Why is it displaying twice?
This is my class to retrieve from file and print
class BankAccount{ //core banking facilities
PrintStream pw=System.out;
protected String name;
protected long accountNumber;
protected float balance=0;
public String choiceList="\n1.AddAccount\n2.Withdraw\n3.Deposit\n4.MyAccount";
public BankAccount(String name,long accountNumber,float balance){
this.accountNumber=accountNumber;
this.name=name;
this.balance = balance;
}
public String getName(){
return this.name;
}
public long get_Account_no(){
return this.accountNumber;
}
public float get_Balance(){
return this.balance;
}
public BankAccount(){//loads from file to arraylist
BufferedReader in = null;
ArrayList <BankAccount> customer_list=new ArrayList<BankAccount>();
try {
in = new BufferedReader(new FileReader("bankfile.txt"));
String str;
while ((str = in.readLine()) != null) {
String[] temp_list=str.split(";");
accountNumber=Long.parseLong(temp_list[1]);
balance=Float.parseFloat(temp_list[2]);
BankAccount customer = new BankAccount(temp_list[0],accountNumber,balance);
customer_list.add(customer);
}
}catch (FileNotFoundException e) {e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
} finally {
if (in != null) {
try{ in.close();
} catch(Exception e){e.printStackTrace();}
}
}
for(BankAccount c: customer_list) pw.println(c.getName()+" "+c.get_Balance()+"\n");
}
}
and my main is-
class banker {
public static void main(String args[]){
additional_functionality af=new additional_functionality();
BankAccount ba=new BankAccount();
ba.pw.println("This is.. \n \t\tTHE BANK\nplease wait...");
String ch=JOptionPane.showInputDialog(ba.choiceList);
Integer choice=Integer.parseInt(ch);
switch(choice){
case 1: af.addAcount();
break;
case 4: //af.findAccount();
break;
default: JOptionPane.showMessageDialog(null,"Wrong Choice!","ERR",JOptionPane.ERROR_MESSAGE);
}System.exit(0);
}
my text file is-
bankfile.txt
Sorry, i'm not getting error. Hope this will helps you. I think that problem is that you twice run this constructor. Also, I run your code. And it's works.
My Main.java
public class Main {
public static void main(String[] args) {
// write your code
new BankAccount();
}
}
My file bankfile.txt
lala;0;0
coca;0;1
bola;1;1
My BankAccount.java
import java.io.*;
import java.util.ArrayList;
public class BankAccount {
private String name;
private long accountNumber;
private float balance;
public BankAccount(){//loads from file to arraylist
BufferedReader in = null;
ArrayList<BankAccount> customer_list=new ArrayList<BankAccount>();
try {
in = new BufferedReader(new FileReader("bankfile.txt"));
String str;
while ((str = in.readLine()) != null) {
String[] temp_list=str.split(";");
accountNumber=Long.parseLong(temp_list[1]);
balance=Float.parseFloat(temp_list[2]);
BankAccount customer = new BankAccount(temp_list[0],accountNumber,balance);
customer_list.add(customer);
}
for(BankAccount c: customer_list) System.out.println(c.getName()+" "+c.get_Balance());
}catch (FileNotFoundException e) {e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
} finally {
if (in != null) {
try{ in.close();
} catch(Exception e){e.printStackTrace();}
}
}
}
public BankAccount(String name, Long accountNumber, float balance){
this.name = name;
this.balance = balance;
this.accountNumber = accountNumber;
}
public String getName() {
return name;
}
public long getAccountNumber() {
return accountNumber;
}
public float get_Balance() {
return balance;
}
}

Reading Text file and adding the objects into an Array

I have a Contact class that basically just holds information of a contact. We store the contact object in an array.
I had to write the array into a text file, and I knew how to do that, but now I must read that file and store the objects back into an array, and I'm stuck!
Note, ContactList Below also uses class Contact, which just basically has get/set methods.
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
public class ContactList{
int ptr = -1;
Contact[] list;
int contactLength;
public ContactList(){//second constructor needed
list=new Contact[20];
contactLength=20;
for(int i =0;i<20;i++){
list[i]=null;
}
}
public ContactList(int length){//second constructor needed
list=new Contact[length];
contactLength=length;
for(int i =0;i<length;i++){
list[i]=null;
}
}
public boolean add(Contact c){
boolean found = false;
int i = 0;
while(!found&&i<20){
if (list[i]==null){
list[i]=c;
found=true;
ptr=i;
}
i++;
}
return found;
}
public Contact find(String name){
boolean found=false;
int i =0;
while(i<contactLength&&!found){
ptr++;
if(ptr==contactLength){
ptr=0;
}
if(list[ptr]!=null){
if (list[ptr].getName().contains(name)){
found=true;
return list[ptr];
}
}
i++;
}
return null;
}
public Contact remove(){
Contact current= list[ptr];
list[ptr]=null;
return current;
}
public void displayContacts(){
for(int i =0;i<contactLength;i++){
if(list[i]!=null){
System.out.println(list[i].toString());
}
else {
System.out.println("Empty:");//"Name:\nAddress:\nPhone\nComments:"
}
}
}
public boolean write (String fileName){
PrintWriter p = null;
try {
p = new PrintWriter(new File(fileName));
} catch (Exception e) {
return false;
}
for(int i =0;i<contactLength;i++){
if(list[i]!=null){
p.println(list[i].toString());
}}
p.close();
return true;
}
public class Contact {
private String name;
private long phone;
private String address;
private String comments;
public void setName( String name){
this.name =name;
}
public String getName(){
return name;
}
public void setPhone(long phone){
this.phone=phone;
}
public long getPhone(){
return phone;
}
public void setAddress(String address){
this.address= address;
}
public String getAddress(){
return address;
}
public void setComments( String comments){
this.comments= comments;
}
public String getComments(){
return comments;
}
public String toString(){
return ("Name:\t\t"+name+"\nAddress:\t"+address+"\nPhone Number:\t"+phone+"\nComments:\t"+comments +"\n");
}
public Contact(String name, long phone, String address, String comments){
this.name=name;
this.phone=phone;
this.address=address;
this.comments=comments;
}
public boolean equals(Contact other){
if (this.name!=other.name){
return false;
}
if (this.phone!=other.phone){
return false;
}
if (this.address!=other.address){
return false;
}
if (this.comments!=other.comments){
return false;
}
return true;
}
Here is what I have so far...
public boolean read(String fileName){
Scanner s = null;
try {
s = new Scanner(new File(fileName));
} catch (Exception e) { // returns false if fails to find fileName
return false;
}
for(int i=0; i)
}
And YES I must use array! No lists! And nothing fancy please, this is an intro class, I won't understand it. Just scanner.
I see the pros and cons in the comment section, what about putting an end to the debate, given how you write I'm guessing you will need something like:
public static void read(String fileName){
try(BufferedReader in = new BufferedReader(new FileReader(fileName))){
String line = null;
String[] contact = new String[4];
int contactCounter = 0;
int buffer = 0;
while ((line = in.readLine()) != null){
buffer = line.split("\t").length - 1;
contact[contactCounter] = line.split("\t")[buffer];
contactCounter++;
if (contactCounter == 3){
new Contact(contact[0], contact[1], contact[2], contact[3]);
contactCounter == 0;
}
}
} catch (IOException e){
e.printStackTrace();
}
}
I strongly suggest you improve how you serialize your Contact because this format is a mess, especially having not clear boundaries, the best I could figure was counting 4 EOL to create a new Contact.
Maybe have a look at csv format: https://en.wikipedia.org/wiki/Comma-separated_values

Java - Type Mismatch: Cannot Convert From Element type String[] to List<String>

I'm unfamiliar with getters and setters (and basically just Java) but I have to use them for this assignment, so if I did anything wrong with those please tell me.
The more important issue is the error that I am getting on my method. The word for word instructions from my assignment for the particular method I'm working on are:
Your processData() method should take all the record data from your ArrayList and add the data into each of your instance fields via your setters.
But I keep getting an error that says:
Type mismatch: cannot convert from element type String[] to List
On the line that says "for (List<String> rowData: content)" on the word content.
Thank you very much for any help you can give me.
My code so far:
public abstract class Client {
String file = "bank-Detail.csv";
ArrayList<String[]> bank = new ArrayList<>();
static Client o[] = new Client[12];
public Client(String file) {
this.file = file;
}
private String ID;
private String Age;
private String Sex;
private String Region;
private String Income;
private String Married;
private String Children;
private String Car;
private String Save_Act;
private String Current_Act;
private String Mortgage;
private String Pep;
public List<String[]> readData() throws IOException {
//initialize variable
int count = 0;
//name file
String file = "bank-Detail.txt";
//make array list
List<String[]> content = new ArrayList<>();
//trycatch for exceptions
try {
//file reader
BufferedReader br = new BufferedReader(new FileReader(file));
//string to add lines to
String line = "";
while ((line = br.readLine()) != null) {
content.add(line.split(","));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
processData(content);
return content;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getAge() {
return Age;
}
public void setAge(String age) {
this.Age = age;
}
public String getSex() {
return Sex;
}
public void setSex(String sex) {
Sex = sex;
}
public String getRegion() {
return Region;
}
public void setRegion(String region) {
Region = region;
}
public String getIncome() {
return Income;
}
public void setIncome(String income) {
Income = income;
}
public String getMarried() {
return Married;
}
public void setMarried(String married) {
Married = married;
}
public String getChildren() {
return Children;
}
public void setChildren(String children) {
Children = children;
}
public String getCar() {
return Car;
}
public void setCar(String car) {
Car = car;
}
public String getSave_Act() {
return Save_Act;
}
public void setSave_Act(String save_Act) {
Save_Act = save_Act;
}
public String getCurrent_Act() {
return Current_Act;
}
public void setCurrent_Act(String current_Act) {
this.Current_Act = current_Act;
}
public String getMortgage() {
return Mortgage;
}
public void setMortgage(String mortgage) {
this.Mortgage = mortgage;
}
public String getPep() {
return Pep;
}
public void setPep(String pep) {
Pep = pep;
}
public String toString() {
return "[ID = " + ", age=";
/// ect....
}
public void processData(List<String[]> content) {
int index = 0;
for (List<String> rowData : content) {
//initialize array of objects
//o[index] = new Client();
//use setters to populate your array of objects
o[index].setID(rowData.get(0));
o[index].setAge(rowData.get(1));
o[index].setRegion(rowData.get(3));
o[index].setSex(rowData.get(2));
o[index].setIncome(rowData.get(4));
o[index].setMarried(rowData.get(5));
o[index].setChildren(rowData.get(6));
o[index].setCar(rowData.get(7));
o[index].setSave_Act(rowData.get(8));
o[index].setCurrent_Act(rowData.get(9));
o[index].setMortgage(rowData.get(10));
o[index].setPep(rowData.get(11));
System.out.println(rowData);
index++;
}
}
public void printData() {
}
}
The problem is in the processData method. The type of content is List<String[]>. So when you try to loop this list, each element is a String array, not List. Also, since each element in your list is a String array, you can access the elements of each of the String Array elements of the list by using the normal array square brackets, instead of get method of List. Try the following fix:
public void processData(List<String[]> content) {
int index=0;
for (String[] rowData: content){
//initialize array of objects
//o[index] = new Client();
//use setters to populate your array of objects
o[index].setID(rowData[0]);
o[index].setAge(rowData[1]);
o[index].setRegion(rowData[3]);
o[index].setSex(rowData[2]);
o[index].setIncome(rowData[4]);
o[index].setMarried(rowData[5]);
o[index].setChildren(rowData[6]);
o[index].setCar(rowData[7]);
o[index].setSave_Act(rowData[8]);
o[index].setCurrent_Act(rowData[9]);
o[index].setMortgage(rowData[10]);
o[index].setPep(rowData[11]);
System.out.println(rowData);
index++;
}
}
As your error hints at... content is a List<String[]>, so it contains String[] elements, not List<String> elements.
If your end goal is a list of Client objects, just make the method List<Client> readData() instead.
List<Client> clients = new ArrayList<Client>();
BufferedReader br = null;
try {
//file reader
br = new BufferedReader(new FileReader(file));
//string to add lines to
String line = "";
Client c = null;
while ((line = br.readLine()) != null) {
c = new Client();
String[] rowData = line.split(",");
c.setID(rowData.get(0));
...
clients.add(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (Exception e) {}
}
return clients;

java.lang.NullPointerException while reading value from json to java object

Here I am reading json value from youtube to java.
I am getting values properly except the thumbnail data while getting thumbnail object value i am getting java.lang.NullPointerException
public class JsonVideoDetais {
public static void main(String... args) {
BufferedReader reader = null;
StringBuilder buffer = null;
try {
String link = "https://gdata.youtube.com/feeds/api/videos/" + "aa_wFClyiVE" + "?v=2&alt=jsonc";
URL url = new URL(link);
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
buffer = new StringBuilder();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1) {
buffer.append(chars, 0, read);
}
} catch (Exception e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
Logger.getLogger(JsonVideoDetais.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
videoDetails data;
data = new Gson().fromJson(buffer.toString(), videoDetails.class);
System.out.println(data.getData().getTitle());
System.out.println(data.getData().getTn().getHqDefault());
System.out.println(data.getData().getTn().getSqDefault());
}
}
class videoDetails {
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String toString() {
return String.format("data:%s", data);
}
}
class Data {
private String id;
private String title;
private String description;
private int duration;
private Thumbnail tn;
public Thumbnail getTn() {
return tn;
}
public void setTn(Thumbnail tn) {
this.tn = tn;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String toString() {
return String.format("title:%s,id:%s,description:%s,tn:%s,duration:%d", title, id, description, tn, duration);
}
}
class Thumbnail {
private String sqDefault;
private String hqDefault;
public String getSqDefault() {
return sqDefault;
}
public void setSqDefault(String sqDefault) {
this.sqDefault = sqDefault;
}
public String getHqDefault() {
return hqDefault;
}
public void setHqDefault(String hqDefault) {
this.hqDefault = hqDefault;
}
public String toString() {
return String.format("sqDefault:%s,hqDefault:%s", hqDefault, sqDefault);
}
}
I am getting following exception
Exception in thread "main" java.lang.NullPointerException
at utility.JsonVideoDetais.main(JsonVideoDetais.java:52)
while calling
System.out.println(data.getData().getTn().getHqDefault());
System.out.println(data.getData().getTn().getSqDefault());
If you wll see this link. It is having value for sqDefault and hqDefault
I would like to fetch the value of sqDefault and hqDefault.
How to do this.
In your Data class, i created an object like this. I guess the Thumbnail object is getting set to thumbnail, tn is not working on my side too.
private Thumbnail thumbnail;// instead of tn
and the resultant output is : -
Blood Glucose Hindi - Dr. Anup, MD Teaches Series
https://i1.ytimg.com/vi/aa_wFClyiVE/hqdefault.jpg
https://i1.ytimg.com/vi/aa_wFClyiVE/default.jpg
Using debugger to find out which object is null is fastest way to solve your problem.
OR
Find the null return value with the following code:
System.out.println(data);
System.out.println(data.getData());
System.out.println(data.getData().getTn());
--The following text are newly added-----------------
Well, I have run your program on my laptop, and it seem that the json response of https://gdata.youtube.com/feeds/api/videos/aa_wFClyiVE?v=2&alt=jsonc#data/thumbnail/hqDefault contains no tn field at all. That's why you always got null value.

Categories