Search code examples
repast-simphony

Repast: cannot call method from another class in Context Builder


I dont know why I get NullPointerException:

ERROR [AWT-EventQueue-0] 18:21:05,864 repast.simphony.ui.RSApplication - Error while initializing simulation
java.lang.NullPointerException
    at intraCity_Simulator.GlobalScheduler.load_data(GlobalScheduler.java:20)
    at intraCity_Simulator.Initialization_Builder.build(Initialization_Builder.java:306)
    at repast.simphony.dataLoader.engine.ClassNameContextBuilder.build(ClassNameContextBuilder.java:41)

Below is the code. The query works when I put it directly in the initialization (context builder) but when I put this code in another class and call it in the context builder it reports NullPointerException.

public void load_data() {
    Context<Object> context = ContextUtils.getContext(this);
    Iterable<Object> readers = context.getObjects(DataReader.class);
    DataReader this_reader = null;
    Query<Object> reader_query = new PropertyEquals<Object>(context, "name", "parcel");
    for (Object o : reader_query.query()) {
        if (o instanceof DataReader) {
            this_reader = (DataReader) o;
        }
    }
    System.out.print(this_reader.getName());
}   

when I do this in context builder it reports nullPointerException

GlobalScheduler gs = new GlobalScheduler();
context.add(gs);
gs.load_data();

UPDATE:

I just find the line "Context context = ContextUtils.getContext(this);" is not working. the context is still being null. Why? But I need this line as the query needs the context as a parameter.

However, if I follow your suggestion to pass the context directly into the method load_data() it works.

public void load_data(Context context) {
//      Context<Object> context = ContextUtils.getContext(this);
        DataReader this_reader = null;
        System.out.println("context  " + context);
        Query<Object> reader_query = new PropertyEquals<Object>(context, "name", "parcel");
        for (Object o : reader_query.query()) {
            System.out.println(o);
            if (o instanceof DataReader) {
                this_reader = (DataReader) o;
            }
        }
        System.out.print(this_reader.getName());
}

Why can I not be able to identify the context using "Context context = ContextUtils.getContext(this);" ? This method works if it is called as a method in step() but fails if it is called as method in Context Builder.


Solution

  • What's actually null there? Without that its hard to tell if this is a repast question or just fixing a null pointer error. If its the latter, it should be easy enough to determine what variable is null, and then why it is so.

    That said, you probably don't need this line

    Context<Object> context = ContextUtils.getContext(this);

    if you are calling it in the ContextBuilder -- just pass in the context to load_data(). That would at least avoid the context being null.