0

I have a Navigation Drawer and want to retrieve the content inside the item in the ListView I am going to click. I can retrieve the position, but no way to link to the list view to get the content of the item clicked. in the debugger i see that is present a list view and indicate also the id left_drawer that is the same I have into the xml file and I try to retrieve:

 android.widget.ListView{634ed4d VFED.VC.. .F..H.ID 0,0-630,1731 #7f0e004f app:id/left_drawer}

so I am wondering what I am doing wrong to have a NPE and why I don't retrieve the item

 @Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {

//I have the position of the list view, and want to retrieve the content of the selected item at that position
ListView listView = (ListView) view.findViewById(R.id.left_drawer);
 String sk = (String) listView.getItemAtPosition(position);//NPE because listView is null?
        Log.d("DEBUG", "onItemClick: "+sk);

//      listView.getChildAt(0);
//listView.getSelectedItem();

}
}

And this is the error message

  Process: android.com.myapp, PID: 28051 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.widget.ListView.getItemAtPosition(int)' on a null object reference
                                                                                at android.com.myapp.DrawerItemClickListener.onItemClick(DrawerItemClickListener.java:22)

this is Navigation Drawer

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"

    >
    <!-- The main content view -->

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/fragment_as_list"
    android:name="android.com.myApp.FragmentA"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
        />

    <ListView android:id="@+id/left_drawer"
        android:layout_width="240dp"

        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="19dp"
        android:background="@drawable/image_background"
        android:paddingTop="?android:attr/actionBarSize"

        android:paddingLeft="@dimen/activity_horizontal_margin"

        android:paddingRight="@dimen/activity_horizontal_margin"

        android:paddingBottom="@dimen/activity_vertical_margin"
      />
</android.support.v4.widget.DrawerLayout>

Update

In my opinion this is not a trivial NPE question. Even if I try to set a condition to eliminate the Exception was unavoidable because ListView was initiated twice once in the Main Class another time in the new class where the Google tutorial moved the Drawer object anonymous class.

Also there is any case mentioned in SO on how to retrieve an item specifically from a Navigation Drawer. Although the problem is intuitively resizable to a simple ListView.getItemAtPosition(). Putting back in one class everything is working.

halfer
  • 19,824
  • 17
  • 99
  • 186
trocchietto
  • 2,607
  • 2
  • 23
  • 36
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Phantômaxx Jul 30 '16 at 20:21
  • I do not think so. the problem is not over NPE, but the fact the listview should not be null and giving to me the text. – trocchietto Jul 30 '16 at 20:23
  • Rotwang, got it. The confusion starts from the fact that the google tutorial calls another class extending the interface onItemClickListener, so being not anonymous the List View mDrawerList is out of range, and as the other man Faisal replied I instantiate twice the list View referring on the same id. Please if is possible could you remove the upvote, it was more an architectural issue than a NPE check to foresee – trocchietto Jul 30 '16 at 20:57
  • `(ListView) view.findViewById(R.id.left_drawer);` what do you think `view` is supposed to be here? (if you are not sure, check the documentation) – njzk2 Jul 30 '16 at 22:06
  • @njzk2 of course not, you are right. the misunderstanding comes from the fact ListView is not reachable in the new class. – trocchietto Jul 30 '16 at 22:09

2 Answers2

1

There is logic error in your snippet, you are already inside your list's setOnItemClickListener method and you initialize your list again, then definitely it will hold nothing in it.

yourListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

    //get your content in Object (parent class of all )
    Object objContent = yourListView.getAdapter().getItem(position);
    String valContent = objContent .toString();
    Toast.makeText(YourMainActivity.this,"Content= "+valContent, Toast.LENGTH_LONG).show();
  }
});
mfaisalhyder
  • 2,250
  • 3
  • 28
  • 38
  • I understand, good point but how can I call the list view? because the problem is the listView that is null. So how can i call the line you suggest if I do not instantiate the list view? – trocchietto Jul 30 '16 at 20:32
  • @trocchietto The ListView like every other view in Android should be initialized in the onCreate method, this is the "standard" way: if the view is declared in the layout file (.xml) you have to retrieve it in code with findViewById(..) inside onCreate method (or after method setContentView has been called). See my answer for the code – Lorenzo Barbagli Jul 30 '16 at 21:00
  • Lorenzo, I replied you, I can upvote you for the interest – trocchietto Jul 30 '16 at 21:05
  • @trocchietto i don't get it, u said you are clicking listView items from another class? – mfaisalhyder Jul 30 '16 at 21:06
  • i followed the google tutorial https://developer.android.com/training/implementing-navigation/nav-drawer.html where there is not onItemClickListener as anonymous class as in your example.But it creates a new class that extends the interface OnItemClickListener. As consequence the listview is not anymore in the range that can be called. But you were right and I am thinking to accept your reply, because I got a NPE as you said because I instantiated twice ListView. Just i do not find nice to be downvoted, because is not a duplicate of "how to fix NPE" as has been indicated in my post – trocchietto Jul 30 '16 at 21:21
  • There u go , upVote :) i myself sometimes don't understand people's behaviour..! – mfaisalhyder Jul 30 '16 at 21:35
  • Even if you're following tutorial it should work, from mainaActivity they passed new Object of class that implements ListViee.OnItemClickListener. but for simplicity sake. Do handle clicking events from same activity. – mfaisalhyder Jul 30 '16 at 21:38
  • Yes. is working from the main Activity, I just put the anonymous class back. after all anononymous classes are not bad considering the future always more reactiveRX. I am going to accept your reply, I learned a lot. – trocchietto Jul 30 '16 at 21:59
1

You have to find the ListView in the layout file outside of the onItemClickListener. You can assign the ListView reference to an instance field and then use it inside the click event handler.

This is a pseudocode (can't test it right now):

private ListView list;    

public onCreate(..) {
    setContentView(..);

    list = findViewById(R.id.left_drawer);
    list.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
            //here you have a reference of your ListView, and the position of the clicked item.
            list.getAdapter().getItem(position); //this is the clicked item
        }
    });
}
Lorenzo Barbagli
  • 1,241
  • 2
  • 16
  • 34
  • No Lorenzo does not work because the ListView was out of range, as I implemented onItemClickListener in another class as the google tutorial suggests. so I did not have access to listview anymore. – trocchietto Jul 30 '16 at 21:02