Andy Andy - 3 months ago 20
Android Question

Viewing an image on a Android Fragment

I am having trouble showing an image from the drawable folder on to a fragment.
When I try to show do it, it comes up with a

java.lang.NullPointerException
.
any help would be appreciated.

This is my code,

public class Fragment4 extends Fragment {
public Fragment4() {
}

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate (R.layout.fragment4, container, false);
ImageView image = (ImageView)rootView.findViewById(R.id.image);
image.setImageResource(R.drawable.image123);
return rootView;
}
}


XML file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" >

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>

Answer

Your ImageView has no id. Set it as follows,

<ImageView
   android:id="@+id/image"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content" />
Comments