Problem filling an array with my JSON file information - java

I have a JComboBox that I want to be filled with an array of my json file information:
This is my json:
{"Agencias":[{"nombre":"OpenWorld C.A","agenciaDir":"Los teques","telefono":"45789658","nombreContacto":"daniel","telefonoContacto":"34567321"}]}
I'll show you 2 versions of the same array-fill-function: the first version doesn't work, and is what im trying to do; the second version do not fill the array (what I need) but it works in my combobox. This is the first version:
public String[] llenarComboboxAgencias() {
String[] array1 = null; //i create a new null array
JSONArray listaAgencias = agencias.getJSONArray("Agencias"); //get into my JSon "Agencias" array
for(int j=0;j<listaAgencias.length();j++) { //start reading "Agencias array"
JSONObject agencia = listaAgencias.getJSONObject(j); //JSONObject for each object in my "Agencias" array.
this.string1=agencia.getString("nombre"); //I save my JSONObect "nombre"(name) in a string
array1[j]=agencia.getString("nombre"); //I give to my "array1"[position] the information of the object name
}
return array1; //Return my string array1
}
Now, what happens in this already shown code, is a nullpointerException in the line: array[j]=agencia.getString("nombre");. The question is not the same thing of this post Link, because I did an other code without filling my array, with the same coding logic (I think) and do not have problems.
So, this is my second version with an already filled array. And it works perfectly!:
public String[] llenarComboboxAgencias(){
JSONArray listaAgencias = agencias.getJSONArray("Agencias"); //get into my JSon "Agencias" array
for(int j=0;j<listaAgencisa.length();j++) { //start reading "Agencias array"
JSONObject agencia = listaAgencias.getJSONObject(j); //JSONObject for each object in my "Agencias" array.
this.string1=agencia.getString("nombre"); //I save my JSONObect "nombre"(name) in a string
//this is where my code changes: now im printing all my "names" on the console
System.out.println(string1);
}
//and this is the most important change: im not filling my array, this is an already filled one!
String[] array1= {"Hello","Friend"};
return array1; //return my already filled array
}
This code, in console it shows all my JSON "agencias" names, and my JFrame JCombobox, gets the filled array as options without getting any problem/error.
So the problem is in the first code where I tried to fill my array1[], but I don't get why? a string[] isn't an object, and im starting the "fill" in the first array1[] box :0, and otherwise the array isn't empty, it have already a string on it my Agencia's "nombre" (OpenWorld C.A)
My question is simple: why my first code doesn't work, and why my second on does? how can I get a code to fill properly my array, and return it like the second version does?

Your array is null: String[] array1 = null;. Then you try to assign to the array: array1[j]=agencia.getString("nombre");. That's why you get a NPE.
You need to instantiate your array.
String[] array1 = new String[listaAgencisa.length()];
Alternately, use an ArrayList instead.

Related

How to add items to array of objects using loops

I've got a multiple student objects I want to write into with a CSV file containing their details. I've set each row of the CSV file to an array then was going to split each entry of the array into another array and use that to set the attributes of the object. However, each time I try, I get a NullPointerException.
String studentCSV = "src\\CSV Files\\Students.csv";
Student[] student = new Student[CSV_Reader.count(studentCSV)];
String[] values = CSV_Reader.read(studentCSV);
for(int i=0;i<values.length;i++){
String[] line = values[i].split(",");
student[i].addPerson(line[0],line[1],line[2],line[3]);
student[i].addStudent(line[4],line[5],line[6]);
}
int n=10; // for example
Student[] student = new Student[n];
//now you just allocate memory for array
for(int i=0;i<student.length;i++){
student[i]=new Student();
// here you assign student to your any element of array
}
// now you can do anything with elements of your student array
Most likely, there is a line with information (or separator) missing and trying to access that index causes the exception. You should check that first (simply print out the lines in the loop at first and whatever causes the error will be the last to print).
Otherwise: please show the full error log and point out on which line the error occurs.

Creating array in one line

I have a code
String ejgStr[] = new String[][]{{null},new String[]{"a","b","c"},{new String()}}[0] ;
System.out.println(ejgStr[0]);
which compiles without error.
From what I understand you can't create an array with non-matching square brackets.
On the left, we have String ejgStr[], which is 1-d array and
On the right, we have String[][]{some array}[0], which is 2-d array
These seem to have different dimensions but why do they successfully compile?
You are assigning a one-dimensional String[] array to the first dimension of an inline two-dimensional String[][] array. Have a look the comments:
String ejgStr[] =
new String[][] {
{ null }, // a null 1D String array
new String[] {"a","b","c"}, // a 1D String array containing a,b,c
{ new String() } // a String array containing empty String
}[0]; // access the { null } 1D array
I expect your assignment to be equivalent to doing this:
String ejgStr[] = { null };
You assign a 1D array to the ejgStr refference. If you look at the end of the first statemend, you will see that you have a [0] index specified which means you will assign the first array (position 0) to your referrence. If you remove the [0] you will receive a compilation error.
new String[][]{...} is a 2D array.
new String[][]{...}[0] is the first element of a 2D array, which is a 1D array.
That's what you're assigning to String ejgStr[].
String ejgStr[] is just a reference to a variable in heap space.
you're pointing to first dimensional of 2D-dimensional array using [0] and make a reference of it in ejgStr[]. this is not common to get 1D from 2D array, but you can do it if you need and of course it wont make compile error.

Array inside of an Array - Java

Ok, so I have a 2D array that returns an array.
Object[][] sample = new Object[1][1];
//ok just imagine sample already has an array inside of it
How do I retrive the array within the 2d array?
I have tried to create a new array with the value,
object[] = sample[0][0];
but it just creates an error.
When I print the value of
sample[0][0]
it returns the value:
[[Ljava.lang.Object;#4e25154f
I do not know how to solve this.
sample[0][0] is Object not int[], sample[0] can be one dimensional array or any Object, note that arrays are also Object in java.
To print multidimensional array you can use Arrays.deepToString(twoDarray) but this does not work if you have stored specifically Object.
Moreover, [[Ljava.lang.Object;#4e25154f is the result of default toString representation of the Object stored at sample[0][0] which is I think an array. To print array you can use Arrays.toString(int[]).
I guess this is what you are trying to do,
Object[][] obj = new Object[1][1];
obj[0][0] = new int[]{0,1,0,2};
System.out.println(obj);
//To get int[]
int[] arr= (int[]) obj[0][0];//Need to cast to the int[] specifically
//because it's currently stored as an Object
System.out.println(Arrays.toString(arr));
OUTPUT
[[Ljava.lang.Object;#1db9742
[0, 1, 0, 2]
sample[0][0] returns the object not int. First you need to downcast it and then retrieve integer value
For example :-
CustomObject co = (CustomObject)sample[0][0]; // downcast here
then retrieve the required field from your custom object

ArrayStoreException while converting List<String> to Text Array MapReduce

In a mapreduce code, while converting list to array of (org.apache.hadoop.io.Text) Text type, receiving ArrayStoreException.
List<String> testList= new ArrayList<String>();
testList.add("testData1");
testList.add("testData2");
Text[] testArray=testList.toArray(new Text[testList.size()]);
but when i dont add any value to the list and then convert it to array, it works fine(with null values). Can some one please point my mistake.
You can't store Strings in a Text array (Text[]).
You can store them in a String array (String[]) :
String[] testArray=testList.toArray(new String[testList.size()]);
when i dont add any value to the list and then convert it to array, it works fine
It only works since you are creating an empty array in this case, so nothing is stored in it.
If you must produce a Text[] that contains the data from the source List<String>, you have to iterate over the List and produce the Text instances yourself:
Text[] testArray = new Text[testList.size()];
for (int i = 0; i < testList.size(); i++) {
testArray[i] = new Text(testList.get(i)); // assuming the Text class
// has such a constructor
}

Passing array into constructor to use on JList

I know the title sound confusing and thats because it is. its a bit long so try too stay with me.
this is the layout i have my code designed
variables
constructor
methods.
im trying too fill a Jlist full on names. i want too get those names using a method. so here goes.
in my variables i have my JList. its called contactNames;
i also have an array which stores 5 strings which are the contacts names;
heres the code for that anyway
String contact1;
String contact2;
String contact3;
String contact4;
String contact5;
String[] contactListNames;
JList contactList;
simple enough. then in my constructor i have the Jlist defined to fill itself with the contents of the array
String[] contactListNames = new String[5];
JList contactList = new JList(contactListNames);
fillContactList();
that method fillContactList() is coming up shortly.
now heres where stuff gets balls up.
ive created three different methods all of which havent worked. basically im trying to fill the array with all of them.
this is the simplest one. it doesnt set the Jlist, it doesnt do anything compilicated. all it trys too do is fill the array one bit at a time
public void fillContactList()
{
for(int i = 0;i<3;i++)
{
try
{
String contact;
System.out.println(" please fill the list at index "+ i);
Scanner in = new Scanner(System.in);
contact = in.next();
contactListNames[i] = contact;
in.nextLine();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
unfortunately this doesnt qwork. i get the print out to fill it at index 0; i input something and i get a nice big stack trace starting at
contactListNames[i] = contact;
so my question in short is
why cant i fill the array from that method.
***********************************************888 ***********************************************888
stack trace by request
please fill the list at index 0
overtone
please fill the list at index 1
java.lang.NullPointerException
at project.AdminMessages.fillContactList(AdminMessages.java:410)
at project.AdminMessages.<init>(AdminMessages.java:91)
at project.AdminUser.createAdminMessages(AdminUser.java:32)
at project.AdminUser.<init>(AdminUser.java:18)
at project.AdminUser.main(AdminUser.java:47)
To define an array in a constructor you can do something along these lines,
// if values are predefined, you can explicitly fill the array
String[] contacts = {"Bill Gates", "Steve Jobs", "Jon Skeet"};
// or this way, both will work.
String[] contacts = new String[2];
Looking at JList from the Java Doc's you can most certainly pass in an array to JList
String[] data = {"one", "two", "three", "four"};
JList dataList = new JList(data);
You are getting NullPointerException because the array, contactListNames is not initialized, you would need to initialize it.
You define an array in a constructor just like you would any other variable. So, it would look something like:
// define an array of size 3
String[] contactListNames = new String[3];
The reason you are getting exceptions is because you don't actually initialize the array. You declare it but you never set it to a value (or give it a size). You should post the stack trace of the error but I suspect it's a NullPointerException.
Then in my constructor i have the
Jlist defined to fill itself with the
contents of the array
String[] contactListNames = new String[5];
JList contactList = new JList(contactListNames);
fillContactList();
What you're doing here is creating new local variables that are shadowing the ones defined in your class.
Change it to:
contactListNames = new String[5];
contactList = new JList(contactListNames);
fillContactList();

Categories