2

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

2 Answers 2

2

Making the array isn't enough, you also have to give each index something to hold. Otherwise, each index in the array will hold null for Object arrays. For example, to assign something to index 0 after creating the array:

sok_kocka = new Kocka[10]; 
sok_kocka [0] = new Kocka();

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, not 1.

Sign up to request clarification or add additional context in comments.

Comments

0

sok_kocka = new Kocka[10]; creates an empty array of size 10 that can hold objects of type "Kocka". This however does not mean that the array has any items in it - You have to assign those manually.

Comments

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.