Null pointer exception when trying to access method (java) [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am developing some code in Java but facing a problem with a NPE.
It happens when I try to use a method in another class.
Here is my code :
public class MyClass{
private Attributes attr = null;
public static void main(String [ ] args) throws ParseException, SAXException, IOException, ParserConfigurationException {
MyClass main = new MyClass();
Options options = main.parseCommandLine();
CommandLineParser parser = new BasicParser();
CommandLine cl = parser.parse(options, args);
main.configureAttributes(main);
}
private void configureAttributes(MyClass main, CommandLine cl) throws ParserConfigurationException, SAXException, IOException {
String[] attributes = cl.getOptionValues("a");
Integer tag = null;
for(int i = 0; i < attributes.length ; i++) {
String[] parts = attributes[i].split("=");
String tagName = parts[0];
String value = parts[1];
tag = Integer.parseInt(tagName,16);
this.attr.setString(tag, DICT.vrOf(tag), value);
}
}
}
But I am getting an NPE on the last line : this.attr.setString(tag, DICT.vrOf(tag), value);
I have all the right imports. It is a Maven project so I also added the dependency to my pom.xml.
Thanks a lot for your help !
V.

Looks like you forgot to initialize your attr field. According to your source here is only one assignment to this field: private Attributes attr = null;. So, I think, you need to initialize your field somewhere in your code.

And where are you initializing Attributes attr?
You need to something like Attributes attr = new Attributes(); because right know your variable does contain nothing - null

Related

Java: ClassNotFound Classpath issues

Im trying to read some information from a file into some objects. Main method just reads the Information into some string variables then uses those strings to initialize objects. Pretty simple. The objects are stored using a BST.
However, The error Im getting is ClassNotFoundException. Except when I run the java 'file' command, 'file' is spelled and capitalized correctly.
I've been reading that you can change the path that JVM uses when searching for class files.
so I tried:
set CLASSPATH=$CLASSPATH=~/../../BackEnd
but that didn't do anything..
Here is my main file..
import java.util.Scanner;
import java.io.File;
class BackEnd
{
public static void main(String args[]) throws java.io.FileNotFoundException
{
Tree.ServiceTree providers = new Tree.ServiceTree();
String path = "./providers.txt";
Scanner read = new Scanner (new File(path));
read.useDelimiter(",");
String information[] = new String[5];//array of strings used to store info from file, then used to initialize objects
try
{
while(read.hasNext())
{
for(int i = 0; i < 5; ++i)
{
information[i] = read.nextLine();//read in all the info into the array
}
Services.Service newService;//used as dynamic reference to be passed to tree
Services.Service serviceInfo = new Services.Service(information[0], information[1]);//initalizes base class to be passed to derived constructor
switch(information[0])//check type to initalize appropriate object
{
case "Dogwalk":
newService = new Services.Dogwalk(serviceInfo, information[2], information[3]);
case "Groceries":
newService = new Services.Groceries(serviceInfo, information[2], information[3]);
case "Housework":
newService = new Services.Housework(serviceInfo, information[2], information[3]);
}
providers.insert(information[4], newService);
}
read.close();
throw new java.io.FileNotFoundException("File not found...");
}
catch(java.io.FileNotFoundException exception)
{
System.out.println("File not found");
}
//providers.display();
}
}
Figured it out. Error had nothing to do with compilation or class path and was due
to uninitialized variable newService

OpenNLP categorizer Version 1.8

Im trying to build a categorizer in version 1.8 of openNLP but with the code below I keep getting a NullPointerException. What am I doing wrong?
public class test
{
public static void main(String[] args) throws IOException
{
InputStream is = new FileInputStream("D:/training.txt");
DoccatModel m = new DoccatModel(is);
Tokenizer tokenizer = WhitespaceTokenizer.INSTANCE;
String tweet = "testing sentence";
String[] tokens = tokenizer.tokenize(tweet);
DocumentCategorizerME myCategorizer = new DocumentCategorizerME(m);
double[] outcomes = myCategorizer.categorize(tokens);
String category = myCategorizer.getBestCategory(outcomes);
}
}
You should have a look at following tutorial. They are useing OpenNLP version 1.7.2. This may be a more recent example to work with.
https://www.tutorialkart.com/opennlp/training-of-document-categorizer-using-naive-bayes-algorithm-in-opennlp/
Hope it helps.

Implementing save/open with RichTextFX?

Here is my code:
private void save(File file) {
StyledDocument<ParStyle, Either<StyledText<TextStyle>, LinkedImage<TextStyle>>, TextStyle> doc = textarea.getDocument();
// Use the Codec to save the document in a binary format
textarea.getStyleCodecs().ifPresent(codecs -> {
Codec<StyledDocument<ParStyle, Either<StyledText<TextStyle>, LinkedImage<TextStyle>>, TextStyle>> codec
= ReadOnlyStyledDocument.codec(codecs._1, codecs._2, textarea.getSegOps());
try {
FileOutputStream fos = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(fos);
codec.encode(dos, doc);
fos.close();
} catch (IOException fnfe) {
fnfe.printStackTrace();
}
});
}
I am trying to implement the save/loading from the demo from here on the RichTextFX GitHub.
I am getting errors in the following lines:
StyledDocument<ParStyle, Either<StyledText<TextStyle>, LinkedImage<TextStyle>>, TextStyle> doc = textarea.getDocument();
error: incompatible types:
StyledDocument<Collection<String>,StyledText<Collection<String>>,Collection<String>>
cannot be converted to
StyledDocument<ParStyle,Either<StyledText<TextStyle>,LinkedImage<TextStyle>>,TextStyle>
and
= ReadOnlyStyledDocument.codec(codecs._1, codecs._2, textarea.getSegOps());
error: incompatible types: inferred type does not conform to equality
constraint(s) inferred: ParStyle
equality constraints(s): ParStyle,Collection<String>
I have added all the required .java files and imported them into my main code. I thought it would be relatively trivial to implement this demo but it has been nothing but headaches.
If this cannot be resolved, does anyone know an alternative way to save the text with formatting from RichTextFX?
Thank you
This question is quite old, but since i ran into the same problem i figured a solution might be useful to others as well.
In the demo, the code from which you use, ParStyle and TextStyle (Custom Types) are used for defining how information about the style is stored.
The error messages you get pretty much just tell you that your way of storing the information about the style (In your case in a String) is not compatible with the way it is done in the demo.
If you want to store the style in a String, which i did as well, you need to implement some way of serializing and deserializing the information yourself.
You can do that, for example (I used an InlineCssTextArea), in the following way:
public class SerializeManager {
public static final String PAR_REGEX = "#!par!#";
public static final String PAR_CONTENT_REGEX = "#!pcr!#";
public static final String SEG_REGEX = "#!seg!#";
public static final String SEG_CONTENT_REGEX = "#!scr!#";
public static String serialized(InlineCssTextArea textArea) {
StringBuilder builder = new StringBuilder();
textArea.getDocument().getParagraphs().forEach(par -> {
builder.append(par.getParagraphStyle());
builder.append(PAR_CONTENT_REGEX);
par.getStyledSegments().forEach(seg -> builder
.append(
seg.getSegment()
.replaceAll(PAR_REGEX, "")
.replaceAll(PAR_CONTENT_REGEX, "")
.replaceAll(SEG_REGEX, "")
.replaceAll(SEG_CONTENT_REGEX, "")
)
.append(SEG_CONTENT_REGEX)
.append(seg.getStyle())
.append(SEG_REGEX)
);
builder.append(PAR_REGEX);
});
String textAreaSerialized = builder.toString();
return textAreaSerialized;
}
public static InlineCssTextArea fromSerialized(String string) {
InlineCssTextArea textArea = new InlineCssTextArea();
ReadOnlyStyledDocumentBuilder<String, String, String> builder = new ReadOnlyStyledDocumentBuilder<>(
SegmentOps.styledTextOps(),
""
);
if (string.contains(PAR_REGEX)) {
String[] parsSerialized = string.split(PAR_REGEX);
for (int i = 0; i < parsSerialized.length; i++) {
String par = parsSerialized[i];
String[] parContent = par.split(PAR_CONTENT_REGEX);
String parStyle = parContent[0];
List<String> segments = new ArrayList<>();
StyleSpansBuilder<String> spansBuilder = new StyleSpansBuilder<>();
String styleSegments = parContent[1];
Arrays.stream(styleSegments.split(SEG_REGEX)).forEach(seg -> {
String[] segContent = seg.split(SEG_CONTENT_REGEX);
segments.add(segContent[0]);
if (segContent.length > 1) {
spansBuilder.add(segContent[1], segContent[0].length());
} else {
spansBuilder.add("", segContent[0].length());
}
});
StyleSpans<String> spans = spansBuilder.create();
builder.addParagraph(segments, spans, parStyle);
}
textArea.append(builder.build());
}
return textArea;
}
}
You can then take the serialized InlineCssTextArea, write the resulting String to a file, and load and deserialize it.
As you can see in the code, i made up some Strings as regexes which will be removed in the serialization process (We don't want our Serializer to be injectable, do we ;)).
You can change these to whatever you like, just note they will be removed if used in the text of the TextArea, so they should be something users wont miss in their TextArea.
Also note that this solution serializes the Style of the Text, the Text itself and the Paragraph style, BUT not inserted images or parameters of the TextArea (such as width and height), just the text content of the TextArea with its Style.
This issue on github really helped me btw.

Replace the end of a string

I have a path name thats a xml and im trying to replace it with.pdf .
I am trying to do it like this:
"files" is a string, for example its value is 123456.xml or 123456.XML
else if(files.endsWith(".XML") || files.endsWith(".xml")){
String pdfName = files.replace(".xml", ".pdf");
derp = db.getDerpyName(pdfName);
XMLobj.Process(files, derp);
}
When I do a print of pdfname its still 123456.xml
Im trying to make it 123456.pdf
Please advise.
Thanks!
Your assumptions must be wrong, I tested this code
public static void main(String[] args) throws Exception {
String files = "123456.xml";
String pdfName = files.replace(".xml", ".pdf");
System.out.println(pdfName);
}
The output is
123456.pdf
EDIT:
Based on your comment asking for case insensitivity, you could do -
public static void main(String[] args) throws Exception {
String files = "123456.XML";
int index = files.toLowerCase().indexOf(".xml");
String pdfName;
if (index > -1) {
pdfName = files.substring(0, index) + ".pdf";
} else {
pdfName = files + ".pdf";
}
System.out.println(pdfName);
}
Which will also output
123456.pdf
Use this and it will work even if the name is .XML or .xml :)
files.replaceAll("(?i)\.xml", ".pdf");
Try just like this for replace with ignore case with regx:
public static void main(String[] args) throws Exception {
String files = "123456.XML";
String pdfName = files.replaceAll("(?i)xml", "pdf");
System.out.println(pdfName);
}
String pdfName = files.replace(".xml",".pdf").replace(".XML",".pdf")
For the sample code you have posted in your question, you should change it as follows:
else if(files.toLowerCase().endsWith(".xml")){
// ^ checks every possibility such as ".XML", ".xMl", ".Xml", and so on
String pdfName = files.replaceAll("(?i)\.xml", ".pdf");
// ^ as per other answers, replaces case-insensitive
derp = db.getDerpyName(pdfName);
XMLobj.Process(files, derp);
}
This has the potential problem of doing unnecessary replacement in a filename like My.xml.file.xml which will become My.pdf.file.pdf.
If you need to avoid that and you only want My.xml.file.pdf, you can use the following regex instead: "(?i)\.xml$" or "(?i)\.xml\Z"

Getting variables from another .java file using reflection

I've managed to get reflection working by getting and formatting the variables in the class that the toString() method is in.
public class ReadFile {
public int test1 =0;
public String test2 = "hello";
Boolean test3 = false;
int test4 = 1;
public static void main(String[] args) throws IOException{
ReadFile test = new ReadFile();
System.out.println(test);
}
public String toString(){
//Make a string builder so we can build up a string
StringBuilder result = new StringBuilder();
//Declare a new line constant
final String NEW_LINE = System.getProperty("line.separator");
//Gets the name of THIS Object
result.append(this.getClass().getName() );
result.append(" Class {" );
result.append(NEW_LINE);
//Determine fields declared in this class only (no fields of superclass)
Field[] fields = this.getClass().getDeclaredFields();
//Print field names paired with their values
for ( Field field : fields ) {
result.append(" ");
try {
result.append(field.getType() + " ");
result.append( field.getName() );
result.append(": ");
//requires access to private field:
result.append( field.get(this) );
} catch ( IllegalAccessException ex ) {
System.out.println(ex);
}
result.append(NEW_LINE);
}
result.append("}");
return result.toString();
}
}
However I was wondering whether it would be possible to specify a specific file in the directory for the toString() to work on?
I have tried getting a file and plugging it in the System.out.println() but the way I see it is you need to make an instance of a class and give it the instance for it to work. So I'm not sure how that can be done programatically.
I have been trying something like this:
Path path = FileSystems.getDefault().getPath("D:\\Directory\\Foo\\Bar\\Test.java", args);
File file = path.toFile();
System.out.println(file);
However I don't get very far with it, I've mainly been seeing if I can convert the file into anything usable but I'm not sure what I need to be doing!
Any advice would be great.
I think you need to look into the ClassLoader API - you need to get an new URLClassLoader and ask it to load your .java file into the JVM. You can then reflect on it.
You can try to read the package information from the file (D:\Directory\Foo\Bar\Test.java) and than try to load it the class by its name:
Class.forName(nameOfTheClass)
Java API Class

Categories