null pointer exception string 2d array in java - java

public String[][] fetchData()
{
String[][] data = null;
int counter = 0;
while (counter < 10){
data[counter] = new String[] {"abc"};
counter++;
}
return data;
}
Getting the error in this loop.
Please let me know where i am wrong

You need to allocate memory to data.
String[][] data = new String[ROW][COLUMN].
Read this

String[][] data = null;
==> you have a null pointer exception when you try to write in data
You might do
String[][] data = new String[10][];

You get a NPE because you explicitly set data to null:
String[][] data = null;
You need to allocate the number of rows first:
String[][] data = new String[][NUMBER_OF_ROWS];

data[counter] = new String[] {"abc"};
Here you are putting "abc" to array, but why you're using array if it has only one cell?
data[counter] = new String("sample string");
would be enough. And ofc you need also to declare "data" as one-dimensional array.

Related

how to store two single dimensional array values into jdbc java bean values and stored it into mysql?

here I get Student id get correct format but their status i got last value only
my java bean code
String[] arr1=new String[1000]; //stuid
if(aa!=null)
{
arr1=aa.split(",");
}
String[] arr = new String[1000]; //status
if(ss!=null){
arr = ss.split(",");
}
for(int j=0;j<arr1.length;j++)
{
for(int i=0;i<arr.length;i++)
{
bb.setStuid(arr1[j]);
bb.setStatus(arr[i]);
bb.setSid(sid);
bb.setCid(cid);
bb.setTtid(ttid);
bb.setDate(date);
bb.setDid(did);
bb.setHour(hour);
}
bb=ad.AddAttendance(bb);
}
return bb;
}
see my images
and my mysql inserted value is
result page in mysql database (wrong value)
But, what I want exactly
correct data show in front end
You are always looping the entire arr array for each of the arr1 element. And that's why for each stuid, status is the last value (since the last value is stored inside bb.setStatus() when the inner loop completes for one studId).
You have to use single loop. And I think you will get your desired result.
String[] arr1=new String[1000]; //stuid
if(aa!=null)
{
arr1=aa.split(",");
}
String[] arr = new String[1000]; //status
if(ss!=null){
arr = ss.split(",");
}
for(int j=0;j<arr1.length;j++)
{
bb.setStuid(arr1[j]);
bb.setStatus(arr[j]); // It will take status of j'th studId
bb.setSid(sid);
bb.setCid(cid);
bb.setTtid(ttid);
bb.setDate(date);
bb.setDid(did);
bb.setHour(hour);
}
bb=ad.AddAttendance(bb);
}
return bb;
}
Hope this will help.
Hi hope this will work.
You should only use single for loop.
String[] arr1=new String[1000]; //stuid
if(aa!=null)
{
arr1=aa.split(",");
}
String[] arr = new String[1000]; //status
if(ss!=null){
arr = ss.split(",");
}
for(int j=0;j<arr1.length;j++)
{
bb.setStuid(arr1[j]);
bb.setStatus(arr[j]);
bb.setSid(sid);
bb.setCid(cid);
bb.setTtid(ttid);
bb.setDate(date);
bb.setDid(did);
bb.setHour(hour);
bb=ad.AddAttendance(bb);
}
return bb;
}

How to Iterate through the Android ArrayList and get the Index

I have this two ArrayLists. I need to iterate through the stationNames Array and get the index. Then return the value of the same index of stationIDs array. How do i achieve this? Please help me. The existing solutions on stackoverflow didn't work on this. I am new to android development.
When i iterate through the Array like the following code it give an error saying Array type expected; found: java.util.ArrayList<java.lang.String>
ArrayList<String> stationNames = new ArrayList<String>();
ArrayList<String> stationIDs = new ArrayList<String>();
stationName = "Hello"
int index = -1;
try {
for (int i = 0; i < stationNames.length; i++) {
if (stationNames[i].equals(stationName)) {
index = i;
break;
}
}
}
catch (Exception e){
Log.d("Excetion!",e.getLocalizedMessage());
}
return stationIDs[index];
stationNames here is not an array , but an ArrayList. So, you cannot use .length on it, use .size() :
Even simpler to do :
return stationNames.indexOf(stationName);
if it is found in the list will return its position or -1 if not.
Without all the hazzle of try catches and for loops. I could do the same task with one line of code, like following...
int output = stationIDs.get(stationNames.indexOf(stationName));
Thank you all for your help!
Just use indexOf method of the ArrayList object.
ArrayList<String> stationNames = new ArrayList<String>();
ArrayList<String> stationIDs = new ArrayList<String>();
String stationName = "Hello"
int index = stationNames. indexOf(stationName);
if(index!=-1){
String value= stationIDs[index];
}

ArrayList<Objects[]> to strings to use in SQL IN statement

I am trying to build a string to pass it as an SQL query within the IN statement.
ArrayList<Object[]> arrayList = new ArrayList<Object[]>();
List<String> strings = new ArrayList<>(arrayList .size());
for (Object object : arrayList ) {
strings.add(Objects.toString(object, null));
}
System.out.println("askldnlkasdn"+strings);
This still prints out the memory locations instead of the actual string
askldnlkasdn[[Ljava.lang.Object;#7bb11784, [Ljava.lang.Object;#33a10788, [Ljava.lang.Object;#7006c658, [Ljava.lang.Object;#34033bd0, [Ljava.lang.Object;#47fd17e3, [Ljava.lang.Object;#7cdbc5d3, [Ljava.lang.Object;#3aa9e816, [Ljava.lang.Object;#17d99928, [Ljava.lang.Object;#3834d63f, [Ljava.lang.Object;#1ae369b7]
I have also tried out
using StringBuilder and StringUtils. But things dont seem to work.
Any inputs as to where the problem is?
you should override method toString in your objects
You can use an SQL specific java Array.
try (PreparedStatement stmt = connection.prepareStatement("... IN (?) ...")) {
Object[] elements = ...
stmt.setArray(1, connection.createArray("TEXT", elements));
stmt.executeUpdate();
}
The problem you have is that you are implicitly using the toString() method of the Object elements inside your ArrayList. By default, that method returns the class and address of the Object. You should override the toString() method in every class you will use inside the list so it returns what you want it to.
This is new code that may help,
// Data of Array of Object for test the Code
Object[] a = new Object[1];
a[0] = "Hello";
Object[] b = new Object[1];
b[0] = "Friend";
Object[] c = new Object[1];
c[0] = "This is";
Object[] d = new Object[1];
d[0] = "Just Test";
// The Array List of objects and the data entry
ArrayList<Object[]> arrayList = new ArrayList<Object[]>();
arrayList.add(a);
arrayList.add(b);
arrayList.add(c);
arrayList.add(d);
// New List of strings
List<String> strings = new ArrayList<>(arrayList .size());
// The Process of adding the data from array list of objects to the strings
for(int i = 0; i < arrayList.size(); i++){
strings.add((String) arrayList.get(i)[0]);
}
// Just for print the data to console
for(int i = 0 ; i < strings.size(); i++){
System.out.println(strings.get(i));
}
System.out.println("askldnlkasdn "+strings.get(0));
I hope that solve the problem, if not please inform me, you can use it for more than one dimensional array.
You can just save it as String , like this code
ArrayList<String> arrayList = new ArrayList<>();
List<String> strings = new ArrayList<>(arrayList .size());
for (Object object : arrayList ) {
strings.add(Objects.toString(object, null));
}
System.out.println("askldnlkasdn"+strings);
Or you want it Object for specific purpose?

NullPointerException at adding int to ArrayList

I have a function which is supposed to work with given ArrayList<String> and return the output as ArrayList<Integer>. The problem is NullPointerException is raised on hourList.add(hourInt); and I don't know why.
public ArrayList<Integer> takeTime(ArrayList<String> logs) {
ArrayList<Integer> hourList=null;
Integer hourInt;
for(String line: logs) {
String[] matrix = line.split(" ");
String[] hour = matrix[3].split(":");
// System.out.print(hour[0]+"\n");
String s = hour[0].replaceFirst("^0+(?!$)", "");
hourInt = Integer.parseInt(s);
System.out.print(hourInt+",");
hourList.add(hourInt); // <--- NullPointerException here
}
return hourList;
}
System.out.print(hourInt+",");:
0,0,0,0,1,1,2,3,4,4,4,4,4,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10
You need to construct your ArrayList while declaring it:
ArrayList<Integer> hourList = new ArrayList<>();
Otherwise hourList.add will give NPE since reference hourList is null.
You have to initialize the ArrayList:
List<Integer> hourList = new ArrayList<Integer>;
You are trying to call a function of a null object. Try:
ArrayList<Integer> hourList=new ArrayList<Integer>();

Object array issue

I wan to know why am I getting a null pointer exception on the line marked below, I am trying to add stuff from a properties table to the object map, so I can insert column information into a JTable dont know if its 100% clear, but any input will be appreciated
public Object getList(){
dvd.loadList(dvd.dvdInventory);
Object [][] data = null;
int i = 0;
int j = 0;
Iterator<Object> kitr= dvd.dvdInventory.keySet().iterator();
Iterator<Object> itr = dvd.dvdInventory.values().iterator();
while(itr.hasNext()){
String key = (String) kitr.next();
String values = (String) itr.next();
String[] tokens = values.split(" / ");
for ( String token : tokens ){
data[j][i] = token.toString(); <------this line gets null
i++; pointer exception
}
i = 0;
j++;
}
return data;
}
Object [][] data = null;
The array is null. YOu need to allocate space:
Object [][] data = new Object[5][5];
or whatever size you want.
Unless you know the size of the row/columns of the array it is better to use a Vector of Vectors for the DefaultTableModel of JTable.
Edit:
To use Vectors you would restructure the code to be something like:
Vector<Vector<String>> data = new Vector<Vector<String>>();
while(itr.hasNext())
{
String key = (String) kitr.next();
String values = (String) itr.next();
String[] tokens = values.split(" / ");
Vector<String> row = new Vector<String>();
for ( String token : tokens ){
row.add(token.toString());
}
data.add(row);
}
Null pointer exception is happening because you have initialized your array as null. You need to allocate some memory to your array, right now it is just null as defined here:
Object [][] data = null;
You should know, what size do you need to for the array that you have. You cannot simply initialize it to any value. If you don't know the size then consider using the collections, which can grow dynamically.
You may consider using List of Arraylist and define it as :
List<List<Object>> lists = new ArrayList<List<Object>>();

Categories

Resources