HotN
HotN

Reputation: 4386

Null ImageView Reference

I'm trying to get a reference to an ImageView object and for whatever reason, it keeps coming back as null.

XML:

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:padding="6dip">
  <ImageView android:id="@+id/application_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" />
  <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/label" android:text="Application Name" />
  <CheckBox android:id="@+id/check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" />
</LinearLayout>

Java:

ImageView img = (ImageView) v.findViewById(R.id.application_icon);

I don't feel like I'm doing anything wrong yet my img var always comes back as null. What's wrong with this picture?

Upvotes: 2

Views: 6130

Answers (3)

Aleadam
Aleadam

Reputation: 40381

Sat's answer is correct, i.e., you need a proper layout, but setContentView() is not the only way to reference a View. You can use a LayoutInflater to inflate a parent layout of the View (even if it is not shown) and use that newly inflated layout to reference the View.

public class MyActivity extends Activity {
  Context context;
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    context = this;
// the rest of yout code

private void someCallback() {
  LayoutInflater inflater = (LayoutInflater) context.getSystemService
     (Context.LAYOUT_INFLATER_SERVICE);
  LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.iconLayout, null);
  ImageView img = (ImageView) ll.findViewById(R.id.application_icon);
// you can do whatever you need with the img (get the Bitmap, maybe?)

The only change you need to your xml file is to add an ID to the parent layout, so you can use it with the LayoutInflater:

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="iconLayout"
<!-- all the rest of your layout -->
  <ImageView android:id="@+id/application_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" />
<!-- all the rest of your layout -->
</LinearLayout>

Upvotes: 1

Sunil Pandey
Sunil Pandey

Reputation: 7102

use

ImageView img = (ImageView)findViewById(R.id.application_icon);

Upvotes: 0

sat
sat

Reputation: 41076

When you are referencing the imageView , make sure that you are using the proper layout, i.e. setContentView(R.layout.yourIntendedXmlLayout);

That xml should contain your imageView. Then you can refer to your imageView.

Upvotes: 1

Related Questions