Cooper Fryar
Cooper Fryar

Reputation: 11

Storing HashMaps for apps [CodeName One]

I have been trying to figure this out for a week or two and cannot do it.

I have two classes, MyApplication and Store. This is just a testing program to see what is wrong with my storing code.

This is the MyApplication class

public class MyApplication {
private Form current;
private Resources theme;
private Store o;

public void init(Object context) {
    theme = UIManager.initFirstTheme("/theme");
    Util.register("Store", Store.class);
    Toolbar.setGlobalToolbar(true);
}

public void start() {
    if(current != null){
        current.show();
        return;
    }

        Form hi = new Form("Hi World");

        TextField enter = new TextField("","Enter Here", 20, TextField.ANY);
        Button add = new Button("Add");

        add.addActionListener((ev)-> 
                o.add(enter.getText() + "", 100));  /*Failing here*/

        hi.add(enter).add(add);

        hi.show();

}

private void save()
{
    Storage.getInstance().writeObject("NameOfFile", o);
}

private void load()
{
    o = (Store) Storage.getInstance().readObject("NameOfFile");
}

public void stop() {
    current = Display.getInstance().getCurrent();
    if(current instanceof Dialog) {
        ((Dialog)current).dispose();
        current = Display.getInstance().getCurrent();
    }
}
public void destroy() {
}

}

This is the Store class

public class Store implements Externalizable {    
private static final int VERSION = 1;
HashMap<String, Integer> data;

public void externalize(DataOutputStream out) throws IOException 
{
    Util.writeObject(data, out);
}
public void internalize(int version, DataInputStream in) throws IOException 
{
    data = (HashMap<String, Integer>)Util.readObject(in);
}
public void add(String s, Integer i)
{
    data.put(s, i);
}
public int getVersion() 
{
    return VERSION;
}
public String getObjectId() 
{
    return "Store";
}
}

I previously used a Hash map pointers in the MyApplication class but it failed at the same location.

Upvotes: 1

Views: 50

Answers (1)

steve hannah
steve hannah

Reputation: 4716

The code you've posted doesn't seem to initialize the data HashMap anywhere. You aren't calling your load() method, and you aren't actually creating the Hashmap anywhere. Therefore the line that you have highlighted likely fails with an NPE.

In the future, you should include more information than just "Failing Here". If there is a stack trace, always provide that. If there is not a stack trace, then you need to describe how you know it fails there.

Upvotes: 1

Related Questions