Question

I'm writing an app for Java ME, and I need a class for holding some data(PhoneBook). When I'm trying to launch this app, I'm always getting a nullPointerException. I'm calling the constructor of a class, and it allocates memory for 10 elements, so it shouldn't be null. What am I doing wrong?

import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

public class TinyMIDlet extends MIDlet implements CommandListener {

    private PhoneBook phoneBook = new PhoneBook();

    public void initPhoneBook() {
        phoneBook.records[0].Name = new String("abc");        
    }

    protected void startApp() {
        initPhoneBook();
    }

    public class Record {
        public String Name;
        public String Number;
        public String email;
        public String Group;
    }

    public class PhoneBook {
        public Record[] records;

        PhoneBook() {
            records = new Record[10];
        }
    }
}
Was it helpful?

Solution

The array of records isn't null, but each individual element of it is. You need to instantiate each element as well, right now it's just an array with 10 null entries.

OTHER TIPS

phoneBook.records[0].Name = new String("abc");  

should be

phoneBook.records[0] = new Record();
phoneBook.records[0].Name= new String("abc");// or  = "abc"

I'm not reputable enough yet (heh) to edit Tom's detailed answer, but, to be precise

phoneBook.records[0] = new something();

should be

phoneBook.records[0] = new Record();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top