Passing array into constructor to use on JList - java

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();

Related

Problem filling an array with my JSON file information

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.

For Loop doesnt add point to an array

I have the following for loop which looks through a string ArrayList of results, each item in the string is seperated by "::":
ArrayList<String> resultsArray = MyClass.results;
Integer numPoints = resultsArray.size();
for (int i =0;i<numPoints;i++){
String[] pointDetails = resultsArray.get(i).split("::");
String pointName = pointDetails[0];
String pointDescription = pointDetails[1];
String coordinates = pointDetails[2];
//Turn coordinates into geopoints
String coord[] = coords.split(",");
Integer lng= (int) (Double.valueOf(coord[0]) * 1000000);
Integer lat = (int)(Double.valueOf(coord[1])*1000000);
GeoPoint gPoint = new GeoPoint(lng,lat);
arrayPointName = new ArrayList <String>();
arrayPointDescription = new ArrayList <String>();
arrayPointCoords=new ArrayList<GeoPoint>();
arrayPointName.add(pointName);
arrayPointDescription.add(pointDescription);
arrayPointCoords.add(gPoint);
}
I know I have 20 points in the initial string ArrayList and have printed out its size to check this. However, when I print out the new arraylists, such as arrayPointName, they only contain one point. Any idea on why this is?
Look at this code:
arrayPointName = new ArrayList <String>();
arrayPointDescription = new ArrayList <String>();
arrayPointCoords=new ArrayList<GeoPoint>();
Those three statements - assigning new, empty ArrayList references to your variables - are being executed on every iteration of your loop.
They should come before your loop instead: you only want to initialize the variables once (creating the three lists) and then add a new item on each iteration.
As a side note, populating multiple collections like this is normally a bad idea. It's usually better to create a single type which encapsulates the related data (name, description, coordinates in this case) and then create a single collection of items of that type. That's usually a lot easier to work with.
you used coords as an ArrayList Without initiate it .Also you initiate for each iteration arrayPointName, arrayPointDescription and arrayPointCoords that's why they lost the value created in the previous iteration. they should be initiate juste one time before starting the loop
it will be easy to help you if you give us a sample of resultsArray strring.

Arraylist of arraylist in method

having a problem trying to get an arraylist containing arraylists to work in my program, Im getting a strange warning saying: add #SuppressWarnings "null" to processArray(), regardless of If I add this or not my program crashes, Is there anything obvious that Im doing wrong here? any help would go a long way thanks.
private ArrayList<ArrayList<String>> processArray(ResponseList<Status> responses){
ArrayList<ArrayList<String>> mainArray = null;
ArrayList<String> innerArrays = null;
for (Status response: responses ){
String name, status, imgUrl, time;
name = response.getUser().getName();
status = response.getText();
imgUrl = response.getUser().getProfileImageURL().toString();
time = response.getCreatedAt().toString();
ArrayList<String> rtLinks = checkLinks(response.getText());
if(rtLinks != null){
for (String tLink: rtLinks){
innerArrays.add(name);
innerArrays.add(status);
innerArrays.add(imgUrl);
innerArrays.add(time);
innerArrays.add(tLink);
mainArray.add(innerArrays);
}
}
}
return mainArray;
You never actually initialize either of those arraylists.
You want
ArrayList<ArrayList<String>> mainArray = new ArrayList<ArrayList<String>>(); // or new ArrayList<>() in java 7
and inside the inner for loop:
ArrayList<String> innerArrays = new ArrayList<String>(); // or new ArrayList<>() in java 7
Also, don't ever suppress warnings "just to make code work". Only suppress them when you know exactly why they appear and exactly why you're choosing to ignore them.
Your program is probably crashing due to a NullPointerException. This occurs when you try to access a variable whose value is null (known as dereferencing a null pointer). Before you access either of the two ArrayLists, you'll need to initialize it. Try changing the two lines to this:
ArrayList<ArrayList<String>> mainArray = new ArrayList<ArrayList<String>>();
ArrayList<String> innerArrays = new ArrayList<String>();
This should solve your immediate problem.
However, I'm not sure why you're using an innerArrays list at all. I would refactor the last bit to this:
for (String tLink: rtLinks){
ArrayList<String> tempList = new ArrayList<String>();
tempList.add(name);
tempList.add(status);
tempList.add(imgUrl);
tempList.add(time);
tempList.add(tLink);
mainArray.add(tempList);
}
and remove the innerArrays variable. This way, the scope is more limited, and the code operates more logically.
You are trying to add the innerArrays variable into your main ArrayList, but you have declared your main ArrayList null in the beginning of the method. Initialize the main ArrayList as a new ArrayList of ArrayLists of Strings, and your code should work.

error in this line :"private String[][] variable=new String[][] {var1,var2,var n}"

my question is im getting d jtable but i want to display the data from the database into the the jtable.
if i pass data directly its being displayed in the jtable but i wont data from the database..
please help
the problem is in this line:
private String[][] row1=new String[][]{jono,jdate,prname};
jono,jdate and prname are the variables that contain the data from database.
i need to display it in jtable.
Of course, you declare a two dimensional array but the initialization is just one dimension.
Try this:
private String[][] row1=new String[][]{{jono,jdate,prname}};
You're creating a matrix (2-dimensional array) but are only instantiating single-dimensional objects.
The declaration should look something like this:
String[][] row1 = new String[][] {
new String[] { jono },
new String[] { jdate },
new String[] { prname }
};
Without knowing much else about what you are doing, I can't be certain if this would be what you would need, but it's a start.
Most likely jono, jdate, and prname are not instances of String[]. Post the error and the declaration of those variables for more help.

Multidimensional array to ListView.. how?

I have a query result set which I like to edit first and then put it to my ListView. Without editing my data first, I could use SimpleCursorAdapter like that:
ListAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.list_item,
mCursor,
new String[] { "address", "city" },
new int[] { R.id.address, R.id.zip_city });
this.setListAdapter(adapter);
But now, I put everything in a multidimensional array like that:
if(mCursor.isFirst()) {
//create a new array
String[][] listData = new String[mCursor.getCount()][3];
int i = 0;
do {
listData[i] = new String[] {
mCursor.getString(mCursor.getColumnIndex("address")),
mCursor.getString(mCursor.getColumnIndex("zip")) + " " + mCursor.getString(mCursor.getColumnIndex("city")),
calculateDistance(Double.parseDouble(mCursor.getString(mCursor.getColumnIndex("diff"))))
};
i++;
} while(mCursor.moveToNext());
}
So my problem is now, I have no idea how to put this to my ListView. Could someone help me here? Sorry for my bad english and Java knowledge. :)
Either write your own adapter class, extending BaseAdapter, that works with your array, or switch to a different data structure, such as a MatrixCursor.
HOW TO USE A LISTVIEW WITH A MULTI-DIMENSION ARRAY
Guys, the simplest way is as follows -
In the calling activity, let us call it FirstActivity, you declare the multiple dimension array as public static
public static MyArray[][];
In the second activity you refer to this array using -
FirstActivity.MyArray
Now create a single dimension array that reads just one column from the multi dimension array using a loop eg
for(int i = 0; i < FirstActivity.MyArray.length; i++){
SingleArray[i] = FirstActivity.MyArray[i][0];}
Then use an adapter to bind the list to the SingleArray
setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, SingleArray));
Just remember to clear the arrays each time, so they do not retain values from before.
Regards
Craig Paardekooper

Categories