Will Will - 1 month ago 10
Android Question

imageView.setImageBitmap is not working in android

solved by Emil thx
I have following in my main

package com.example.surfacetest;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
//this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
ImageView img = (ImageView) findViewById(R.drawable.hero_frame);
img.setImageBitmap(BitmapFactory.decodeResource(this.getResources(),R.drawable.chen_gong));

}

}
`


in the xml file I have

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".MainActivity" />
<ImageView
android:id="@+id/hero1"
android:maxWidth="100dp"
android:maxHeight="100dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerInside"
android:layout_marginLeft="5.33dp"
/>
<ImageView
android:id="@+id/hero2"
android:maxWidth="100dp"
android:maxHeight="100dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerInside"
android:layout_marginLeft="5.33dp"
android:layout_toRightOf="@id/hero1"
/>




Is there anything that I am missing, I worked on this question for the past two days and can't find any solution on internet or I am missing it. Help please.

Answer

The problem is in this line:

    ImageView img = (ImageView) findViewById(R.drawable.hero_frame);

You need to pass the ID of the ImageView you want to find, you are probably getting a NullPointerException at the moment, because img can not be found, try something like this:

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