I referred to this question but it does not offer what I am asking about.
I have some variables which are declared globally and, initially, they are assigned to NULL. Inside the constructor I call a function called "newGame()"
, this function initialise the variables. And inside onDraw()
I am trying to draw a text contains the size of one of the variables that I have initialised inside the newGame()
function, and when I run the app, it crashes, and logCat
says: NPE
.
So, i think, if the constructor is called first, my variables should have been initialsed, so that there should be no NPE
. But, since there is NPE
, it seems that, onDraw()
is called before the constructor, is that true?
Update_1
I have also placed the newGame()
function inside onSizeChanged()
but, I receive the same NPE
Update_2
I am checking if an object of a hashmap
is null or not like this in the following:
if (obj == null)
is it correct to check whether or not an object is null?
Update_3
here is how I initialise the "hand"
if (hand == null) {
Log.i(TAG, "@dealCards: Hand hashMap was NULL, it will be initialised");
hand = new HashMap<Integer, Card>();
}
Code
private HashMap<Integer, Card> deck = null;
private HashMap<Integer, Card> tableHand = null;
private HashMap<Integer, Card> myHand = null;
private HashMap<Integer, Card> compHand = null;
....
....
//CONSTRUCTOR
public GameView(Context context) {
super(context);
// TODO Auto-generated constructor stub
mContext = context;
scale = mContext.getResources().getDisplayMetrics().density;
textPaint = new Paint();
textBounds = new Rect();
deckSize_String = "Deck_Size: ";
cardArraySize_String = "cardsArraySize: ";
textPaint.setAntiAlias(true);
textPaint.setColor(Color.RED);
textPaint.setStyle(Paint.Style.STROKE);
textPaint.setTextAlign(Paint.Align.LEFT);
textPaint.setTextSize(scale*15);
newGame();
}
....
....
//OnDraw()
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawText("tableHand: "+tableHand.size(), 10, 200, textPaint);
}
private void newGame() {
// TODO Auto-generated method stub
Log.i(TAG, "@newGame()");
initDeck();
dealCards(deck, tableHand);
myTurn = whosTurn();
if (myTurn) {
dealCards(deck, myHand);
dealCards(deck, compHand);
}else {
dealCards(deck, myHand);
dealCards(deck, compHand);
}
}
...
...
...
private void dealCards(HashMap<Integer, Card> deck, HashMap<Integer, Card> hand) {
// TODO Auto-generated method stub
if (hand == null) {
Log.i(TAG, "@dealCards: Hand hashMap was NULL, it will be initialised");
hand = new HashMap<Integer, Card>();
}
for (int i=0; i<4; i++) {
hand.put( (hand.size()+1), deck.get( ((DECK_MAX_SIZE - deck.size())+1) ) );
copyDealtCards( dealtCardsPile, deck.get( ((DECK_MAX_SIZE - deck.size())+1) ) );
deck.remove( ((DECK_MAX_SIZE - deck.size())+1) );
}
}