0

I have: public class TestButton extends ImageButton {....

I have some code which generates a null pointer exception at:

  final Drawable temp1 = babyview.getDrawable();

Before this I use:

 public void dancebabydance() {
  babyview = (ImageView) findViewById(R.id.baby);

Here is the xml portion:

<ImageView
    android:id="@+id/baby"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:src="@drawable/dbaby2"
     />

I am ideally trying to compare this dbaby2 to a drawable and see if they are equal, and if they are change them to something new.

Can this be done extending ImageButton like this? Where am I stuffing up?

Prmths
  • 2,022
  • 4
  • 21
  • 38
John Ashmore
  • 1,015
  • 1
  • 10
  • 25
  • 1
    This may be dumb, but are you setting contentView to whatever layout your ImageView is a a part of? – Prmths Sep 13 '13 at 03:38
  • from where you are calling `dancebabydance()`? post that part also – Nizam Sep 13 '13 at 03:40
  • as mentioned in my answer use `android:tag` to set a `String` and use that to compare your images... you can set the resource id as the tag value or set the resource name... – Ali Sep 13 '13 at 04:16
  • Yes, I didn't set contentView within this class, that is it I guess – John Ashmore Sep 14 '13 at 05:26

2 Answers2

2

The problem is in the second part

babyview = (ImageView) findViewById(R.id.baby);

in the class(is it an Activity?) view there is no such view. It usually happens because of one of three reasons:

1) you forgot to setContentView

2) you try to get view before you called setContentView

3) you use a wrong layout in setContentView

Maxim Efimov
  • 2,747
  • 1
  • 19
  • 25
1

I would recommend using the android:tag field to set a String that you can compare. No other method is going to work well for you.

getDrawable() will only have a value if you called setImageDrawable() in your code. If you are trying to get the drawable you provided in the android:src attribute.. well you have to get it directly from resources you cannot get it from the ImageView.

If you know the resource id (R.id.my_drawable for example) and want to get the Drawable you can use:

Drawable d = getResources().getDrawable(android.R.drawable.my_drawable);
    ImageView image = (ImageView)findViewById(R.id.image);
    image.setImageDrawable(d);

If you don't know the resource id look at the answer here.

You can get the a Bitmap of the ImageView however. You can call setDrawingCacheEnabled(true) then call getDrawaingCache() to get a Bitmap. If you do this remember to set setDrawingCacheEnabled(false).

Community
  • 1
  • 1
Ali
  • 12,354
  • 9
  • 54
  • 83