**In this i am trying to sort an array of objects by their id's whose age > 30 but compiler is giving error in searchVoteByAge function in while loop :
while((j>-1)&& (v[j].getVoterId() > key.getVoterId())) in this line **
error :Exception in thread "main"
java.lang.NullPointerException at algorithms.Dijstra_algo.searchVoterByAge(Dijstra_algo.java:77) at
algorithms.Dijstra_algo.main(Dijstra_algo.java:55)
import java.util.Scanner;
public class Demo
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Voter voter[]=new Voter[4];
for(int i=0;i<voter.length;i++){
int v_id=sc.nextInt();
sc.nextLine();
String v_nme=sc.next();
sc.nextLine();
int v_age=sc.nextInt();
sc.nextLine();
boolean is_vote_casted=sc.nextBoolean();
sc.nextLine();
String constituency=sc.next();
sc.nextLine();
voter[i]=new Voter();
voter[i].setVoterId(v_id);
voter[i].setVoterName(v_nme);
voter[i].setVoterAge(v_age);
voter[i].setVoteCasted(is_vote_casted);
voter[i].setConstituency(constituency);
}
String cons=sc.next();
int c=findTotal(voter,cons);
if(c>0)
System.out.println(c);
else
System.out.println("No votes Casted");
Voter v[]=searchVoterByAge(voter);
if(v.length > 0){
for(Voter obj: v){
System.out.println(obj.getVoterId());
}
}
else
System.out.println("No such voters");
}
private static Voter[] searchVoterByAge(Voter[] voters) {
Voter v[]=new Voter[voters.length];
int k=0,f=0;
for(Voter obj:voters) {
if(obj.getVoterAge()<30) {
v[k]=new Voter();
v[k++]=obj;
f=1;
}
}
for(int i=1;i<v.length;i++) {
Voter key=v[i];
int j=i-1;
while((j>-1)&& (v[j].getVoterId() > key.getVoterId())) {
v[j+1]=v[j];
j--;
}
v[j+1]=key;
}
if(f == 0) {
return new Voter[0];
}
else
return v;
}
static int findTotal(Voter voters[],String s){
int c=0;
for(Voter voter:voters){
if(voter.isVoteCasted() && voter.getConstituency().equals(s)){
c++;
}
}
return c;
}
}
** Voter Class**
public class Voter {
private int voterId;
private String voterName;
private int voterAge;
private String constituency;
private boolean isVoteCasted;
public int getVoterId() {
return voterId;
}
public void setVoterId(int voterId) {
this.voterId = voterId;
}
public String getVoterName() {
return voterName;
}
public void setVoterName(String voterName) {
this.voterName = voterName;
}
public int getVoterAge() {
return voterAge;
}
public void setVoterAge(int voterAge) {
this.voterAge = voterAge;
}
public String getConstituency() {
return constituency;
}
public void setConstituency(String constituency) {
this.constituency = constituency;
}
public boolean isVoteCasted() {
return isVoteCasted;
}
public void setVoteCasted(boolean isVoteCasted) {
this.isVoteCasted = isVoteCasted;
}
}
So I have two methods:
public double calcAvg()
{
double dSum;
dSum=iTest1+iTest2+iTest3/3;
System.out.print(dSum);
return dSum;
}
public void setTestScores(int iTest1, int iTest2, int iTest3)
{
if(iTest1>0)
{
this.iTest1=iTest1;
}
if(iTest2>0)
{
this.iTest2=iTest2;
}
if(iTest3>0)
{
this.iTest3=iTest3;
}
I am trying to figure out why calcAvg() is setting the values of iTest1, iTest2, iTest3 as 0 after inputting the variables with values like so:
Methods.setTestScores(90,78,83);
EDIT Added global code
import java.util.Scanner;
import java.text.DecimalFormat;
public class Student
{ Scanner kbAlpha=new Scanner(System.in);
Scanner kbNum=new Scanner(System.in);
String strLast; //student's last name
String strFirst; //student's first name
int iTest1; //test 1
int iTest2; //test 2
int iTest3; //test 3
String strStreet; //student’s street address
String strCity; //student’s city
String strState; //student’s state
String strZip; //student’s zip
//+Student(first:String,last:String) //the only constructor
public String Student(String first , String last)
{
return first + last;
}
//+setName(first:String, last:String):void
public void setName(String strFirst,String strLast)
{
if(strFirst.equals(""))
{
}
else
{
this.strFirst=strFirst;
}
if(strLast.equals(""))
{
}
else
{
this.strLast=strLast;
}
}//end setName (String ,String)
//+setTestScores( t1:int, t2:int, t3:int):void
public void setTestScores(int iTest1, int iTest2, int iTest3)
{
if(iTest1>0)
{
this.iTest1=iTest1;
}
if(iTest2>0)
{
this.iTest2=iTest2;
}
if(iTest3>0)
{
this.iTest3=iTest3;
}
}//end setTestScores(int, int, int)
//+setTest(score:int,numTest:int):void
public void setTest(int score, int numTest)
{
if(numTest>=1 && numTest<=3)
{
switch(numTest)
{
case 1:
this.iTest1=score;
}
}
}//end setTest(int, int)
//+setStreet(street:String):void
public void setStreet(String strStreet)
{
if(strStreet.equals(""))
{
}
else
{
this.strStreet=strStreet;
}
}//end setStreet(String)
//+setCity(city:String):void
public void setCity(String strCity)
{
if(strCity.equals(""))
{
}
else
{
this.strCity=strCity;
}
}//end setCity(String)
//+setState(state:String):void
public void setState(String strState)
{
if(strState.equals(""))
{
}
else
{
this.strState=strState;
}
}//end setState(String)
//+setZip(zip:String):void
public void setZip(String strZip)
{
if(strZip.equals(""))
{
}
else
{
this.strZip=strZip;
}
}//end setZip(String)
//+setAddress(street:String,city:String,state:String,zip:String):void
public void setAddress(String strStreet,String strCity,String strState,String strZip)
{
if(strStreet.equals(""))
{
}
else
{
this.strStreet=strStreet;
}
if(strCity.equals(""))
{
}
else
{
this.strCity=strCity;
}
if(strState.equals(""))
{
}
else
{
this.strState=strState;
}
if(strZip.equals(""))
{
}
else
{
this.strZip=strZip;
}
}//end setAddress(String,String,String,String)
//+getName():String
public String getName()
{
String strName;
strName=this.strFirst + this.strLast;
return strName;
}//end getName()
//+getTest(numTest:int):int
public int getTest(int numTest)
{
return numTest;
}//end getTest(int)
//+getAddress():String
public String getAddress()
{
String strAddress;
strAddress=(this.strStreet + this.strCity + this.strState + this.strZip);
return strAddress;
}//end getAddress()
//+getStreet():String
public String getStreet()
{
String strStreet;
strStreet=this.strStreet;
return this.strStreet;
}//end getStreet()
//+getCity():String
public String getCity()
{
String strCity;
strCity=this.strCity;
return this.strCity;
}//end getCity()
//+getState():String
public String getState()
{
String strState;
strStreet=this.strState;
return this.strState;
}//end getState()
//+getZip():String
public String getZip()
{
String strZip;
strZip=this.strZip;
return this.strZip;
}//end getZip()
//+findMax():int
//+findMin():int
//+calcAvg():double
public double calcAvg()
{
//double dAvg;
double dSum;
dSum=(iTest1+iTest2+iTest3)/3;
System.out.print(dSum);
return dSum;
}
//+studentRecord():String
//public String studentRecord()
}
//+letterGrade():char
//+equals(s:Student):Boolean
import java.util.Scanner;
import java.text.DecimalFormat;
public class Proj3
{
public static void main(String[] args)
{
Methods.setTestScores(90,78,83);
Student MethodAvg = new Student();
MethodAvg.calcAvg();
}
}
You didn't post what Methods is, but I'm assuming it's an instance of Student. The reason why iTest1, iTest2, iTest3 are 0 is that you are setting the values in the first Student, but calling calcAvg() on the second one, where the variables have default 0 value. Try
public static void main(String[] args)
{
Student student = new Student();
student.setTestScores(90, 78, 83);
student.calcAvg();
}
The problem is in the main method, you are setting the variables in instance and calculating the average on a separate instance, try the below code it will work:
public static void main(String[] args)
{
Student std = new Student();
std.setTestScores(90,78,83);
std.calcAvg();
}
I'm having difficulty passing arrays between methods, I've managed to set them all to false from boolean, and returned the array to the main. However from there I don't know how to pass it to another method, and then later display the boolean true array as "yes" or the boolean false array as "no". My code looks as follows:
import javax.swing.*;
class methodarrays
{
public static void main (String[]param)
{
arrays();
seen();
display();
}
public static boolean[] arrays()
{
boolean [] birds = new boolean [5];
for (int i=0;i<birds.length;i++)
{
birds[i]=false;
}
return birds;
}
public static boolean seen()
{
String quit = "100";
String ans = "";
while(!ans.eqauls(quit))
{
ans=JOptionPane.showInputDialog(null,"Which bird are you reporting? \n 1) Blue Tit 2) Blackbird 3)Robin 4)Wren 5)Greenfinch");
if (ans.equals("1"))
{
birds[0] = true;
return birds[0];
}
else if (ans.equals("2"))
{ birds[1] = true;
return birds[1];
}
else if (ans.equals("3"))
{
birds[2] = true;
return birds[2];
}
else if (ans.equals("3"))
{
birds[2] = true;
return birds[2];
}
else if (ans.equals("4"))
{
birds[3] = true;
return birds[3];
}
else if (ans.equals("5"))
{
birds[4] = true;
return birds[4];
}
}
}
public static void display()
{
JOptionPane.showMessageDialog(null,"Your Garden Watch results are:");
}
}
To give you are starting hand... you can set the result of your arrays method to a local variable in the main method and pass as a argument to the seen. Then you can do the same for the display method.
public static void main (String[]param)
{
boolean[] birds = arrays();
seen(birds);
display(birds);
}
public static boolean[] arrays()
{
...
}
public static boolean seen(boolean[] birds)
{
...
There are plenty of tutorials around the web for this kind thing. Here being one example.
You need to pass it as a parameter or declare a global array.
Passing by parameter:
class methodarrays {
public static void main (String[]param)
{
boolean [] myArray =arrays();
seen(myArray);
display(myArray);
}
public static boolean seen(boolean [] myArrayParam)
{
for (int i=0;i<myArrayParam.length;i++)
{...}
}
public static boolean display(boolean [] myArrayParam)
{
for (int i=0;i<myArrayParam.length;i++)
{...}
}
}
As global array:
class methodarrays {
boolean [] myArray
public static void main (String[]param)
{
myArray = arrays();
seen();
display();
}
public static boolean seen()
{
for (int i=0;i<myArray.length;i++)
{...}
}
public static boolean display()
{
for (int i=0;i<myArray.length;i++)
{...}
}
}
Declare
boolean [] birds = new boolean [5];
as accessible object for all methods within your class.
import javax.swing.*;
class methodarrays
{
private boolean [] birds = new boolean [5]
...
public static boolean[] arrays()
{
for (int i=0;i<birds.length;i++)
{birds[i]=false;
}
return birds;
}
...
}
Here is the implementation mimicing your own:
import javax.swing.JOptionPane;
public class Example {
private static boolean [] birds = new boolean [5];
public static void main (String[]param){
arrays();
seen();
display();
}
public static boolean[] arrays()
{
// Completely unnecessary since values are set to false by default;
for (int i=0;i<birds.length;i++)
{birds[i]=false;
}
return birds;
}
public static void seen(){
String quit = "100";
String ans = "";
while(!ans.equals(quit))
{
ans=JOptionPane.showInputDialog(null,"Which bird are you reporting? \n 1) Blue Tit 2) Blackbird 3)Robin 4)Wren 5)Greenfinch");
if (ans.equals("1"))
{ birds[0] = true;
}
else if (ans.equals("2"))
{ birds[1] = true;
}
else if (ans.equals("3"))
{ birds[2] = true;
}
else if (ans.equals("3"))
{ birds[2] = true;
}
else if (ans.equals("4"))
{ birds[3] = true;
}
else if (ans.equals("5"))
{ birds[4] = true;
}
}
}
public static void display(){
System.out.println("Your results are: ");
System.out.println("Blue Tit: " + birds[0]);
System.out.println("Blackbird: " + birds[1]);
//and so on..
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
the program is to count the frequency of each word in a sentence.
This is the source code:
import java.io.*;
import java.util.Scanner;
class Dictionary
{
String key;
int val;
public Dictionary()
{
key="";
val=0;
}
void insert(String k)
{
key=k;
val=1;
System.out.println("\nInserted key with value: "+k);
}
void update()
{
val++;
}
String retkey()
{
return key;
}
int retval()
{
return val;
}
public void display()
{
System.out.println("Word = "+key);
System.out.println("Number = "+val);
}
}
class stack
{
Dictionary D[]=new Dictionary[50];
int n;
int top;
public stack(int N)
{
n=N;
top=-1;
// D=new Dictionary[n];
}
public void push(String p)
{
top++;
System.out.println("pushing "+p+"\n top=="+top);
D[top].insert(p);
System.out.println("\ntop="+top);
}
public void check(String p)
{
int i=0,flag=1;
String q="";
if(top==-1)
{
System.out.println("top=-1");
push(p);
flag=0;
}
else
{
for(i=0;i<=top;i++)
{
q=D[i].retkey();
if(q.equals(p))
{
D[i].update();
flag=0;
}
else
flag=1;
}
if(flag==1)
push(p);
}
}
public void print()
{
D[top].display();
}
}
public class Wrdcnt
{
public static void main(String[] args)throws Exception
{
// Dictionary D[]=new Dictionary() ;
String st="";
String p="";
System.out.println("Enter String: ");
Scanner in= new Scanner(System.in);
st=in.nextLine();
/* no of words*/
int n=count(st);
int j=0;
System.out.println("No of words: "+n);
stack stck =new stack(n);
for(int i=0;i<=st.length();i++)
{
if(i==st.length())
{
p = st.substring(j,i);
System.out.println(""+p);
stck.check(p);
System.out.println("Checking done for word: "+p);
j=0;
break;
}
if(st.charAt(i)==' ')
{
p = st.substring(j,i);
System.out.println(""+p);
stck.check(p);
j=i+1;
System.out.println("Checking done for word: "+p);
}
}
}
public static int count(String s)
{
int w=0;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)==' ')
{
w++;
}
}
return (w+1);
}
}
output:
Enter String:
Roses are red
No of words: 3
Roses
top=-1
pushing Roses
top==0
Exception in thread "main" java.lang.NullPointerException
at stack.push(Wrdcnt.java:51)
at stack.check(Wrdcnt.java:61)
at Wrdcnt.main(Wrdcnt.java:117)
In this line:
D[top].insert(p);
You access the variable D[top], which happens to be null.
When trying to invoke insert(p) on null, you get a NullPointerException.
This happens because you only initialize the array, but don't initialize the objects themselves to populate the array:
Dictionary D[]=new Dictionary[50];
Is allocating place for the Dictionary[] array, but NOT allocating the Dictionary objects themselves.
My code connects to an Api, takes all Json values and stores them all in a object list resultClass. How I loop through the list and display all name properties of the objects?
This is the code I am using. The JSON values are sent with the method call as parameter with name object. Then loops and takes all objects and stores them in a list.
public void onResponse(JSONObject object) {
Log.i("gw2Log", "Json Response" + object);
resultClass resultClass = new resultClass();
try {
resultClass.setCount(object.getInt("count"));
resultClass.setPage(object.getInt("page"));
resultClass.setLast_page(object.getInt("last_page"));
resultClass.setTotal(object.getInt("total"));
JSONArray list = new JSONArray(object.getString("results"));
for (int i = 0; i < resultClass.getTotal(); i++) {
JSONObject resultsObject = list.getJSONObject(i);
resultClass.setData_id(resultsObject
.getInt("data_id"));
resultClass.setName(resultsObject
.getString("name"));
resultClass.setRarity(resultsObject
.getInt("rarity"));
resultClass.setRestriction_level(resultsObject
.getInt("restriction_level"));
resultClass.setImg(resultsObject
.getString("img"));
resultClass.setType_id(resultsObject
.getInt("type_id"));
resultClass.setSub_type_id(resultsObject
.getInt("sub_type_id"));
resultClass.setPrice_last_changed(resultsObject
.getString("price_last_changed"));
resultClass.setMax_offer_unit_price(resultsObject
.getInt("max_offer_unit_price"));
resultClass.setMin_sale_unit_price(resultsObject
.getInt("min_sale_unit_price"));
resultClass.setOffer_availability(resultsObject
.getInt("offer_availability"));
resultClass.setSale_availability(resultsObject
.getInt("sale_availability"));
resultClass.setSale_price_change_last_hour(resultsObject
.getInt("sale_price_change_last_hour"));
resultClass.setOffer_price_change_last_hour(resultsObject
.getInt("offer_price_change_last_hour"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0; i < resultClass.total; i++) {
Log.i("gw2Log", resultClass.name[i]);
}
}
This is the Json response i am logging
Json Response{"total":6,"last_page":1,"results":[{"sale_availability":0,"offer_availability":0,"img":"https:\/\/render.guildwars2.com\/file\/01D07FABAE26C0E5240892B00DA7AF90AB0EA022\/455828.png","rarity":7,"type_id":16,"sale_price_change_last_hour":0,"max_offer_unit_price":0,"data_id":19648,"price_last_changed":"2015-04-20 20:23:48 UTC","offer_price_change_last_hour":0,"name":"Gift of Twilight","min_sale_unit_price":0,"restriction_level":0,"sub_type_id":0},{"sale_availability":0,"offer_availability":0,"img":"https:\/\/render.guildwars2.com\/file\/CE3AF0B7B9BB6244726779F5B6A930541BA6C15F\/456031.png","rarity":5,"type_id":18,"sale_price_change_last_hour":0,"max_offer_unit_price":0,"data_id":49191,"price_last_changed":"2015-04-20 20:23:48 UTC","offer_price_change_last_hour":0,"name":"Twilight","min_sale_unit_price":0,"restriction_level":80,"sub_type_id":6},{"sale_availability":23,"offer_availability":20643,"img":"https:\/\/render.guildwars2.com\/file\/CE3AF0B7B9BB6244726779F5B6A930541BA6C15F\/456031.png","rarity":7,"type_id":18,"sale_price_change_last_hour":0,"max_offer_unit_price":27500000,"data_id":30704,"price_last_changed":"2015-04-20 20:17:57 UTC","offer_price_change_last_hour":0,"name":"Twilight","min_sale_unit_price":31959998,"restriction_level":80,"sub_type_id":6},{"sale_availability":0,"offer_availability":0,"img":"https:\/\/render.guildwars2.com\/file\/D04EF6FDE3DBC26E7BB109EB4F52057FEAD8619E\/699325.png","rarity":1,"type_id":4,"sale_price_change_last_hour":0,"max_offer_unit_price":0,"data_id":65578,"price_last_changed":"2015-04-20 20:23:48 UTC","offer_price_change_last_hour":0,"name":"Twilight Arbor Armor Box","min_sale_unit_price":0,"restriction_level":0,"sub_type_id":0},{"sale_availability":0,"offer_availability":0,"img":"https:\/\/render.guildwars2.com\/file\/666209104CCB024D53359C0EA0A299076E610771\/65704.png","rarity":1,"type_id":4,"sale_price_change_last_hour":0,"max_offer_unit_price":0,"data_id":65577,"price_last_changed":"2015-04-20 20:23:48 UTC","offer_price_change_last_hour":0,"name":"Twilight Arbor Token Loot Box","min_sale_unit_price":0,"restriction_level":0,"sub_type_id":0},{"sale_availability":0,"offer_availability":0,"img":"https:\/\/render.guildwars2.com\/file\/2626184EDDC254B4F7634A04F878062C6B2AF20D\/780372.png","rarity":1,"type_id":4,"sale_price_change_last_hour":0,"max_offer_unit_price":0,"data_id":65579,"price_last_changed":"2015-04-20 20:23:48 UTC","offer_price_change_last_hour":0,"name":"Twilight Arbor Weapons Box","min_sale_unit_price":0,"restriction_level":0,"sub_type_id":0}],"count":6,"page":1}
When digging around for a solution and checking the actual error it says it expects and array but a string is given Log.i("gw2Log", resultClass.name[i]);
When I loop through this Log call Log.i("gw2Log", resultClass.name); it displays the last objects name property the amount it loops.
EDIT:
On request to include my resultClass.java:
public class resultClass {
public int data_id;
public String name;
public int rarity;
public int restriction_level;
public String img;
public int type_id;
public int sub_type_id;
public String price_last_changed;
public int max_offer_unit_price;
public int min_sale_unit_price;
public int offer_availability;
public int sale_availability;
public int sale_price_change_last_hour;
public int offer_price_change_last_hour;
public int count;
public int page;
public int last_page;
public int total;
public int getData_id() {
return data_id;
}
public void setData_id(int data_id) {
this.data_id = data_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRarity() {
return rarity;
}
public void setRarity(int rarity) {
this.rarity = rarity;
}
public int getRestriction_level() {
return restriction_level;
}
public void setRestriction_level(int restriction_level) {
this.restriction_level = restriction_level;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public int getType_id() {
return type_id;
}
public void setType_id(int type_id) {
this.type_id = type_id;
}
public int getSub_type_id() {
return sub_type_id;
}
public void setSub_type_id(int sub_type_id) {
this.sub_type_id = sub_type_id;
}
public String getPrice_last_changed() {
return price_last_changed;
}
public void setPrice_last_changed(String price_last_changed) {
this.price_last_changed = price_last_changed;
}
public int getMax_offer_unit_price() {
return max_offer_unit_price;
}
public void setMax_offer_unit_price(int max_offer_unit_price) {
this.max_offer_unit_price = max_offer_unit_price;
}
public int getMin_sale_unit_price() {
return min_sale_unit_price;
}
public void setMin_sale_unit_price(int min_sale_unit_price) {
this.min_sale_unit_price = min_sale_unit_price;
}
public int getOffer_availability() {
return offer_availability;
}
public void setOffer_availability(int offer_availability) {
this.offer_availability = offer_availability;
}
public int getSale_availability() {
return sale_availability;
}
public void setSale_availability(int sale_availability) {
this.sale_availability = sale_availability;
}
public int getSale_price_change_last_hour() {
return sale_price_change_last_hour;
}
public void setSale_price_change_last_hour(int sale_price_change_last_hour) {
this.sale_price_change_last_hour = sale_price_change_last_hour;
}
public int getOffer_price_change_last_hour() {
return offer_price_change_last_hour;
}
public void setOffer_price_change_last_hour(int offer_price_change_last_hour) {
this.offer_price_change_last_hour = offer_price_change_last_hour;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getLast_page() {
return last_page;
}
public void setLast_page(int last_page) {
this.last_page = last_page;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}
try something like this
first make a new object something like MyObject
public class MyObject {
public int data_id;
public String name;
public int rarity;
public int restriction_level;
public String img;
public int type_id;
public int sub_type_id;
public String price_last_changed;
public int max_offer_unit_price;
public int min_sale_unit_price;
public int offer_availability;
public int sale_availability;
public int sale_price_change_last_hour;
public int offer_price_change_last_hour;
public int getData_id() {
return data_id;
}
public void setData_id(int data_id) {
this.data_id = data_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRarity() {
return rarity;
}
public void setRarity(int rarity) {
this.rarity = rarity;
}
public int getRestriction_level() {
return restriction_level;
}
public void setRestriction_level(int restriction_level) {
this.restriction_level = restriction_level;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public int getType_id() {
return type_id;
}
public void setType_id(int type_id) {
this.type_id = type_id;
}
public int getSub_type_id() {
return sub_type_id;
}
public void setSub_type_id(int sub_type_id) {
this.sub_type_id = sub_type_id;
}
public String getPrice_last_changed() {
return price_last_changed;
}
public void setPrice_last_changed(String price_last_changed) {
this.price_last_changed = price_last_changed;
}
public int getMax_offer_unit_price() {
return max_offer_unit_price;
}
public void setMax_offer_unit_price(int max_offer_unit_price) {
this.max_offer_unit_price = max_offer_unit_price;
}
public int getMin_sale_unit_price() {
return min_sale_unit_price;
}
public void setMin_sale_unit_price(int min_sale_unit_price) {
this.min_sale_unit_price = min_sale_unit_price;
}
public int getOffer_availability() {
return offer_availability;
}
public void setOffer_availability(int offer_availability) {
this.offer_availability = offer_availability;
}
public int getSale_availability() {
return sale_availability;
}
public void setSale_availability(int sale_availability) {
this.sale_availability = sale_availability;
}
public int getSale_price_change_last_hour() {
return sale_price_change_last_hour;
}
public void setSale_price_change_last_hour(int sale_price_change_last_hour) {
this.sale_price_change_last_hour = sale_price_change_last_hour;
}
public int getOffer_price_change_last_hour() {
return offer_price_change_last_hour;
}
public void setOffer_price_change_last_hour(int offer_price_change_last_hour) {
this.offer_price_change_last_hour = offer_price_change_last_hour;
}
}
then make your resultClass look like this
public class resultClass {
public int count;
public int page;
public int last_page;
public int total;
public ArrayList<MyObject> myObjects = new ArrayList();
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getLast_page() {
return last_page;
}
public void setLast_page(int last_page) {
this.last_page = last_page;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public MyObject getObject(int pos){
return myObjects.get(pos);
}
public void addObject(MyObject object)
{
myObjects.add(object);
}
}
then your response should be something like this
public void onResponse(JSONObject object) {
Log.i("gw2Log", "Json Response" + object);
resultClass resultClass = new resultClass();
try {
resultClass.setCount(object.getInt("count"));
resultClass.setPage(object.getInt("page"));
resultClass.setLast_page(object.getInt("last_page"));
resultClass.setTotal(object.getInt("total"));
JSONArray list = new JSONArray(object.getString("results"));
for (int i = 0; i < resultClass.getTotal(); i++) {
JSONObject resultsObject = list.getJSONObject(i);
MyObject temp = new MyObject();
temp.setData_id(resultsObject
.getInt("data_id"));
temp.setName(resultsObject
.getString("name"));
temp.setRarity(resultsObject
.getInt("rarity"));
temp.setRestriction_level(resultsObject
.getInt("restriction_level"));
temp.setImg(resultsObject
.getString("img"));
temp.setType_id(resultsObject
.getInt("type_id"));
temp.setSub_type_id(resultsObject
.getInt("sub_type_id"));
temp.setPrice_last_changed(resultsObject
.getString("price_last_changed"));
temp.setMax_offer_unit_price(resultsObject
.getInt("max_offer_unit_price"));
temp.setMin_sale_unit_price(resultsObject
.getInt("min_sale_unit_price"));
temp.setOffer_availability(resultsObject
.getInt("offer_availability"));
temp.setSale_availability(resultsObject
.getInt("sale_availability"));
temp.setSale_price_change_last_hour(resultsObject
.getInt("sale_price_change_last_hour"));
temp.setOffer_price_change_last_hour(resultsObject
.getInt("offer_price_change_last_hour"));
resultClass.addObject(temp);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0; i < resultClass.total; i++) {
Log.i("gw2Log", resultClass.getObject(i).name);
}
}
You could try this code. You wanted to use table of objects, but you created just single object. Create arrayList of your resultClass and then use simplier 'for' for your list
public void onResponse(JSONObject object) {
Log.i("gw2Log", "Json Response" + object);
List<resultClass> resultClassList = new ArrayList<resultClass>();
resultClass resultClass = new resultClass();
try {
resultClass.setCount(object.getInt("count"));
resultClass.setPage(object.getInt("page"));
resultClass.setLast_page(object.getInt("last_page"));
resultClass.setTotal(object.getInt("total"));
JSONArray list = new JSONArray(object.getString("results"));
for (int i = 0; i < resultClass.getTotal(); i++) {
JSONObject resultsObject = list.getJSONObject(i);
resultClass.setData_id(resultsObject
.getInt("data_id"));
resultClass.setName(resultsObject
.getString("name"));
resultClass.setRarity(resultsObject
.getInt("rarity"));
resultClass.setRestriction_level(resultsObject
.getInt("restriction_level"));
resultClass.setImg(resultsObject
.getString("img"));
resultClass.setType_id(resultsObject
.getInt("type_id"));
resultClass.setSub_type_id(resultsObject
.getInt("sub_type_id"));
resultClass.setPrice_last_changed(resultsObject
.getString("price_last_changed"));
resultClass.setMax_offer_unit_price(resultsObject
.getInt("max_offer_unit_price"));
resultClass.setMin_sale_unit_price(resultsObject
.getInt("min_sale_unit_price"));
resultClass.setOffer_availability(resultsObject
.getInt("offer_availability"));
resultClass.setSale_availability(resultsObject
.getInt("sale_availability"));
resultClass.setSale_price_change_last_hour(resultsObject
.getInt("sale_price_change_last_hour"));
resultClass.setOffer_price_change_last_hour(resultsObject
.getInt("offer_price_change_last_hour"));
resultClassList.add(resultClass);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(resultClass result : resultClassList) {
Log.i("gw2Log", result.name);
}
}
Ok, I'm pretty sure of several things:
Tomer Shemesh is right, you are overriding your resultClass object on every iteration.
You wanna make arrays out of your normal variables in the resultClass so you can actually store more than one Item.
About that error you're getting:
It occurs in the lower for loop, where you want to log the names, right?
resultClass.nameis a String variable, it holds exactly one string of characters. You are trying to get a string out of an array by saying something like resultClass.name[i]. For that to work youu need to decrlare it as a string array, holding several string like public String[] name;, and in the constructor initialize it with a given capactiy like name = new String[cap];. Or you use an ArrayList<String> instead, which grows dynmically, but uses own getters and setters instead of the easy name[index] functions of an array.
Sorry, but I don't really want to write the right code here, as pretty much the whole thing needs to be rewritten, I hope this will help you rewrite it yourself though.