lilzz
lilzz

Reputation: 5413

ImageView Android

Method1 (Not working) I declared an Imageview in XML

<ImageView
    android:id="@+id/imageView1" 
    android:layout_height="wrap_content"
    android:layout_weight="0.21" 
    android:layout_width="100dp" 
    android:layout_gravity="center">
</ImageView>

Then I declare it in code

ImageView iv=(ImageView)findViewById(R.id.imageView1);

Then I download a image from web (image)

iv.setImageBitmap(image);
setContentView(iv);

Method2 (working)

Instead of XML i just declare

ImageView iv=new ImageView(this);

Then I download a image from web (image)

iv.setImageBitmap(image);
 setContentView(iv);

The question why Method1 doesn't work and Method2 works?

Upvotes: 0

Views: 6231

Answers (3)

Bobbake4
Bobbake4

Reputation: 24857

You should be doing setContentView(R.layout.file_containing_imageView). Then you can call findViewById().

The issue you are having is you are using findViewById() before setting the content view so there are no views present to find.

Upvotes: 0

Hemant Menaria
Hemant Menaria

Reputation: 701

I agree with @blessenm you should put setContentView code (in which that imageView xml written ) berfor FindViewById for image.

ex: setContentView(R.layout.mainxml);
    iv=(imageView)findViewById(R.id.imageView1);
    iv.setImageBitmap(image);

Upvotes: 0

blessanm86
blessanm86

Reputation: 31789

Method 1 should give a force close error as you are using findViewById before setContentView. FindViewById tries to find the view inside the layout you specified in setContentView. So setContentView should be called first.

Upvotes: 4

Related Questions