Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将新项添加到ListView NullPointerException错误_Java_Android_Android Listview - Fatal编程技术网

Java 将新项添加到ListView NullPointerException错误

Java 将新项添加到ListView NullPointerException错误,java,android,android-listview,Java,Android,Android Listview,需要向ListView添加新项目的帮助,我正在尝试在android(蓝牙)中“查询配对设备”,在添加数据时遇到一些错误。。。这是我的密码: public class BlueLightProtoActivity extends ActionBarActivity { public static final String TAG = "BlueLightProto"; private BluetoothAdapter BTAdapter = null; private A

需要向ListView添加新项目的帮助,我正在尝试在android(蓝牙)中“查询配对设备”,在添加数据时遇到一些错误。。。这是我的密码:

public class BlueLightProtoActivity extends ActionBarActivity {

    public static final String TAG = "BlueLightProto";
    private BluetoothAdapter BTAdapter = null;
    private ArrayList adapter;
    private ListView listview;
    private ToggleButton togglebutton;
    private Button btnOn, btnOff;
    private OutputStream Out;
    private InputStream In;
    private static final int EnableBT = 1;
    private static final int DiscoverBT = 2;
    private static final int DiscDur = 300;
    private final UUID SecureUUID = UUID.fromString("3debad23-01b7-4c71-8710-ffb4bfbf0b36");
    private final UUID UnsecureUUID = UUID.fromString("fde1b057-5906-4d22-88c5-a0412a0c758e");

    private final BroadcastReceiver BcRcv = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice BTDvc = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                adapter.add(BTDvc.getName() + "\n" + BTDvc.getAddress());
            }
        }
    };

    /*
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(mReceiver, filter);
    */

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Log.e(TAG, "OnCreate1" );
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_blue_light_proto);

        togglebutton = (ToggleButton)findViewById(R.id.toggleButton);
        listview = (ListView)findViewById(R.id.listView);
        btnOn = (Button)findViewById(R.id.OnBtn);
        btnOff = (Button)findViewById(R.id.OffBtn);

        btnOn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "Button On Pressed!");
                sendData("1");
                toast("You have clicked ON");   //MUST FIND WAY TO GET FEEDBACK FROM ARDUINO!!!!
            }
        });

        btnOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "Button Off Pressed!");
                sendData("2");
                toast("You have clicked OFF");   //MUST FIND WAY TO GET FEEDBACK FROM ARDUINO!!!!
            }
        });

        BTAdapter = BluetoothAdapter.getDefaultAdapter();

        if(BTAdapter == null) {
            ExitNoBluetooth();
            return;
        }

        listview.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        Log.e(TAG, "onItemClick");
                        String itemValue = (String) listview.getItemAtPosition(position);
                        String MAC = itemValue.substring(itemValue.length() - 17);
                        BluetoothDevice BTDvc = BTAdapter.getRemoteDevice(MAC);

                        ConnectThread C = new ConnectThread(BTDvc);
                        C.start();
                    }
                }
        );

        Log.e(TAG, "OnCreate2" );
    }

    public void onToggleClicked(View view) {

        Log.e(TAG, "onToggleClicked1");
        //adapter.clear();
        ToggleButton togglebutton = (ToggleButton) view;
        Log.e(TAG, "onToggleClicked2");

        if(togglebutton.isChecked()) {
            if(!BTAdapter.isEnabled()) {
                Log.e(TAG, "onToggleClicked, request enable BT");
                Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBluetoothIntent, EnableBT);
            } else {
                toast("Your bluetooth is already enabled");
                addQuery();
                discoverDevices();
                makeDiscoverable();

                AcceptThread A = new AcceptThread();
                A.start();
            }
        } else {
            Log.e(TAG, "onToggleClicked, disabling BT");
            BTAdapter.disable();
            adapter.clear();
            toast("Your device is now disabled");
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent Data) {
        if(requestCode == EnableBT) {
            if(resultCode == Activity.RESULT_OK) {
                Log.e(TAG, "onActivityResult, BT enabled");
                toast("Bluetooth has been enabled \n Scanning for Remote Bluetooth devices...");
                addQuery();
                discoverDevices();
                makeDiscoverable();

                AcceptThread A = new AcceptThread();
                A.start();
            } else {
                Log.e(TAG, "onActivityResult, BT fail to enable");
                toast("Bluetooth failed to enable");
                togglebutton.setChecked(false);
            }
        } else if(requestCode == DiscoverBT) {
            if(resultCode == DiscDur) {
                Log.e(TAG, "onActivityResult, device discoverable");
                toast("Your device is now discoverable for " + DiscDur + "seconds");
            } else {
                toast("Fail to enable discoverability");
            }
        }
    }

    public void addQuery() {
        Log.e(TAG, "addQuery1");
        Set<BluetoothDevice> pairedDevices = BTAdapter.getBondedDevices();
        Log.e(TAG, "addQuery2" );
        if(pairedDevices.size() > 0) {
            Log.e(TAG, "addQuery3" );
            int n = 4;
            for(BluetoothDevice device : pairedDevices) {
                Log.e(TAG, "addQuery" + n + "......." + device.getName() + "......." );
                adapter.add(device.getName() + "\n" + device.getAddress());
                Log.e(TAG, "addQueryX" );
                n++;
            }
        }
    }

    public void discoverDevices(){
        Log.e(TAG, "discoverDevices");
        if (BTAdapter.startDiscovery()) {
            toast("Discovering other bluetooth devices");
        } else {
            toast("Discovery failed to start");
        }
    }

    public void makeDiscoverable() {
        Log.e(TAG, "makeDiscoverable");
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DiscDur);
        startActivityForResult(discoverableIntent, DiscoverBT);
    }

    //connect as server
    private class AcceptThread extends Thread {
        private final BluetoothServerSocket BTSvrSckt;

        public AcceptThread() {
            BluetoothServerSocket temp = null;
            try {
                temp = BTAdapter.listenUsingRfcommWithServiceRecord("BlueLightProto", SecureUUID);
            } catch (IOException e) {}
            BTSvrSckt = temp;
        }

        public void run() {
            BluetoothSocket BTSckt = null;
            while (true) {
                try {
                    BTSckt = BTSvrSckt.accept();
                } catch (IOException e) {
                    break;
                }
                if (BTSckt != null) {
                    //manageConnectedSocket(BTSckt); //Do work to manage the connection in a separate thread
                    try {
                        BTSvrSckt.close();
                    } catch (IOException e) {
                        break;
                    }
                }
            }
        }

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

    //Connect as Client
    private class ConnectThread extends Thread {
        private final BluetoothSocket BTSckt;

        public ConnectThread(BluetoothDevice device) {
            BluetoothSocket temp = null;

            try {
                temp = device.createRfcommSocketToServiceRecord(SecureUUID);
            } catch (IOException e) {}
            BTSckt = temp;
        }

        public void run() {
            BTAdapter.cancelDiscovery();

            try {
                BTSckt.connect();
            } catch (IOException connectException) {
                try {
                    BTSckt.close();
                } catch (IOException closeException) {}
                return;
            }
            //manageConnectedSocket(BTSckt)
        }

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

    private void sendData(String message) {
        byte[] msg = message.getBytes();
        Log.e(TAG, "...Sending data: " + message + "...");

        try {
            Out.write(msg);
        } catch (IOException e) {
            String stat = "An exception occurred during write: " + e.getMessage();
            toast(stat);
        }
    }

    public void toast(String text) {
        Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
    }

    public void ExitNoBluetooth() {
        Log.e(TAG, "ExitNoBluetooth");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Cannot use BlueLightProto without bluetooth")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setTitle("BlueLightProto")
                .setCancelable(false)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        finish();
                    }
                });
        builder.create().show();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "onStop");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "onRestart");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_blue_light_proto, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
公共类BluelightProActivity扩展了ActionBarActivity{
公共静态最终字符串标记=“BlueLightProto”;
私有蓝牙适配器BTAdapter=null;
专用ArrayList适配器;
私有列表视图列表视图;
私有切换按钮切换按钮;
专用按钮btnOn、btnOff;
私有输出流输出;
私有输入流;
私有静态最终int EnableBT=1;
私有静态最终int DiscoverBT=2;
专用静态最终int DiscDur=300;
专用最终UUID SecureUUID=UUID.fromString(“3debad23-01b7-4c71-8710-FFB4BF0B36”);
专用最终UUID UnsecureUUID=UUID.fromString(“fde1b057-5906-4d22-88c5-a0412a0c758e”);
专用最终广播接收器BcRcv=新广播接收器(){
公共void onReceive(上下文、意图){
String action=intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(ACTION)){
BluetoothDevice BTDvc=intent.getParcelableExtra(BluetoothDevice.EXTRA\u设备);
add(BTDvc.getName()+“\n”+BTDvc.getAddress());
}
}
};
/*
IntentFilter筛选器=新的IntentFilter(BluetoothDevice.ACTION\u已找到);
registerReceiver(mrReceiver,过滤器);
*/
@凌驾
创建时受保护的void(Bundle savedInstanceState){
Log.e(标记为“OnCreate1”);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u blue\u light\u proto);
togglebutton=(togglebutton)findViewById(R.id.togglebutton);
listview=(listview)findViewById(R.id.listview);
btnOn=(按钮)findviewbyd(R.id.OnBtn);
btnOff=(按钮)findViewById(R.id.OffBtn);
btnOn.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
Log.e(标记“按下按钮!”);
sendData(“1”);
toast(“您点击了”);//必须找到从ARDUINO获得反馈的方法!!!!
}
});
setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
Log.e(标记“按下按钮关闭!”);
sendData(“2”);
toast(“您点击了”);//必须找到从ARDUINO获得反馈的方法!!!!
}
});
BTAdapter=BluetoothAdapter.getDefaultAdapter();
if(BTAdapter==null){
ExitNoBluetooth();
返回;
}
listview.setOnItemClickListener(
新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
Log.e(标记为“onItemClick”);
String itemValue=(String)listview.getItemAtPosition(position);
字符串MAC=itemValue.substring(itemValue.length()-17);
蓝牙设备BTDvc=BTAdapter.getRemoteDevice(MAC);
ConnectThread C=新的ConnectThread(BTDvc);
C.开始();
}
}
);
Log.e(标记为“OnCreate2”);
}
已勾选公共空间(视图){
Log.e(标签“OnTogglecked1”);
//适配器。清除();
ToggleButton ToggleButton=(ToggleButton)视图;
Log.e(标签“OnTogglecked2”);
if(togglebutton.isChecked()){
如果(!BTAdapter.isEnabled()){
Log.e(标签“onToggleClicked,请求启用BT”);
意图启用BluetoothIntent=新意图(BluetoothAdapter.ACTION\u REQUEST\u ENABLE);
startActivityForResult(enableBluetoothIntent,EnableBT);
}否则{
toast(“您的蓝牙已启用”);
addQuery();
发现设备();
使可发现();
AcceptThread A=新的AcceptThread();
A.开始();
}
}否则{
Log.e(标签“onToggleClicked,禁用BT”);
BTAdapter.disable();
适配器。清除();
toast(“您的设备现在已禁用”);
}
}
ActivityResult上的公共void(int请求代码、int结果代码、意图数据){
if(requestCode==EnableBT){
if(resultCode==Activity.RESULT\u确定){
Log.e(标记“onActivityResult,BT-enabled”);
toast(“蓝牙已启用\n扫描远程蓝牙设备…”);
addQuery();
发现设备();
使可发现();
AcceptThread A=新的AcceptThread();
A.开始();
}否则{
Log.e(标记“onActivityResult,BT无法启用”);
toast(“蓝牙无法启用”);
togglebutton.setChecked(假);
}
}else if(requestCode==DiscoverBT){
if(resultCode==DiscDur){
Log.e(标签“onActivityResult,设备可发现”);
toast(“您的设备现在可被发现的时间为“+DiscDur+”秒”);
}否则{
toast(“未能实现可发现性”);
}
}
}
公共void addQuery(){
Log.e(标签“addQuery1”);
Set pairedDevices=BTAdapter.getBondedDevices();
Log.e(标签“addQuery2”);
如果(pairedDevices.size()>0){
Log.e(标签“addQuery3”);
int n=4;
用于(蓝牙设备:pairedDevices){
Log.e(标记“addQuery”+n+“…+device.getName()+”);
adapter.add(device.getName()+“\n”+device.getAddre
02-15 00:08:23.388  27882-27882/com.ebookfrenzy.bluelightproto I/BlueLightProto﹕ onStart
02-15 00:08:23.388  27882-27882/com.ebookfrenzy.bluelightproto I/BlueLightProto﹕ onResume
02-15 00:08:23.408  27882-27882/com.ebookfrenzy.bluelightproto I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:385>: EGL 1.4 QUALCOMM build:  ()
    OpenGL ES Shader Compiler Version: E031.24.00.02
    Build Date: 01/20/14 Mon
    Local Branch: PMH2-KK_3.5-RB1-AU61-554722-586267-set2
    Remote Branch:
    Local Patches:
    Reconstruct Branch:
02-15 00:08:23.438  27882-27882/com.ebookfrenzy.bluelightproto D/OpenGLRenderer﹕ Enabling debug mode 0
02-15 00:08:23.498  27882-27882/com.ebookfrenzy.bluelightproto I/ActivityManager﹕ Timeline: Activity_idle id: android.os.BinderProxy@428db578 time:75247271
02-15 00:08:25.238  27882-27882/com.ebookfrenzy.bluelightproto I/ViewRootImpl﹕ ViewRoot's Touch Event : Touch Down
02-15 00:08:25.318  27882-27882/com.ebookfrenzy.bluelightproto I/ViewRootImpl﹕ ViewRoot's Touch Event : Touch UP
02-15 00:08:25.328  27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ onToggleClicked1
02-15 00:08:25.328  27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ onToggleClicked2
02-15 00:08:25.328  27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ onToggleClicked, request enable BT
02-15 00:08:25.338  27882-27882/com.ebookfrenzy.bluelightproto I/BlueLightProto﹕ onPause
02-15 00:08:28.198  27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ onActivityResult, BT enabled
02-15 00:08:28.198  27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ addQuery1
02-15 00:08:28.208  27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ addQuery2
02-15 00:08:28.208  27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ addQuery3
02-15 00:08:28.208  27882-27882/com.ebookfrenzy.bluelightproto E/BlueLightProto﹕ addQuery4.......U8860.......
02-15 00:08:28.208  27882-27882/com.ebookfrenzy.bluelightproto D/AndroidRuntime﹕ Shutting down VM
02-15 00:08:28.208  27882-27882/com.ebookfrenzy.bluelightproto W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4188de48)
02-15 00:08:28.208  27882-27882/com.ebookfrenzy.bluelightproto E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.ebookfrenzy.bluelightproto, PID: 27882
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.ebookfrenzy.bluelightproto/com.ebookfrenzy.bluelightproto.BlueLightProtoActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.deliverResults(ActivityThread.java:3382)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:3425)
        at android.app.ActivityThread.access$1300(ActivityThread.java:139)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1248)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5105)
        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:792)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at com.ebookfrenzy.bluelightproto.BlueLightProtoActivity.addQuery(BlueLightProtoActivity.java:185)
        at com.ebookfrenzy.bluelightproto.BlueLightProtoActivity.onActivityResult(BlueLightProtoActivity.java:155)
        at android.app.Activity.dispatchActivityResult(Activity.java:5467)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:3378)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:3425)
        at android.app.ActivityThread.access$1300(ActivityThread.java:139)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1248)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5105)
        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:792)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
        at dalvik.system.NativeStart.main(Native Method)
adapter.add(device.getName() + "\n" + device.getAddress());
private ArrayList adapter = new ArrayList();