views:

108

answers:

3

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];
        }
    }
}
+12  A: 

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.

Brian Schroth
Ops. I was gonna post an answer but you were faster...
luiscubal
Thanks, now I've understand :)
vasin
+4  A: 
phoneBook.records[0].Name = new String("abc");

should be

phoneBook.records[0] = new Record();
phoneBook.records[0].Name= new String("abc");// or  = "abc"
Tom
I concur with this, all you have done in your example is tell the code that your array will have 10 phone numbers, you never give it the new object. This should work.
SacramentoJoe
A: 

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();
violoncello
Thanks, I edited my answer.
Tom

related questions