Android listView.setOnItemClickListener(this)在运行时崩溃

时间:2016-05-29 01:48:56

标签: java android listview android-studio crash

我试图使用BT连接进行Tic-tac-toe游戏。 但是,当我添加应该显示配对设备的代码时,当我尝试运行应用程序时它会崩溃。 看起来像" listView.setOnItemClickListener()"的问题。 游戏部分没有问题。

main java:

public class XO extends Activity implements OnItemClickListener {

Button b0,b1,b2,b3,b4,b5,b6,b7,b8,bConnect,bDisconnect,bExit,bClear,bWin,bLoss;
Button[] bArray;
TextView tAlert;


int win = 0,
    loss = 0,
    cout=0,
    msg=0;
boolean mode = false,
        wait = false;

ArrayAdapter<String> listAdapter;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
IntentFilter filter;
BroadcastReceiver receiver;
String tag = "debugging";
Handler mHandler = new Handler(){
    @Override
    public void handleMessage (Message msg)
    {
        Log.i(tag, "in handler");
        super.handleMessage(msg);
        switch(msg.what){
            case SUCCESS_CONNECT:
                ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
                Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_SHORT).show();
                String s = "successfully connected";
                connectedThread.write(s.getBytes());
                Log.i(tag, "connected");
                break;
            case MESSAGE_READ:
                byte[] readBuf = (byte[])msg.obj;
                String string = new String(readBuf);
                Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show();
                break;
        }
    }

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_xo);

    tAlert = (TextView) findViewById(R.id.tAlert);
    b0 = (Button) findViewById(R.id.b0);
    b1 = (Button) findViewById(R.id.b1);
    b2 = (Button) findViewById(R.id.b2);
    b3 = (Button) findViewById(R.id.b3);
    b4 = (Button) findViewById(R.id.b4);
    b5 = (Button) findViewById(R.id.b5);
    b6 = (Button) findViewById(R.id.b6);
    b7 = (Button) findViewById(R.id.b7);
    b8 = (Button) findViewById(R.id.b8);
    bWin = (Button) findViewById(R.id.bWin);
    bLoss = (Button) findViewById(R.id.bLoss);
    bConnect = (Button) findViewById(R.id.bConnect);
    bDisconnect = (Button) findViewById(R.id.bDisconnect);
    bExit = (Button) findViewById(R.id.bExit);
    bClear = (Button) findViewById(R.id.bClear);

    bWin.setText(String.valueOf(win));
    bLoss.setText(String.valueOf(loss));
    tAlert.setText("By nawiązać połączenie urządzenia muszą być sparowane");

    bArray = new Button[]{b0,b1,b2,b3,b4,b5,b6,b7,b8};

    bConnect.setOnClickListener(new bConnectListener());
    bDisconnect.setOnClickListener(new bDisconnectListener());
    bClear.setOnClickListener(new bClearListener());
    bExit.setOnClickListener(new bExitListener());
    for(Button b : bArray){
        b.setOnClickListener(new bListener());
    }

    init();

    if(btAdapter==null){
        Toast.makeText(getApplicationContext(), "No bluetooth detected", Toast.LENGTH_SHORT).show();
        finish();
    }else{
        if(!btAdapter.isEnabled()){
            turnOnBT();
        }
        getPairedDevices();
        startDiscovery();
    }



}

private void startDiscovery() {
    btAdapter.cancelDiscovery();
    btAdapter.startDiscovery();
}


private void turnOnBT() {
    Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, 1);
}

private void getPairedDevices() {
    devicesArray=btAdapter.getBondedDevices();
    if(devicesArray.size()>0){
        for(BluetoothDevice device:devicesArray){
            pairedDevices.add(device.getName());

        }
    }
}

public void init() {

    listView = (ListView) findViewById(R.id.listView);
    listView.setOnItemClickListener(this);

    listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, 0);
    listView.setAdapter(listAdapter);
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    pairedDevices = new ArrayList<String>();
    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    devices = new ArrayList<BluetoothDevice>();
    receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                devices.add(device);
                String s = "";

                for(int a=0; a<pairedDevices.size(); a++){
                    if(device.getName().equals(pairedDevices.get(a))){
                        s = "(Paired)";
                        break;
                    }
                }

                listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
            }

            else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){

            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){

            }
            else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                if(btAdapter.getState() == btAdapter.STATE_OFF){
                    turnOnBT();
                }
            }
        }
    };
    registerReceiver(receiver, filter);
    IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(receiver, filter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
}



@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode==RESULT_CANCELED){
        Toast.makeText(getApplicationContext(), "Bluetooth must be enabled to continue", Toast.LENGTH_SHORT).show();
        finish();
    }
}

public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
    if(btAdapter.isDiscovering()){
        btAdapter.cancelDiscovery();
    }
    if (listAdapter.getItem(arg2).contains("Paired")){
        BluetoothDevice selectedDevice = devices.get(arg2);
        ConnectThread connect = new ConnectThread(selectedDevice);
        connect.start();
        Log.i(tag, "in click listener");
    }else{
        Toast.makeText(getApplicationContext(), "device is not paired", Toast.LENGTH_SHORT).show();
    }

}

private class ConnectThread extends Thread{
    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device){
        BluetoothSocket tmp = null;
        mmDevice = device;
        Log.i(tag, "construct");

        try{
            tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID);

        } catch (IOException e){
            Log.i(tag, "get socket failed");
        }
        mmSocket = tmp;
    }

    public void run(){
        btAdapter.cancelDiscovery();
        Log.i(tag,"connect-run");
        try {


            mmSocket.connect();
            Log.i(tag, "connect - succeeded");
        } catch (IOException connectException) {    Log.i(tag, "connect failed");

            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }
        mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
    }

    public void cancel(){
        try {
                mmSocket.close();
            } catch (IOException e) { }
        }
    }

    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer;
            int bytes;


            while (true) {
                try {

                    buffer = new byte[1024];
                    bytes = mmInStream.read(buffer);

                    mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();

                } catch (IOException e) {
                    break;
                }
            }
        }

        public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) {
            }
        }

        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
            }
        }

    }

devicelist.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.pwsz.rc.kolkokrzyzyk.XO"
android:background="#ffffff">
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:text="Paired Devices"
    android:id="@+id/tvPD"
    />
<ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/tvPD"
    >
</ListView>

logcat的:

05-29 03:28:08.315 4639-4639/com.pwsz.rc.kolkokrzyzyk E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.pwsz.rc.kolkokrzyzyk, PID: 4639 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pwsz.rc.kolkokrzyzyk/com.pwsz.rc.kolkokrzyzyk.XO}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2202)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5103)
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)
Caused by: java.lang.NullPointerException
at com.pwsz.rc.kolkokrzyzyk.XO.init(XO.java:162)
at com.pwsz.rc.kolkokrzyzyk.XO.onCreate(XO.java:121)
at android.app.Activity.performCreate(Activity.java:5275)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2166)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2252) 
at android.app.ActivityThread.access$800(ActivityThread.java:139) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5103) 
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)

3 个答案:

答案 0 :(得分:0)

好吧,来自异常消息。 我们可以抓住信息

Caused by: java.lang.NullPointerException
     at com.pwsz.rc.kolkokrzyzyk.XO.init(XO.java:162)
     at com.pwsz.rc.kolkokrzyzyk.XO.onCreate(XO.java:121)

是,函数Init()和第162行的错误。 pleace发布关于Main.java的完整代码(包括improt````)。 通过这种方式,我可以获得有关错误的moew信息。

答案 1 :(得分:0)

listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);

似乎找不到id为“listView”的视图,因此返回null,将内容视图布局设置为“R.layout.activity_xo”,但上面显示的xml文件名为devicelist。 XML。你应该检查一下。

答案 2 :(得分:0)

包含'listview'的xml文件的名称是'devicelist.xml'。

但你用过

    setContentView(R.layout.activity_xo);

'activity_xo'布局中可能没有ListView。