1

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); 

5 Answers 5

9

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.
Sign up to request clarification or add additional context in comments.

1 Comment

HiThank you I thought the mAppoitments = new cDate[24]; was setting it up,
5

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.

Comments

4

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);

1 Comment

Thank youI thought mAppoitments = new cDate[24] was intializing all the objects in the array
1
final int COUNT= 24;

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

Comments

-1
cDate myAppointments = new cDate[24];

try declaring the variable type

1 Comment

If that was the problem, it wouldn't even compile. The real issue is that his array is filled with null references.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.