I’m slowly getting crazy… trying to define a very simple class array to hold instances of other reference class.
But I’m getting null pointer error all the time.
What do I wrong?
For any help I am very thankful!!
//-------------------------
// main activity
//-------------------------
package bangkokguy.android.fromscratch;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Palya kaki = new Palya();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
//-------------------------
// class Palya
//-------------------------
package bangkokguy.android.fromscratch;
public class Palya {
public Kocka sok_kocka [];
public Palya() {
sok_kocka = new Kocka[10];
<b>sok_kocka [1].letter = ' '; /*!!! null pointer here */</b>
}
}
//-------------------------
// class Kocka
//-------------------------
package bangkokguy.android.fromscratch;
public class Kocka /*implements _NewLetter, _IsFree*/ {
public char letter;
static final char c_empty = ' ';
public Kocka () {letter = c_empty;}
public Kocka (char letterke) {letter = letterke;}
public void _NewLetter (char letterke) {letter = letterke;}
public boolean _IsFree () {return letter == c_empty;}
}
Making the array isn’t enough, you also have to give each index something to hold. Otherwise, each index in the array will hold
nullfor Object arrays.For example, to assign something to index 0 after creating the array:
You will have to do this for all the indexes in the array if you want to avoid NPEs. Also keep in mind array indexes start at
0, not1.