Andy
Andy

Reputation: 61

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>

Upvotes: 0

Views: 1976

Answers (2)

b1programmer
b1programmer

Reputation: 187

It is because you didn't add id attribute to the image in xml Try this:

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

Upvotes: 3

Neerajlal K
Neerajlal K

Reputation: 6828

Your ImageView has no id. Set it as follows,

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

Upvotes: 4

Related Questions