Error - with listview.performItemClick()

2019-07-31 01:56发布

问题:

I need to call a method listview.setOnItemClickListener () and when I found this site on the solution, then I try realize it , but get an error with it at any mActivePosition, I can not understand what the problem, is here logcat:

12-28 05:33:39.324  13066-13066/com.example.SmsService E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.SmsService, PID: 13066
java.lang.NullPointerException
        at com.example.SmsService.VideoView$3.getView(VideoView.java:140)
        at com.example.SmsService.VideoView.onCardboardTrigger(VideoView.java:217)
        at com.google.vrtoolkit.cardboard.CardboardActivity$SensorListener.onCardboardTrigger(CardboardActivity.java:84)
        at com.google.vrtoolkit.cardboard.sensors.MagnetSensor$TriggerDetector$1.run(MagnetSensor.java:141)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5118)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:606)
        at dalvik.system.NativeStart.main(Native Method)

there is problem string :

listview.getAdapter().getView(1, null, null),

And there is all my class, gist. Сan anyone tell me why this any typing errors and how it can fix that would work?

回答1:

Where are you trying to use performClick()?

If calling performItemClick on the onCreate() method, there would be NullPinterException,

Because the screen is not fully visible to the user.

Try calling this method in onWindowFocusChanged() like below:

listview.getAdapter().getView(1, null, null).performClick();

Instead of that you can also use same delay after:

Handler().postDelayed(new Runnable() 
{ 
    @Override public void run() {
                  listView.performItemClick(listView.getAdapter()
                      .getView(1, null, null), 0, listView.getAdapter().getItemId(1)); 
               } 
}, 2000);

Important note: This will work for single item that is item in position 1.

Also, If your question is all about using onWindowFocusChanged try checking this:

public void onWindowFocusChanged(boolean hasFocus) {

            super.onWindowFocusChanged(hasFocus);

          if(hasFocus) 
             Toast.makeText(context, text, duration).show();
    }