How to solve Null Pointer Exception while using array? - java

Here its showing null pointer exception in the line arr[i] = "true";
String[] count = null;
String[] arr = null;
int i = 0;
rs2 = st2.executeQuery("SELECT COUNT(*) as y FROM " + usrtbl + " WHERE user_id NOT IN (SELECT user_id FROM " + usrroletbl + ")");
rs2.next();
if (rs2.getInt("y") == 0) {
arr[i] = "false";
count = arr;
i++;
} else {
arr[i] = "true";
count = arr;
i++;
}
Any help will be appreciated.

You need to initialize the String[] array
Approach 1
String[] errorSoon = new String[100]; // <--initialized statement, this is fixed size array, so you need to set the size accordingly, keeping memory usage in mind.
Approach2
use List
List<String> errorSoon = new ArrayList<String>();
Also as mentioned by #dave, if it is really required to have array here, or just a boolean variable can work for you.

You have defined arr to be null and you have not allocated it any memory. So of course, accessing arr[i] will result in a NullPointerException.
You could first run an SQL query to get the number of results and allocate the space, eg.
arr = new String[<count>];
Or you could use an ArrayList to hold the values. This is simpler as it will grow dynamically to hold your data.
As an aside, you should consider converting arr (or your ArrayList) to hold boolean. Then you can use true and false directly (rather than their string equivalents).

As #Dave said you have declared both the String arrays as null, so of course you will get NullPointerException. You have to know the size of your resultset first and then declare the array according to the size.
But instead of that I would recommend you to use ArrayList. Its simple and can dynamically add your result. You can do something like this-
List<String> list=new ArrayList<String>();
while(rs.next()){
if(// your condition){
list.add("something");
}
else{
list.add("something");
}
}
So it will keep on adding "something" in the list till the last row is covered.
Then you can easily iterate through the list as per your requirement.
Or you can also convert the ArrayList into an Array using the following command-
Object obj[]=list.toArray(); //Note that it will create an Array of Object datatype. You have to typecast it to your required datatype later if you want to print or manipulate the data.

Related

Dynamically adding Strings to an object[]

I'm working on a project for work involving a JTable with a dynamic number of columns. Each column is basically a separate transaction but I do not know the number of transactions a file will have ahead of time.
Typically when I create a JTable I know how many columns I will have and I declare it like this:
String header[] = new String[]{
"Tag","Transaction1"
};
For this project however there can be any number of transactions each time the program is used so I would need to dynamically add columns based upon the length of a certain array before I even create my rows. (The first row is actually going to also be used as a header).
So I have an array with a given length, but I don't know how to use this value in a loop, at least not with creating an object like the code above shows.
For example let's say the user uploads a file that has 3 transactions.. I would need my String header[] to read:
String header[] = new String[]{
"Tag","Transaction1","Transaction2","Transaction3"
};
I'd considered possibly creating an array list and adding the transactions to this using a counter and a loop, then possibly extracting the values into the String[] header although I'm not sure if this is the best approach and even still how exactly to make it work.
I actually found the answer to this.. Apparently I need to scrap the entire array and add them like this..
DefaultTableModel tableModel = new DefaultTableModel();
for(String columnName : columnNames){
tableModel.addColumn(columnName);
}
jTable.setModel(tableModel);
A good option for you would be to have an ArrayList to dynamically add or remove elements from the List.
Then, when necessary, you can turn that ArrayList into an array of Strings, like..
ArrayList<String> elements = new ArrayList<String>();
elements.add("Transaction 1");
elements.add("Transaction 2");
elements.add("Transaction 3");
Object[] elementArray = elements.toArray();
I thing you dont need to use an Array, use better an List, this because you can increase the size as much as you need, iterate it, parse it to string-Arrays etc.
Example
List<String> transactions = new ArrayList<String>();
transactions.add("Tag");
// later
transactions.add("Transaction1");
transactions.add("Transaction2");
// print it
for (final String string : transactions) {
System.out.println(string);
}
List<String> headerList = new ArrayList<>();
headerList.add("Tag");
for(int i=1; i <= transactions.length; i++){
headerList.add("Transaction" + i);
}
String[] header = headerList.toArray(new String[headerList.size()]);
I believe what you're looking for is an ArrayList, not an Array nor List, as this allows for dynamic allocation.
The syntax would be:
List<String> header = new ArrayList<String>();
header.add("Tag");
That initializes it. Then, use length() from your File class to set a parameter for a loop, then dynamically add the result of string concatenation with the "Transaction" + your loop index to your ArrayList.
That'd look like:
for (int i = 1; i <= file.length(); i++){
header.Add("Transaction" + i);
}
And, then you can convert it back to an array of strings with:
String[] headerArray = header.toArray(new String[header.size()]);

for-each loop in java can't be used for assignments

Why for-each loop in java can't be used for assignments?
For eg I am trying the below example and not getting the expected result but compiles successfully:
int count = 0;
String[] obj = new String[3];
for (String ob : obj )
ob = new String("obj" + count++);
System.out.println(obj[0]); // null
ob is a local variable which is a copy of the reference in the array. You can alter it but it doesn't alter the array or collection it comes from.
Essentially, that is correct. The for-each loop is not usable for loops where you need to replace elements in a list or array as you traverse it
String[] obj = { "obj1", "obj2", "obj3" };
or
for (int count = 0; count < obj.length; count++) {
obj[count] = "obj" + count;
}
As you've noted, you can't use the variable in an array iteration to set the values of the array. In fact your code, while legal, is unusual in iterating through the elements of an array in order to initialise them. As other answers have noted, you are better off using the index of the array.
Even better is to create the array in the process of initialisation. For example, in Java 8 you could use:
String[] obj = IntStream.range(0, 4).mapToObj(n -> "obj" + n).toArray();
This seems to me to capture your intent of creating strings and then turning them into a new array rather than create an array and then iterate through it changing each element.

Can't i initialized empty String array and pass in the value afterwards in Java?

I can't seems to find out what what is wrong with my codes? i can't pass in non-empty String value into an empty String array?
String[] profiles = wifiPositioningServices.GetAllProfileData();
ArrayList<String[]> macAddresses = new ArrayList<String[]>();
String[] macAddressTemp=null;
//store all profile data into a ArrayList of Profile objects
for(int i=0; i<profiles.length; i++){
String[] result = profiles[i].split(",");
Profile profile = new Profile();
profile.setProfileName(result[0]);
profile.setOwner(result[1]);
profile.setMap(result[2]);
profile.setVisible(result[3]);
boolean visible = Boolean.valueOf(result[3]);
if(visible){
//if visible is true, then add profile name and mac filters into arraylist
profileNames.add(result[0]);
int cnt=0;
for(int j=4; j<result.length; j++){
profile.setMacFiltersList(result[j]);
Log.e("Text:", result[j]);
macAddressTemp[cnt] = result[j];
++cnt;
}
macAddresses.add(macAddressTemp);
}
profileList.add(profile);
}
Java show a nullpointer exception at the line "macAddressTemp[cnt] = result[j];". I am sure that result[j] is not empty cause i was able to print it out via the log msg.
Use an ArrayList instead.
ArrayList<String> macAddressTemp = new ArrayList<String>(100); //check capacity
macAddressTemp.add(result[j]);
EDIT:
You changed your code wrong.
This ArrayList<String[]> macAddresses = new ArrayList<String[]>(); is creating a List that contains arrays. You have to create a List that contains String. Check the code above.
The array macAddressTemp is null.
The NPE is thrown because macAddressTemp is null. You probably want to declare and initialize macAddressTemp inside of the outer loop.
You explicitly set it to null:
String[] macAddressTemp=null;
You need to allocate some space for the array, or use a collection.

JAVA- how to assign string value to string array dynamically

In my application i got string values dynamically. I want to assign these values to string array then print those values.But it shows an error(Null pointer exception)
EX:
String[] content = null;
for (int s = 0; s < lst.getLength(); s++) {
String st1 = null;
org.w3c.dom.Node nd = lst.item(s);
if (nd.getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
NamedNodeMap nnm = nd.getAttributes();
for (int i = 0; i < 1; i++) {
st1 = ((org.w3c.dom.Node) nnm.item(i)).getNodeValue().toString();
}
}
content[s] = st1;
//HERE it shows null pointer Exception.
}
Thanks
This is because your string array is null. String[] content=null;
You declare your array as null and then try to assign values in it and that's why it is showing NPE.
You can try giving initial size to your string array or better to use ArrayList<String>.
ie:
String[] content = new String[10]; //--- You must know the size or array out of bound will be thrown.
Better if you use arrayList like
List<String> content = new ArrayList<String>(); //-- no need worry about size.
For list use add(value) method to add new values in list and use foreach loop to print the content of list.
Use ArrayList or Vector for creating collection (or array) of strings in a dynamic fashion.
List<String> contents = new ArrayList<String>();
Node node = (org.w3c.dom.Node) nnm.item(i)).getNodeValue();
if (null != node)
contents.add(node.toString());
Outside the loop you can do as follows
for(String content : contents) {
System.out.println(content) // since you wanted to print them out
It's a little hard to understand what you're after because your example got munged. However, your String array is null. You need to initialize it, not just declare it. Have you considered using an ArrayList instead? Arrays in java are fixed length (unless they changed this since my university days).
ArrayList is a lot simpler to work with.
E.g.:
List<String> content = new ArrayList<String>();
for (int i = 0; i < limit; i++){
String toAdd;
//do some stuff to get a value into toAdd
content.add(toAdd)
}
There's also something weird with one of your for loops.
for(int i=0;i<1;i++)
The above will only ever iterate once. To clarify:
for(int i=0;i<1;i++){
System.out.println("hello");
}
is functionally identical to:
System.out.println("hello");
They both print out "hello" once, adn that's it.
Use
content[s] = new String(st1);
Now it creates new instance for that particular array index.

ArrayList to Array of Strings in java

ArrayList<String> newArray = new ArrayList<String>();
newArray = urlList.getUrl();
for( int i = 0 ; i < newArray.size();i++)
{
System.out.println(newArray.get(i));
}
newArray.toArray(mStrings );// is this correct
mStrings = newArray.toArray();// or this to convert ArrayList ot String array here
for( int i = 0 ; i < mStrings.length;i++)
{
System.out.println(mStrings[i]);
}
EDIT: when i try as below, I get null pointer exception:
try
{
newArray.toArray(mStrings );
for(int i = 0 ; i < mStrings.length; i++)
{
System.out.println(mStrings[i]);
}
} catch( NullPointerException e )
{
System.out.println(e);
}
Usually I write
String[] array = collection.toArray(new String[collection.size()]);
because this way
I get an array of the type that I want.
I don't have to declare the array before calling Collection.toArray(T[]).
Depends on what you want to do. Both are correct
toArray()
Returns an array containing all of the elements in this list in proper sequence (from first to last element).
Refer here
toArray(T[] a)
Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.
Refer here
In former, you want to get an array. In latter you have an array, you just wanted to fill it up.
In your case, first form is preferred as you just want to get an array without bothering size or details.
Basically this is what happens in 2nd case:
List's size is measures.
(a) If list size is less than that of the array provided, new Array of the type provided as argument is created.(b)Else, the list is dumped in the specified array.
The only benefit of doing so, is you avoid casting. The two form are the same. If you use Object array. i.e.
myList.toArray() <==> toArray(new Object[0])
Now, If you pass an uninitialized array, you will get a NullPointerException. The best way to do it is:
String[] y = x.toArray(new String[0]);
Please read the document
The first option is better as it allows you to pass in a typed array, which is then populated inside the method.
The second option returns an Object[] - so you would have to cast it to use String methods.
In plain java i'm use something like
rolesList.toArray(new Integer[rolesList.size()]);
for converting list to array. Don't know in android.
How about this
List a = new ArrayList();
a.add("wer");
a.add("sff");
String[] f= (String[]) a.toArray(new String[0]);
System.out.println(f[0]);

Categories

Resources