I'm making a simple board game that uses a table view and a button array as the board squares. My movePlayer takes a destination row and column, places a token in that row and column and replaces its previous position with a button.
My movePlayer method is:
private void movePlayer(int moveToRow, int moveToCol, Button buttons[][])
{
int oldRow = player.getPlayerRow();
int oldCol = player.getPlayerCol();
Button oldPosition = buttons[oldRow][oldCol];
int oldWidth = oldPosition.getWidth();
int oldHeight = oldPosition.getHeight();
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(),
android.R.drawable.btn_default);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, oldWidth, oldHeight, true);
Resources resource = getResources();
oldPosition.setBackground(new BitmapDrawable(resource, scaledBitmap));
player.setPlayerRow(moveToRow);
player.setPlayerCol(moveToCol);
addPlayerToken(moveToRow, moveToCol, buttons);
}
I get the error java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:596) at foo.bar.minions.GameBoard.movePlayer(GameBoard.java:219)
.
This code works if I replace android.R.drawable.btn_default
with a drawable such as R.drawable.foo
.
The code will also work if I replace everything below int oldWidth
with oldPosition.setBackgroundResource(android.R.drawable.btn_default);
but the button isn't scaled properly or doesn't look like the other buttons. For reference I use tableRow.addView(button);
to create my buttons.
What can I do to make my buttons look the same?
Fixed it, the problem was because the button that was drawn using tableRow.addView(button);
is not the same image as android.R.drawable.btn_default
so the fix was just adding button.setBackgroundResource(android.R.drawable.btn_default);
to before tableRow.addView(button);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.