Unexpected NullPointerException while accessing re

2019-06-10 15:08发布

问题:

This question already has an answer here:

  • DBpedia Jena Query returning null 1 answer

I have this code and I don't understand why I'm getting a NullPointerException:

public static ArrayList<String> retrieveObject(String istance,String property){
    String sparqlQueryString= "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-   syntax-ns#> "+
        "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "+
        "PREFIX dbpedia: <http://dbpedia.org/resource/> "+
        "PREFIX o: <http://dbpedia.org/ontology/> "+
        "PREFIX dbprop: <http://dbpedia.org/property/>"+
        "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>" +
        "select ?c"+
        "where {<"+istance+"> "+property+" ?c.}";
    ArrayList<String> array = new ArrayList<String>();
    Query query = QueryFactory.create(sparqlQueryString);
    QueryExecution qexec = QueryExecutionFactory.sparqlService("http://dbpedia.org/sparql", query);
    ResultSet res = qexec.execSelect();
    for(; res.hasNext();) {
        QuerySolution soln = res.nextSolution();
        for(int i=0;i<query.getProjectVars().size();i++){
            array.add(soln.get(query.getProjectVars().get(i).getVarName()).asResource().toString());   
        }

    }
    return array;
} 

I call the method in this way:

System.out.println(retrieveObject("http://dbpedia.org/resource/Immanuel_Kant","o:deathPlace"));

回答1:

I have Null pointer exception at this line: array.add(soln.get(query.getProjectVars().get(i).getVarName()).asResource().toSt‌​ring());

Break the expression apart to find the NPE - one possibility is that it isn't a URI so asResource is wrong.

Better might be

   for(String var : query.getResultVars() {
        Resource r = soln.getResource(var) ;
        array.add(r.getURI()) ;
   }

(beware of blank nodes)