我按照教程在Android设备中实现蓝牙连接但是当它在类中实现onItemClickListener时会崩溃。
这是我在课堂上的代码:
package com.technowomen.isabel.izyboard202;
import android.bluetooth.*;
import android.content.*;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.util.UUID;
import java.util.ArrayList;
import java.util.Set;
import java.io.*;
import android.os.*;
import android.widget.AdapterView.*;
/**
* Created by Isabel on 25/07/2015.
*/
public class Conectivity extends ActionBarActivity implements onItemClickListener {
private static final int SUCCESS_CONNECT = 0;
private static final int MESSAGE_READ = 1;
int duration = Toast.LENGTH_SHORT;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
Set<BluetoothDevice> pairedDevices;
BluetoothAdapter mBluetoothAdapter;
ArrayAdapter<String> mArrayAdapter;
ArrayList<String> listDevices;
ArrayList<BluetoothDevice> devices;
Handler mHandler;
//ArrayList<BluetoothDevice> listDevices;
ListView listView;
IntentFilter filter;
BroadcastReceiver receiver;
public void onItemClickListener(AdapterView<?> arg0, View arg1,int arg2, long arg3 ){
if (mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
if (mArrayAdapter.getItem(arg2).contains("NOMBRE_ESTEF_DEVICE")){
BluetoothDevice selectedDevice = devices.get(arg2);
Toast.makeText(getApplicationContext(), "Device is paired", duration ).show();
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
}
}
private void turnOnBt() {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
public void init(){
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
listView=(ListView)findViewById(R.id.listView);
mArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
listView.setAdapter(mArrayAdapter);
listView.setOnItemClickListener(this);
/*
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(), " ITEM CLICKED POSITION = "+String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
*/
listDevices=new ArrayList<>();
//listView.setOnItemClickListener(this);
devices = new ArrayList<BluetoothDevice>();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
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);
mArrayAdapter.add(device.getName());
}else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
//still missing
}else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
//still missing
}else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
if (mBluetoothAdapter.getState()== mBluetoothAdapter.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 onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conectivity);
init();
if (mBluetoothAdapter != null) {
// Check if Device support Bluetooth
if (!mBluetoothAdapter.isEnabled()) {
turnOnBt();
}
getPairedDevices();
startDiscovery();
}else {
// Toast.makeText(getApplicationContext(), "No bluetooth detected", duration ).show();
// finish();
}
mHandler = new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
ConnectedThread connected = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "Connect", duration ).show();
String s = "prueba, conecta";
connected.write(s.getBytes());
break;
case MESSAGE_READ:
byte [] readBuff= (byte[])msg.obj;
String string = new String(readBuff);
Toast.makeText(getApplicationContext(), string, duration ).show();
break;
}
}
};
}
private void startDiscovery() {
mBluetoothAdapter.cancelDiscovery();
mBluetoothAdapter.startDiscovery();
}
private void getPairedDevices() {
pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
listDevices.add(device.getName() + " : " + device.getAddress());
}
}
}
@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 enable", duration ).show();
finish();
} else {
System.out.println("two");
}
}
@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_main, 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);
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(mmSocket);
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
// private void manageConnectedSocket(BluetoothSocket mmSocket) {
//
// }
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;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
buffer = new byte[1024];
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
,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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
android:background="@color/black">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ListView">
</ListView>
</RelativeLayout>
仅供参考我已经尝试使用how-to-implement-onitemclicklistener-in-this-code how-to-implement-onitemclicklistener-in-array-adapter
中提供的解决方案请帮我弄清楚我错过了什么。
答案 0 :(得分:0)
OnItemClickListener
是界面:
https://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html
实现接口的类必须为
提供实现onItemClick(AdapterView<?> parent, View view, int position, long id)
评论部分
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(), " ITEM CLICKED POSITION = "+String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
使用匿名内部类
执行相同操作在您的情况下,您评论了以上内容并且
listView.setOnItemClickListener(this);
this
指的是您的Activity类。因此你有
实现OnItemClickListener
要摆脱错误,请替换此
public class Conectivity extends ActionBarActivity implements onItemClickListener {
与
public class Conectivity extends ActionBarActivity implements OnItemClickListener {
并替换此
public void onItemClickListener(AdapterView<?> arg0, View arg1,int arg2, long arg3 ){
if (mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
if (mArrayAdapter.getItem(arg2).contains("NOMBRE_ESTEF_DEVICE")){
BluetoothDevice selectedDevice = devices.get(arg2);
Toast.makeText(getApplicationContext(), "Device is paired", duration ).show();
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
}
}
与
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
if (mArrayAdapter.getItem(arg2).contains("NOMBRE_ESTEF_DEVICE")){
BluetoothDevice selectedDevice = devices.get(arg2);
Toast.makeText(getApplicationContext(), "Device is paired", duration ).show();
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
}
}