Reputation: 6983
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
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
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
Reputation: 1717
cDate myAppointments = new cDate[24];
try declaring the variable type
Upvotes: -1
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
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:
Upvotes: 9