0

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"));
Joshua Taylor
  • 84,998
  • 9
  • 154
  • 353
user2837896
  • 271
  • 3
  • 11
  • We need a stack trace. – Robin Green Oct 13 '13 at 15:42
  • I have Null pointer exception at this line: array.add(soln.get(query.getProjectVars().get(i).getVarName()).asResource().toString()); – user2837896 Oct 13 '13 at 17:44
  • @user2837896 I see you posted a comment "I solved. One space missed after ?c." One: if you found a solution, you should post it as an answer and accept it. Two: I've seen this problem appear on Stack Overflow before, so this is a duplicate (I'm looking for it now). – Joshua Taylor Oct 14 '13 at 14:47
  • Please, oh please, read [this answer](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception/218390#218390) – Simon Forsberg Oct 14 '13 at 18:37

1 Answers1

0

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)

AndyS
  • 16,345
  • 17
  • 21