Ted pottel
Ted pottel

Reputation: 6983

My Java code crashes when I try to call a method from an array of objects

I’m just learning Java and trying to have an array of a class. When a call a methed from the array it crashes. Works fine if it is not an array

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  cDate test=new cDate();
  test.setDay(0);
  mAppoitments = new cDate[24];
  // crashes why?????
  mAppoitments[0].setDay(0); 

Upvotes: 1

Views: 125

Answers (5)

Erdinç Taşkın
Erdinç Taşkın

Reputation: 1578

final int COUNT= 24;

mAppoitments = new cDate[COUNT];
for(int i = 0 ; i < COUNT ; ++i) {
   mAppoitments[i] = new cDate();
   mAppoitments[i].setDay(0); 
}

Upvotes: 1

Kevin
Kevin

Reputation: 1921

You have initialized the array but not the objects in the array. Try initializing these elements before using them.

mAppoitments = new cDate[24];
for (int i = 0; i < mAppoitments.length; i++)
    mAppoitments[i] = new cDate();
mAppoitments[0].setDay(0);

Upvotes: 4

Matt Ryan
Matt Ryan

Reputation: 1717

cDate myAppointments = new cDate[24];

try declaring the variable type

Upvotes: -1

sjr
sjr

Reputation: 9875

You have an array of 24 objects, each of which is set to null. You need to initialize each one before you can call methods on it.

Upvotes: 5

Bozho
Bozho

Reputation: 597106

You haven't filled your array with objects. You have to:

  cDate[0] = test;

Otherwise you have null at index 0, and you cannot invoke anything on null.

And next time you ask a question, give all needed details:

  • what is the exception message and stacktrace. "crashes" means almost nothing
  • tell us what are your variables that are not initialized in the code snippet. You can see one answer that is telling you to fix a local declaration, which is probably an instance variable.

Upvotes: 9

Related Questions