ListAdapter 不工作

ListAdapter does not work

我有一个 mainActivity,它有一个名为 monitoring 的按钮。当我按下按钮时,它应该会显示附近的信标。当我按下按钮时,出现一个错误,说我的应用程序停止工作。这是按钮的代码 activity:

public class MonitoringBeacons extends AppCompatActivity {

    private ProximityManagerContract proximityManager;

    ListAdapter beaconsAdapter;
    ListView listView;
    List<String> beaconsList = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monitoring_beacons);
        KontaktSDK.initialize("kasjdhioasjkdoasdjo");

        proximityManager = new ProximityManager(this);
        proximityManager.setEddystoneListener(createEddystoneListener());

        setAdapter();


        listView.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                        String beacon = String.valueOf(adapterView.getItemAtPosition(position));
                        Toast.makeText(MonitoringBeacons.this, beacon, Toast.LENGTH_SHORT).show();
                    }
                }
        );
    }

    protected void setAdapter() {
        if(beaconsList.isEmpty()) {
            Toast.makeText(MonitoringBeacons.this, "No beacons found", Toast.LENGTH_SHORT).show();
            return ;
        }
        beaconsAdapter = new CustomListAdapter(this, beaconsList);
        listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(beaconsAdapter);
    }

    @Override
    protected void onStart() {
        super.onStart();
        startScanning();
    }

    @Override
    protected void onStop() {
        proximityManager.stopScanning();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        proximityManager.disconnect();
        proximityManager = null;
        super.onDestroy();
    }

    private void startScanning() {
        proximityManager.connect(new OnServiceReadyListener() {
            @Override
            public void onServiceReady() {
                proximityManager.startScanning();
            }
        });
    }

    private EddystoneListener createEddystoneListener() {
        return new SimpleEddystoneListener() {
            @Override
            public void onEddystoneDiscovered(IEddystoneDevice eddystone, IEddystoneNamespace namespace) {
                beaconsList.add(eddystone.getUniqueId());
                setAdapter();
            }

            @Override
            public void onEddystoneLost(IEddystoneDevice eddystone, IEddystoneNamespace namespace) {
                beaconsList.remove(eddystone.getUniqueId());
                setAdapter();
            }
        };
    }

}

和CustomListAdapter的代码:

public class CustomListAdapter extends BaseAdapter {

    private List<String> beaconsList;
    private Activity activity;
    private LayoutInflater inflater;

    public CustomListAdapter(Activity activity, List<String> beaconsList) {
        this.activity = activity;
        this.beaconsList = beaconsList;
    }

    @Override
    public int getCount() {
        return beaconsList.size();
    }

    @Override
    public Object getItem(int location) {
        return beaconsList.get(location);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (convertView == null)
            convertView = inflater.inflate(R.layout.custom_row, null);

        String singleBeaconItem = String.valueOf(getItem(position));
        TextView beaconText = (TextView) convertView.findViewById(R.id.BeaconText);
        ImageView beaconImage = (ImageView) convertView.findViewById(R.id.BeaconImage);

        beaconText.setText(singleBeaconItem);
        beaconImage.setImageResource(R.drawable.tough_beacon_1);

        return convertView;
    }
}

理想情况下,当我按下按钮时,附近的信标应显示为列表,当发现或丢失信标时,列表应自动更新。

已编辑

LogCat

中的堆栈跟踪

------------崩溃开始 08-06 17:02:15.276 2559-2559/com.example.panagiotis.beaconsproject E/AndroidRuntime:致命异常:main 进程:com.example.panagiotis.beaconsproject,PID:2559 java.lang.RuntimeException: 无法启动 activity ComponentInfo{com.example.panagiotis.beaconsproject/com.example.panagiotis.beaconsproject.MonitoringBeacons}: java.lang.NullPointerException: 尝试调用虚拟方法 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' 在空对象引用上 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 在 android.app.ActivityThread.-wrap11(ActivityThread.java) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:148) 在 android.app.ActivityThread.main(ActivityThread.java:5417) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 原因:java.lang.NullPointerException:尝试在空对象引用上调用虚方法 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' 在 com.example.panagiotis.beaconsproject.MonitoringBeacons.onCreate(MonitoringBeacons.java:44) 在 android.app.Activity.performCreate(Activity.java:6237) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 在 android.app.ActivityThread.-wrap11(ActivityThread.java) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:148) 在 android.app.ActivityThread.main(ActivityThread.java:5417) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 08-0617:02:18.087 2559-2559/com.example.panagiotis.beaconsprojectI/Process:发送信号。 PID:2559 SIG:9 08-06 17:02:22.298 3433-3433/com.example.panagiotis.beaconsproject W/System: ClassLoader 引用未知路径: /data/app/com.example.panagiotis.beaconsproject-1/lib/x86 08-06 17:02:22.455 3433-3433/com.example.panagiotis.beaconsproject W/System: ClassLoader 引用未知路径: /data/app/com.example.panagiotis.beaconsproject-1/lib/x86 08-06 17:02:22.604 3433-3433/com.example.panagiotis.beaconsproject W/art: 在Android 4.1之前,方法android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter , android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) 会错误地覆盖 android.graphics.drawable.Drawable 中的 package-private 方法 08-06 17:02:22.715 3433-3460/com.example.panagiotis.beaconsproject D/OpenGLRenderer: 使用 EGL_SWAP_BEHAVIOR_PRESERVED: true
[ 08-​​06 17:02:22.718 3433: 3433 D/ ] HostConnection::get() 新主机连接建立 0xaa9a71c0,tid 3433
[ 08-​​06 17:02:22.754 3433: 3460 D/ ] HostConnection::get() 新主机连接建立 0xaa9a6920,tid 3460 08-06 17:02:22.768 3433-3460/com.example.panagiotis.beaconsproject I/OpenGLRenderer:初始化 EGL,版本 1.4 08-06 17:02:24.070 3433-3460/com.example.panagiotis.beaconsproject E/Surface:getSlotFromBufferLocked:未知缓冲区:0xaa9b17f0 08-06 17:02:26.685 3433-3433/com.example.panagiotis.beaconsproject W/ViewRootImpl:由于没有 window 焦点而取消事件:MotionEvent { action=ACTION_CANCEL, actionButton=0 , id[0]=0, x[0]=397.5, y[0]=956.6797, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount =1, historySize=0, eventTime=70853, downTime=67680, deviceId=0, source=0x1002 } 08-06 17:02:26.685 3433-3433/com.example.panagiotis.beaconsproject W/ViewRootImpl:由于没有 window 焦点而取消事件:MotionEvent { action=ACTION_CANCEL, actionButton=0 , id[0]=0, x[0]=397.5, y[0]=956.6797, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount =1, historySize=0, eventTime=70853, downTime=67680, deviceId=0, source=0x1002 } 08-06 17:02:26.686 3433-3433/com.example.panagiotis.beaconsproject W/ViewRootImpl: 由于没有 window 焦点而取消事件:MotionEvent { action=ACTION_CANCEL, actionButton=0 , id[0]=0, x[0]=397.5, y[0]=956.6797, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount =1, historySize=0, eventTime=70853, downTime=67680, deviceId=0, source=0x1002 } 08-06 17:02:26.686 3433-3433/com.example.panagiotis.beaconsproject W/ViewRootImpl: 由于没有 window 焦点而取消事件:MotionEvent { action=ACTION_CANCEL, actionButton=0 , id[0]=0, x[0]=397.5, y[0]=956.6797, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount =1, historySize=0, eventTime=70853, downTime=67680, deviceId=0, source=0x1002 } 08-06 17:02:28.817 3433-3460/com.example.panagiotis.beaconsproject E/Surface:getSlotFromBufferLocked:未知缓冲区:0xaa9b17f0 08-06 17:02:29.373 3433-3460/com.example.panagiotis.beaconsproject E/Surface:getSlotFromBufferLocked:未知缓冲区:0xb40938f0 08-06 17:02:29.375 3433-3460/com.example.panagiotis.beaconsproject D/OpenGLRenderer:endAllStagingAnimators on 0xa1d53580 (RippleDrawable) with handle 0xa203f910 08-06 17:02:30.806 3433-3460/com.example.panagiotis.beaconsproject E/Surface:getSlotFromBufferLocked:未知缓冲区:0xb4094e60 08-06 17:02:32.811 3433-3460/com.example.panagiotis.beaconsproject E/Surface:getSlotFromBufferLocked:未知缓冲区:0xb40938f0 08-06 17:02:35.874 3433-3433/com.example.panagiotis.beaconsproject D/AndroidRuntime: 关闭虚拟机 08-06 17:02:35.874 3433-3433/com.example.panagiotis.beaconsproject E/AndroidRuntime:致命异常:main 进程:com.example.panagiotis.beaconsproject,PID:3433 java.lang.RuntimeException: 无法启动 activity ComponentInfo{com.example.panagiotis.beaconsproject/com.example.panagiotis.beaconsproject.MonitoringBeacons}: java.lang.NullPointerException: 尝试调用虚拟方法 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' 在空对象引用上 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 在 android.app.ActivityThread.-wrap11(ActivityThread.java) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:148) 在 android.app.ActivityThread.main(ActivityThread.java:5417) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 原因:java.lang.NullPointerException:尝试在空对象引用上调用虚方法 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' 在 com.example.panagiotis.beaconsproject.MonitoringBeacons.onCreate(MonitoringBeacons.java:44) 在 android.app.Activity.performCreate(Activity.java:6237) 在 android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 在 android.app.ActivityThread.-wrap11(ActivityThread.java) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 在 android.os.Handler.dispatchMessage(Handler.java:102) 在 android.os.Looper.loop(Looper.java:148) 在 android.app.ActivityThread.main(ActivityThread.java:5417) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 08-0617:02:39.204 3433-3433/com.example.panagiotis.beaconsprojectI/Process:发送信号。 PID:3433 SIG:9

有什么想法吗?

堆栈跟踪解释了正在发生的事情。

当这行代码执行时:

listView.setOnItemClickListener(...

listView还没有初始化,所以为空。这会导致 NullPointerException.

该变量在 setAdapter() 方法中初始化,但可能不是因为如果 beaconsList.isEmpty() 计算结果为真,该方法提前退出。

简单的解决方案是将初始化 listView 的代码移动到该方法的顶部。