Question

I have this code inside onCreateView in a fragment:

star = (ImageView) rootView.findViewById(R.id.heart);
    star.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity(),"the star was clicked",
                   Toast.LENGTH_LONG).show();
        }
    });

and it's giving null pointer exception. Anyone has any idea of what could it be ?

EDIT: I am editing because the answers didn't make it clear how to resolve the issue. The problem is that rootView, the view I am inflating, is a custom list view, on which I later inflate layout item_row to define a single row in the view. The heart id is defined in this item_row but I am trying to access it from the rootView which is not possbile of course. So could anyone provide me an example of how could I do it ?

Was it helpful?

Solution 2

R.id.heart does not belong to rootView. It means that is not declared inside the layout you inflated inside your onCreateView.

OTHER TIPS

I am doing the same thing. Here is an example that works. Make sure the View you are trying to access has an id defined in the layout you are inflating. In my example R.layout.lesson_video_fragment has an ImageView defined in with the ID R.id.lesson_video.

layout file (lesson_video_fragment.xml):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" 
android:orientation="vertical">

<ImageView 
    android:id="@+id/lesson_video"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:contentDescription="Video"
    android:scaleType="centerCrop"
    />

</LinearLayout>


public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.lesson_video_fragment, container, false);

    videoImage = (ImageView)v.findViewById(R.id.lesson_video);

    videoImage.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            //do your thing
        }           
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top