I'm having some Trouble with an ArrayList. All i need to do is to pass a filled ArrayList to another Class so i can use the Values of the ArrayList there. Here's a snippet from the first Class:
public ArrayList<String> collCollect = new ArrayList<String>();
for (int i = 0; i < ListModel.size(); i++) {
collCollect.add(ListModel.get(i).toString());
}
System.out.println(collCollect);
Till this Part everything is going quite well (i stripped the rest of the Code!)
Now comes the tricky Part! This is the Second Class:
ClassA pMain;
DecimalFormat f = new DecimalFormat("#0.00");
public ArrayList<String> listContent = new ArrayList<String>(pMain.collCollect);
DefaultListModel<String> ListModelNew = new DefaultListModel<String>();
public static void main(String args[]) {
for (int i = 0; i < listContent.size(); i++){
ListModelNew.add(i, listContent.get(i));
}
}
Everytime the ClassB is loaded i get a NullPointerException from the Line where the reference to the Array in pMain is made.
Any help would be appriciated...i'm unable to get the Values from ClassA ArrayList to ClassB -.-
ClassA pMain; // here you not initialized the object.
pMain.collCollect // here you are getting the NullpointerException
public ArrayList<String> listContent = new ArrayList<String>(pMain.collCollect);
^__see here
change
ClassA pMain;
to
ClassA pMain = new ClassA ();
An instance of ClassA needs to be created in the second class. I would recommend creating it within the main method so ClassA is not a dependency for the second class.
DecimalFormat f = new DecimalFormat("#0.00");
public ArrayList<String> listContent;
DefaultListModel<String> ListModelNew = new DefaultListModel<String>();
public static void main(String args[]) {
ClassA pMain = new ClassA();
listContent = new ArrayList<String>(pMain.collCollect);
for (int i = 0; i < listContent.size(); i++){
ListModelNew.add(i, listContent.get(i));
}
}
This can be further refactored:
DecimalFormat f = new DecimalFormat("#0.00");
DefaultListModel<String> ListModelNew = new DefaultListModel<String>();
public static void main(String args[]) {
ClassA pMain = new ClassA();
for (int i = 0; i < pMain.collCollect.size(); i++){
ListModelNew.add(i, pMain.collCollect.get(i));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With