20

So I'm trying to set up a setOnClickListener for my ListView but it's causing a crash in my program for some reason when I try... I'm quite new to programming so when it comes to troubleshooting I can't really do anything sadly :( my code is below so any ideas on what could be wrong would be extremely helpful:

public class HomePageActivity extends Activity {
    //ListView that holds the items
    ListView lstTest;
    
    //Array Adapter that holds the ArrayList and displays the items on the ListView
    AlertsAdapter arrayAdapter;
    
    //List that hosts the items
    ArrayList<Alerts> alrts = null;
    
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.homepage);
        
        //Initialize the ListView
        lstTest = (ListView)findViewById(R.id.lstText);
        
        //Initialize the ArrayList
        alrts = new ArrayList&lt;Alerts&gt;();
        
        //Initialize the array adapter
        arrayAdapter = new AlertsAdapter(HomePageActivity.this, R.layout.listitems,alrts);
        
        //Set the above adapter as the adapter of choice for our list
        lstTest.setAdapter(arrayAdapter);
        
        lstTest.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(
                HomePageActivity.this,
                PromotionActivity.class
                );
                startActivity(intent);
            }
        });
        //... ... ...
    }
} 

Any thoughts? I'm stuck :(

Edit: Posting error log file from ddms:

08-04 04:14:26.351: ERROR/AndroidRuntime(8882): FATAL EXCEPTION: main
08-04 04:14:26.351: ERROR/AndroidRuntime(8882): java.lang.RuntimeException: Unable to start activity ComponentInfo{hypenyte.bdutcher.promopost/hypenyte.bdutcher.promopost.HomePageActivity}: java.lang.RuntimeException: Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.os.Looper.loop(Looper.java:123)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.app.ActivityThread.main(ActivityThread.java:4627)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at java.lang.reflect.Method.invokeNative(Native Method)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at java.lang.reflect.Method.invoke(Method.java:521)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at dalvik.system.NativeStart.main(Native Method)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882): Caused by: java.lang.RuntimeException: Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.widget.AdapterView.setOnClickListener(AdapterView.java:750)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at hypenyte.bdutcher.promopost.HomePageActivity.onCreate(HomePageActivity.java:58)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
08-04 04:14:26.351: ERROR/AndroidRuntime(8882):     ... 11 more

I saw that it said I probably want setOnItemClickListener which is originally what I had coded it as, but that it wouldn't work since eclipse told me my code was wrong with it.

moffeltje
  • 4,521
  • 4
  • 33
  • 57
dootcher
  • 3,059
  • 4
  • 22
  • 18
  • 1
    please check/post the logfile. In Eclipse it's in DDMS perspective / logcat tab. Or via command line in the Android SDK tools: adb shell logcat. btw: your question isn't formatted properly, code parts are not displayed as code, makes reading easier. Thnks. – Mathias Conradt Aug 04 '10 at 03:47
  • added my ddms log as requested. let me know what you think. thanks – dootcher Aug 04 '10 at 04:21
  • The log statement is correct; you want to set `onItemClickListener`. Please share the error Eclipse reports when you try. – Justin Aug 04 '10 at 04:24
  • with it changed to lstTest.setOnItemClickListener(new View.OnClickListener()> The method setOnItemClickListener(AdapterView.OnItemClickListener) in the type AdapterView is not applicable for the arguments (new View.OnClickListener(){}) – dootcher Aug 04 '10 at 04:30
  • and with it changed to lstTest.setOnItemClickListener(new View.OnItemClickListener() { it gives the View.OnItemClickListener cannot be resolved to a type – dootcher Aug 04 '10 at 04:33
  • Watch me use OnItemClickListener because it tells me to do so in the debug screen then receive a message telling me I cannot use it. :) "SetOnItemClickListener cannot be used with a spinner" – Léon Pelletier Jan 30 '14 at 22:42

5 Answers5

51

You need to use setOnItemClickListener()

and then new android.widget.AdapterView.OnItemClickListener()

not new View.OnItemClickListener()

Mathias Conradt
  • 28,420
  • 21
  • 138
  • 192
  • i literally JUST troubleshot (is that actually troubleshoot in past tense? lol) that exact solution as you posted this.. thank you much mathias you definitely got me on the right path – dootcher Aug 04 '10 at 04:57
  • 2
    I know that the above code works, but I would like to know why I would have to do it this way. Can someone explain? – Anirudh Jun 09 '11 at 09:57
  • 1
    @Anirudh: Because the Android API is designed that way if it's assigned to an adapterView, it will throw an exception. Clicking on a listView would mean a click on the entire view, which is usually not very useful anyway, since you mostly want to know in your app which exact child view item (list item) has been clicked, not that the entire listview has been clicked. – Mathias Conradt Jun 10 '11 at 02:09
  • This problem has been driving me crazy. Excellent solution. Thanks! – Demig0d Feb 03 '12 at 04:48
  • I need to know which of two Spinners, with the same adapter, is open. What event can I use to detect when the Spinner is dropped down? No, Android, I probably DON'T want to use `setOnItemClickListener` instead. – Phlip Oct 28 '20 at 23:36
5

Instead of using setOnClickListener, try to use setOnItemClickListener

Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96
Jayson Tamayo
  • 2,741
  • 3
  • 49
  • 76
1

If using Butterknife, check that you don't have OnClick annotation for an AdapterView descentant (Spinner, ListView, etc.)

@OnClick(R.id.spinner_id)

Calling ButterKnife.inject(this, view); will throw the exception

Caused by: java.lang.RuntimeException: Don't call setOnClickListener for an AdapterView. You probably want setOnItemClickListener instead

Maragues
  • 37,861
  • 14
  • 95
  • 96
1

In my case I try to add onClickListener for spinner and I've got the same problem. I've crated workaround with touch listener. Sometimes we need it for hideKeyBoard or send some analyticEvent:

someSpinner.setOnTouchListener { _, event ->  onTouchSomeSpinner(event)}

fun onTouchSomeSpinner(event: MotionEvent): Boolean {
        if(event.action == MotionEvent.ACTION_UP) {
            view.hideKeyBoard()
            view.analyticsEvent()
            ...
        }
        return false
}
Djek-Grif
  • 1,391
  • 18
  • 18
0

firstly set the value inside your main activity where your using your listview:

new android.widget.AdapterView.OnItemClickListener()

in place of adapter of your listview:

  new AdapterView.OnItemClickListener() 

So finally it looks like:

this.listView.setItemsCanFocus(false);
this.listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(android.widget.AdapterView<?> parent, View view, int position, long id) {

 }

when you are using any custom view to populate the data inside listview.

Then in your main Activity file.xml in the parent layout{ inside which listview is there} set this option:

    android:descendantFocusability="blocksDescendants"

and if you are using any buttons/textview inside listview, set this property on that textview/button:

    android:focusable="false"
    android:focusableInTouchMode="false"

For scroll option in your listview just add this line inside activity:

 listView=(ListView)findViewById(R.id.container);
 listView.setNestedScrollingEnabled(true);

As per i understood i am giving answer, and i hope it will help, if anyone found some corrections or helpful, they are welcome.

amit pandya
  • 1,384
  • 13
  • 22