Here I have some code where I create an ActionListener for a JCheckBox.
Once the user clicks the JCheckBox the actionlistener is triggered and this code runs.
First I check whether they are selecting it or deselecting the check box and I input this into the text file. I re-input the checkbox's text plus a 0 if the user is deselecting it or a 1 if they are selecting it.
However, when I try to read through my file using a loop it seems to only result in null values. Here is an excerpt of exactly what I'm talking about.
for (int i = 0; i < notes.length; i++) {
String text;
try {
text = br.readLine();
if (text.contains(s)) {
brw.write(s + "0");
brw.newLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
The notes.length is an array that contains the amount of lines of my file. I've also tried changing that to an int that held line the line count. No change, still didn't work. If I print out "text" and "s" I get the checkbox's text value followed by "null". The text variable should have a value.
I get a NullPointerException..
selected
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at SideNotes$2.actionPerformed(SideNotes.java:86)
By the way.. when I read the file in other places I do not get a NullPointerException. It returns the line just fine.
Full code:
File file = new File("notes.txt");
if (file.exists()) {
try {
FileInputStream fs = new FileInputStream(file);
final BufferedReader br = new BufferedReader(
new InputStreamReader(fs));
final BufferedReader reader = new BufferedReader(
new FileReader("notes.txt"));
FileWriter writer = new FileWriter(file, true);
final BufferedWriter brw = new BufferedWriter(writer);
while (reader.readLine() != null)
lines++;
// reader.close();
notes = new JCheckBox[lines];
ActionListener al = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JCheckBox checkbox = (JCheckBox) e.getSource();
if (checkbox.isSelected()) {
System.out.println("selected");
String s = checkbox.getText();
for (int i = 0; i < notes.length; i++) {
String text;
try {
text = br.readLine();
if (text.contains(s)) {
brw.write(s + "0");
brw.newLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
} else {
System.out.println("deselected");
String s = checkbox.getText();
for (int i = 0; i < notes.length; i++) {
String text;
try {
text = br.readLine();
if (text.contains(s)) {
brw.write(s + "0");
brw.newLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
};
Why am I getting a null result, and how do I fix it?