java.lang.NullPointerException和ActivityThread.handleLaunchActivity

时间:2014-03-25 09:25:10

标签: java android multithreading android-intent null

03-25 11:00:41.920: E/AndroidRuntime(21451): FATAL EXCEPTION: main
03-25 11:00:41.920: E/AndroidRuntime(21451): Process: com.example.bluetooth, PID: 21451
03-25 11:00:41.920: E/AndroidRuntime(21451): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bluetooth/com.example.bluetooth.MainActivity}: java.lang.NullPointerException
03-25 11:00:41.920: E/AndroidRuntime(21451):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at android.app.ActivityThread.access$800(ActivityThread.java:135)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at android.os.Handler.dispatchMessage(Handler.java:102)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at android.os.Looper.loop(Looper.java:136)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at android.app.ActivityThread.main(ActivityThread.java:5017)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at java.lang.reflect.Method.invokeNative(Native Method)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at java.lang.reflect.Method.invoke(Method.java:515)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at dalvik.system.NativeStart.main(Native Method)
03-25 11:00:41.920: E/AndroidRuntime(21451): Caused by: java.lang.NullPointerException
03-25 11:00:41.920: E/AndroidRuntime(21451):    at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:330)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at android.widget.ListView.setAdapter(ListView.java:480)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at com.example.bluetooth.MainActivity.setupListView(MainActivity.java:208)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at com.example.bluetooth.MainActivity.onCreate(MainActivity.java:62)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at android.app.Activity.performCreate(Activity.java:5231)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-25 11:00:41.920: E/AndroidRuntime(21451):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)

主要Activity.java

public class MainActivity extends Activity {

    private static final int Sabit = 1;
    private static int DISCOVERY_REQUEST = 2;
    private Handler handler = new Handler();
    private ArrayList<BluetoothDevice> foundDevices;
    private ArrayAdapter<BluetoothDevice> aa;
    private ListView list;

    private BluetoothAdapter bluetooth;
    private BluetoothSocket socket;
    private UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");

    ListView listDevicesFound;

    Button btnScanDevice;
    TextView stateBluetooth;
    BluetoothAdapter bluetoothAdapter;
    ArrayAdapter<String> btArrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        configureBluetooth();
        setupListView();
        setupSearchButton();
        setupListenButton();

        btnScanDevice = (Button) findViewById(R.id.scandevice);
        stateBluetooth = (TextView) findViewById(R.id.bluetoothstate);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        listDevicesFound = (ListView) findViewById(R.id.devicesfound);
        btArrayAdapter = new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_list_item_1);
        listDevicesFound.setAdapter(btArrayAdapter);
        CheckBlueToothState();
        btnScanDevice.setOnClickListener(btnScanDeviceOnClickListener);
        registerReceiver(ActionFoundReceiver, new IntentFilter(
                BluetoothDevice.ACTION_FOUND));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(ActionFoundReceiver);
    }
    private void CheckBlueToothState() {
        if (bluetoothAdapter == null) {
            stateBluetooth.setText("Bluetooth Desteklemiyor !");
        } 
        else {
            if (bluetoothAdapter.isEnabled()) {
                if (bluetoothAdapter.isDiscovering()) {
                    stateBluetooth
                            .setText("Bluetooth cihazları erişmeye çalışıyor.");
                } else {
                    stateBluetooth
                            .setText("                      Bluetooth Aktifleştirildi !.");
                    btnScanDevice.setEnabled(true);
                }
            } else {
                stateBluetooth.setText("Bluetooth AKTİF DEĞİL !");
                Intent enableBtIntent = new Intent(
                        BluetoothAdapter.ACTION_REQUEST_ENABLE);// Bluetooth açma isteği gönderir
                startActivityForResult(enableBtIntent, Sabit);// Kabul ederseniz açar
            }
        }
    }

    private Button.OnClickListener btnScanDeviceOnClickListener// butona tıklandığında
    = new Button.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            btArrayAdapter.clear();// Eski bluetooth bilgileri silinir
            bluetoothAdapter.startDiscovery();// bluetooth aracı taramaya başlar
            ((ProgressBar) findViewById(R.id.progressBar1)).setVisibility(View.VISIBLE);
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == Sabit) { // bluetooth cihazlarini aramak icin
            CheckBlueToothState();
        }
        if (requestCode == DISCOVERY_REQUEST) {
            boolean isDiscoverable = resultCode > 0;
            if (isDiscoverable) {
                String name = "bluetoothserver";
                try {
                    final BluetoothServerSocket btserver = bluetooth
                            .listenUsingRfcommWithServiceRecord(name, uuid);

                    AsyncTask<Integer, Void, BluetoothSocket> acceptThread = new AsyncTask<Integer, Void, BluetoothSocket>() {

                        @Override
                        protected BluetoothSocket doInBackground(
                                Integer... params) {
                            try {
                                socket = btserver.accept(params[0] * 1000);
                                return socket;
                            } catch (IOException e) {
                                Log.d("BLUETOOTH", e.getMessage());
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(BluetoothSocket result) {
                            if (result != null)
                                switchUI();

                        }
                    };
                    acceptThread.execute(resultCode);
                } catch (IOException e) {
                    Log.d("BLUETOOTH", e.getMessage());
                }
            }
        }
    }

    private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            runOnUiThread(new Runnable() {
                public void run() {
                    ((ProgressBar) findViewById(R.id.progressBar1)).setVisibility(View.GONE);
                }
            });
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                float rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,
                        Short.MAX_VALUE);// rssi değerini almak için oluşturulan intent ancak Short.MIN_VALUE olarak da değiştirilebilir
                float d = (float) ((0.4425 * rssi * rssi + 10.2174 * rssi + 78.6547) * 0.095);// projede kullanılan formül burada uygulandı,bu cihaz için doğru sonuç vermiyor
                String result = String.format("%.2f", d); // format ile ilgili yüzdeli yazım
                btArrayAdapter.add("Cihaz ismi: " + device.getName()
                        + "\nKonumu: " + device.getAddress() + "\n" + rssi
                        + " dbm" + "\n+15 cm veya -15 cm " + "uzaklık: "
                        + result + " cm");
                btArrayAdapter.notifyDataSetChanged();
            Toast.makeText(getApplicationContext(), "Uzaklık hesaplandi", Toast.LENGTH_SHORT).show();

            }
        }
    };
    private void configureBluetooth() {
        bluetooth = BluetoothAdapter.getDefaultAdapter();
    }

    private void setupListenButton() {
        Button listenButton = (Button) findViewById(R.id.button_listen);
        listenButton.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                Intent disc = new Intent(
                        BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                startActivityForResult(disc, DISCOVERY_REQUEST);
            }
        });
    }

    private void setupListView() {
        aa = new ArrayAdapter<BluetoothDevice>(this,
                android.R.layout.simple_list_item_1, foundDevices);
        list = (ListView) findViewById(R.id.list_discovered);
        list.setAdapter(aa);

        list.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View view, int index,
                    long arg3) {
                AsyncTask<Integer, Void, Void> connectTask = new AsyncTask<Integer, Void, Void>() {
                    @Override
                    protected Void doInBackground(Integer... params) {
                        try {
                            BluetoothDevice device = foundDevices
                                    .get(params[0]);
                            socket = device
                                    .createRfcommSocketToServiceRecord(uuid);
                            socket.connect();
                        } catch (IOException e) {
                            Log.d("BLUETOOTH_CLIENT", e.getMessage());
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        switchUI();
                    }
                };
                connectTask.execute(index);
            }
        });
    }

    private void setupSearchButton() {
        Button searchButton = (Button) findViewById(R.id.button_search);

        searchButton.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                registerReceiver(discoveryResult, new IntentFilter(
                        BluetoothDevice.ACTION_FOUND));

                if (!bluetooth.isDiscovering()) {
                    foundDevices.clear();
                    bluetooth.startDiscovery();
                }
            }
        });
    }

    private void switchUI() {
        final TextView messageText = (TextView) findViewById(R.id.text_messages);
        final EditText textEntry = (EditText) findViewById(R.id.text_message);

        messageText.setVisibility(View.VISIBLE);
        list.setVisibility(View.GONE);
        textEntry.setEnabled(true);

        textEntry.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if ((keyEvent.getAction() == KeyEvent.ACTION_DOWN)
                        && (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) {
                    sendMessage(socket, textEntry.getText().toString());
                    textEntry.setText("");
                    return true;
                }
                return false;
            }
        });
        BluetoothSocketListener bsl = new BluetoothSocketListener(socket,
                handler, messageText);
        Thread messageListener = new Thread(bsl);
        messageListener.start();
    }

    private void sendMessage(BluetoothSocket socket, String msg) {
        OutputStream outStream;
        try {
            outStream = socket.getOutputStream();
            byte[] byteString = (msg + " ").getBytes();
            byteString[byteString.length - 1] = 0;
            outStream.write(byteString);
        } catch (IOException e) {
            Log.d("BLUETOOTH_COMMS", e.getMessage());
        }
    }

    BroadcastReceiver discoveryResult = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            BluetoothDevice remoteDevice;
            remoteDevice = intent
                    .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (bluetooth.getBondedDevices().contains(remoteDevice)) {
                foundDevices.add(remoteDevice);
                aa.notifyDataSetChanged();
            }
        }
    };

    private class MessagePoster implements Runnable {
        private TextView textView;
        private String message;

        public MessagePoster(TextView textView, String message) {
            this.textView = textView;
            this.message = message;
        }

        public void run() {
            textView.setText(message);
        }
    }

    private class BluetoothSocketListener implements Runnable {

        private BluetoothSocket socket;
        private TextView textView;
        private Handler handler;

        public BluetoothSocketListener(BluetoothSocket socket, Handler handler,
                TextView textView) {
            this.socket = socket;
            this.textView = textView;
            this.handler = handler;
        }

        public void run() {
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            try {
                InputStream instream = socket.getInputStream();
                int bytesRead = -1;
                String message = "";
                while (true) {
                    message = "";
                    bytesRead = instream.read(buffer);
                    if (bytesRead != -1) {
                        while ((bytesRead == bufferSize)
                                && (buffer[bufferSize - 1] != 0)) {
                            message = message
                                    + new String(buffer, 0, bytesRead);
                            bytesRead = instream.read(buffer);
                        }
                        message = message
                                + new String(buffer, 0, bytesRead - 1);

                        handler.post(new MessagePoster(textView, message));
                        socket.getInputStream();
                    }
                }
            } catch (IOException e) {
                Log.d("BLUETOOTH_COMMS", e.getMessage());
            }
        }
    }


}

2 个答案:

答案 0 :(得分:0)

您的代码需要:

1。初始化列表:private ArrayList<BluetoothDevice> foundDevices;未初始化。

2。使用setupListView();致电foundDevices非空。

应该在foundDevices列表中填充至少一个对象后进行调用,或者在将foundDevices!=null传递给/ adapter之前检查{{1}}。

两者都没有在您的代码中发生,因此您获得了NPE。

答案 1 :(得分:0)

btArrayAdapter = new ArrayAdapter(MainActivity.this,                 android.R.layout.simple_list_item_1);

在oncreate()的此语句中,您需要将其更改为

btArrayAdapter = new ArrayAdapter(MainActivity.this,                 android.R.layout.simple_list_item_1,数组列表);

其中arraylist是ArrayList的对象或String的简单数组。 arraylist将包含需要在listview中显示的文本。