Logcat
07-07 16:03:11.203: E/AndroidRuntime(18538): FATAL EXCEPTION: main
07-07 16:03:11.203: E/AndroidRuntime(18538): java.lang.RuntimeException: Unable to start activity ComponentInfo{tp.mp2014.dotmatrix/tp.mp2014.dotmatrix.bluetoothtest}: java.lang.NullPointerException
07-07 16:03:11.203: E/AndroidRuntime(18538): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2129)
07-07 16:03:11.203: E/AndroidRuntime(18538): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2154)
07-07 16:03:11.203: E/AndroidRuntime(18538): at android.app.ActivityThread.access$700(ActivityThread.java:146)
07-07 16:03:11.203: E/AndroidRuntime(18538): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1260)
07-07 16:03:11.203: E/AndroidRuntime(18538): at android.os.Handler.dispatchMessage(Handler.java:99)
07-07 16:03:11.203: E/AndroidRuntime(18538): at android.os.Looper.loop(Looper.java:137)
07-07 16:03:11.203: E/AndroidRuntime(18538): at android.app.ActivityThread.main(ActivityThread.java:4949)
07-07 16:03:11.203: E/AndroidRuntime(18538): at java.lang.reflect.Method.invokeNative(Native Method)
07-07 16:03:11.203: E/AndroidRuntime(18538): at java.lang.reflect.Method.invoke(Method.java:511)
07-07 16:03:11.203: E/AndroidRuntime(18538): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1043)
07-07 16:03:11.203: E/AndroidRuntime(18538): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
07-07 16:03:11.203: E/AndroidRuntime(18538): at dalvik.system.NativeStart.main(Native Method)
07-07 16:03:11.203: E/AndroidRuntime(18538): Caused by: java.lang.NullPointerException
07-07 16:03:11.203: E/AndroidRuntime(18538): at tp.mp2014.dotmatrix.bluetoothtest.onCreate(bluetoothtest.java:114)
07-07 16:03:11.203: E/AndroidRuntime(18538): at android.app.Activity.performCreate(Activity.java:5185)
07-07 16:03:11.203: E/AndroidRuntime(18538): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
07-07 16:03:11.203: E/AndroidRuntime(18538): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2093)
07-07 16:03:11.203: E/AndroidRuntime(18538): ... 11 more
bluetoothtest.java
package tp.mp2014.dotmatrix;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import tp.mp2014.dotmatrix.ChatListAdapter;
import tp.mp2014.dotmatrix.ChatListAdapter.SiriListItem;
import tp.mp2014.dotmatrix.deviceListAdapter;
import tp.mp2014.dotmatrix.deviceListAdapter.deviceListItem;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class bluetoothtest extends Activity {
/** Called when the activity is first created. */
private ArrayList<deviceListItem> list;
private ArrayList<SiriListItem> delist;
private ButtonClicked clicked;
private readThread mreadThread = null;
private String BlueToothAddress;
final byte ANIMATION_MODE=1;
final byte PICTURE_MODE=2;
final byte TEXT_MODE=3;
int count = 0, click = 0;
ListView listViewPaired;
ListView deviceList;
ListView chatList;
deviceListAdapter mAdapter;
ChatListAdapter chAdapter;
Context mContext;
TextView btStatus;
ArrayList<String> arrayListpaired;
Button buttonSearch,buttonOn,buttonDesc,buttonOff, buttonConnect;
ArrayAdapter<String> adapter;
static HandleSeacrh handleSeacrh;
BluetoothSocket socket;
BluetoothDevice bdDevice;
BluetoothClass bdClass;
ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
BluetoothAdapter bluetoothAdapter = null;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = new ArrayList<deviceListAdapter.deviceListItem>();
delist = new ArrayList<ChatListAdapter.SiriListItem>();
chAdapter = new ChatListAdapter(this, delist);
mAdapter = new deviceListAdapter(this, list);
deviceList = (ListView) findViewById(R.id.deviceList);
buttonSearch = (Button) findViewById(R.id.buttonSearch);
buttonOn = (Button) findViewById(R.id.buttonOn);
buttonDesc = (Button) findViewById(R.id.buttonDesc);
buttonOff = (Button) findViewById(R.id.buttonOff);
buttonConnect = (Button) findViewById(R.id.connectBtn);
btStatus = (TextView) findViewById(R.id.btStatus);
//arrayListpaired = new ArrayList<String>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
clicked = new ButtonClicked();
handleSeacrh = new HandleSeacrh();
//arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
deviceList.setOnItemClickListener(mDeviceClickListener);
/*
* the above declaration is just for getting the paired bluetooth devices;
* this helps in the removing the bond between paired devices.
*/
deviceList.setAdapter(chAdapter);
chatList.setAdapter(mAdapter);
buttonConnect.setOnClickListener(new View.OnClickListener() {
@SuppressLint("NewApi")
@Override
public void onClick(View arg0) {
if (count == 0) {
Toast.makeText(bluetoothtest.this,
"Please connect to the bluetooth first or check the bluetooth open or not ",
Toast.LENGTH_LONG).show();
}
// Need API=14
else if (!socket.isConnected()) {
Toast.makeText(bluetoothtest.this,
"Please waiting for connecting !!!",
Toast.LENGTH_LONG).show();
}
else {
try {
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
buttonOn.setOnClickListener(clicked);
buttonSearch.setOnClickListener(clicked);
buttonDesc.setOnClickListener(clicked);
buttonOff.setOnClickListener(clicked);
}
private void getPairedDevices() {
Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();
if(pairedDevice.size()>0)
{
for(BluetoothDevice device : pairedDevice)
{
arrayListpaired.add(device.getName()+"\n"+device.getAddress());
arrayListPairedBluetoothDevices.add(device);
}
}
adapter.notifyDataSetChanged();
}
/*private void callThread() {
new Thread(){
public void run() {
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//connect(bdDevice);
Log.i("Log", "The bond is created: "+isBonded);
}
}.start();
}*/
private Boolean connect(BluetoothDevice bdDevice) {
Boolean bool = false;
try {
Log.i("Log", "service method is called ");
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("createBond", par);
Object[] args = {};
bool = (Boolean) method.invoke(bdDevice);//, args);// this invoke creates the detected devices paired.
} catch (Exception e) {
Log.i("Log", "Inside catch of serviceFromDevice Method");
e.printStackTrace();
}
return bool.booleanValue();
};
public boolean removeBond(BluetoothDevice btDevice)
throws Exception
{
Class btClass = Class.forName("android.bluetooth.BluetoothDevice");
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
class ButtonClicked implements OnClickListener
{
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonOn:
onBluetooth();
break;
case R.id.buttonSearch:
arrayListBluetoothDevices.clear();
startSearching();
break;
case R.id.buttonDesc:
makeDiscoverable();
break;
case R.id.buttonOff:
offBluetooth();
break;
default:
break;
}
}
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT).show();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
delist.add(new SiriListItem(device.getName() + "\n"
+ device.getAddress(), false));
mAdapter.notifyDataSetChanged();
deviceList.setSelection(delist.size() - 1);
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
.equals(action)) {
setProgressBarIndeterminateVisibility(false);
if (deviceList.getCount() == 0) {
delist.add(new SiriListItem(
"Did not find a bluetooth device", false));
mAdapter.notifyDataSetChanged();
deviceList.setSelection(list.size() - 1);
}
}
}
};
private void startSearching() {
if (!bluetoothAdapter.isEnabled()) {
Toast.makeText(bluetoothtest.this,
"Please open the bluetooth first",
Toast.LENGTH_SHORT).show();
buttonSearch.setText("Search bluetooth devices");
} else if (bluetoothAdapter.isEnabled()) {
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
buttonSearch.setText("Search again");
} else {
delist.clear();
chAdapter.notifyDataSetChanged();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
delist.add(new SiriListItem(device.getName()
+ "\n" + device.getAddress(), true));
chAdapter.notifyDataSetChanged();
deviceList.setSelection(delist.size() - 1);
}
} else {
delist.add(new SiriListItem(
"No devices have been paired", true));
delist.clear();
chAdapter.notifyDataSetChanged();
deviceList.setSelection(delist.size() - 1);
}
/* start discovery */
bluetoothAdapter.startDiscovery();
}
}
};
private void onBluetooth() {
String text = "Bluetooth Status: Turned on";
btStatus.setText(text);
btStatus.setBackgroundColor(Color.GREEN);
if(!bluetoothAdapter.isEnabled())
{
bluetoothAdapter.enable();
Log.i("Log", "Bluetooth is Enabled");
}
}
private void offBluetooth() {
String text = "Bluetooth Status: Turned off";
if(bluetoothAdapter.isEnabled())
{
bluetoothAdapter.disable();
btStatus.setText(text);
btStatus.setBackgroundColor(Color.RED);
}
}
private void makeDiscoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
Log.i("Log", "Discoverable ");
}
class HandleSeacrh extends Handler
{
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 111:
break;
default:
break;
}
}
}
SharedPreferences sp;
private void sendMessageHandle(String msg) {
final byte ANIMATION_MODE=1;
final byte PICTURE_MODE=2;
final byte TEXT_MODE=3;
final String PAUSE = "\r";
int temp,row;
sp = getSharedPreferences("SaveData",MODE_PRIVATE);
byte mode = (byte) sp.getInt("Mode",1);
byte [] pictureData = new byte [129];
byte [] textSetting =new byte [5];
if (socket == null) {
Toast.makeText(mContext, "No connection", Toast.LENGTH_SHORT)
.show();
return;
}
try {
OutputStream os = socket.getOutputStream();
if(mode==TEXT_MODE){
textSetting[0]='T';
textSetting[1]=(byte) sp.getInt("directionData", '1');
textSetting[2]=(byte) sp.getInt("positionData", '1');
textSetting[3]=(byte) sp.getInt("speedSeekBar", 10);
if(sp.getBoolean("checkBox1", true)){
textSetting[4]=1 ;
}
else
textSetting[4]=0 ;
os.write(textSetting);
os.write(msg.getBytes());
}
else if(mode==PICTURE_MODE){
pictureData[0]='B';
for(int col=0;col<32;col++){
for(int i=0;i<4;i++){ //! each byte
temp=(col<<2)+i+1;
for(int j=7;j>=0;j--){ //within 1 byte LSB last
row=(i<<3)+j;
pictureData[temp]<<=1;
if(sp.getBoolean("ledData"+(col+10)+(row+10), false)==true){ //
pictureData[temp]++;
}
}//for each byte
System.out.println("Byte info:col "+col +" row(/8) "+i +" "+pictureData[temp]);
}//col
}//for row
os.write(pictureData);
}
else if(mode==ANIMATION_MODE){
textSetting[0]='A';
textSetting[1]=(byte) sp.getInt("animationIndex", 1);
textSetting[2]='\r';
os.write(textSetting);
}
System.out.println("Mode: "+mode);
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
os.write(PAUSE.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list.add(new deviceListItem(msg, false));
mAdapter.notifyDataSetChanged();
chatList.setSelection(list.size() - 1);
}
private class clientThread extends Thread {
public void run() {
try {
//
bdDevice = bluetoothAdapter.getRemoteDevice(BlueToothAddress);
socket = bdDevice.createRfcommSocketToServiceRecord(UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB"));
Message msg2 = new Message();
msg2.obj = "Please wait, connecting to the server:"
+ BlueToothAddress;
msg2.what = 0;
LinkDetectedHandler.sendMessage(msg2);
socket.connect();
Message msg = new Message();
msg.obj = "Connected !!! Can send message.";
msg.what = 0;
LinkDetectedHandler.sendMessage(msg);
mreadThread = new readThread();
mreadThread.start();
click++;
} catch (IOException e) {
Message msg = new Message();
msg.obj = "Exception! Disconnect to try it again";
msg.what = 0;
LinkDetectedHandler.sendMessage(msg);
click--;
//sendedtTxt.setInputType(InputType.TYPE_CLASS_TEXT);
// Enable the openBtn,closeBtn£¬discoverBtn
//discoverBtn.setClickable(true);
}
}
};
private Handler LinkDetectedHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), (String) msg.obj,
Toast.LENGTH_SHORT).show();
if (msg.what == 1) {
list.add(new deviceListItem((String) msg.obj, true));
} else {
list.add(new deviceListItem((String) msg.obj, false));
}
mAdapter.notifyDataSetChanged();
chatList.setSelection(list.size() - 1);
}
};
private class readThread extends Thread {
public void run() {
byte[] buffer = new byte[1024];
int bytes;
InputStream mmInStream = null;
String tmp = null;
try {
mmInStream = socket.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
while (true) {
try {
// read the data from the inputStream
if ((bytes = mmInStream.read(buffer)) > 0)
{
for (int i = 0; i < bytes; i++) {
tmp = "" + buffer[i];
String st = new String(tmp);
tmp = null;
Message msg = new Message();
msg.obj = st;
msg.what = 1;
}
}
} catch (IOException e) {
try {
mmInStream.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
break;
}
}
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// Cancel discovery because it's costly and we're about to connect
bluetoothAdapter.cancelDiscovery();
if(delist.size() == 0)
{
Log.i("Tag", "Size is = "+delist.size());
}
SiriListItem item = delist.get(arg2);
mAdapter.notifyDataSetChanged();
// When device being clicked
count++;
click = 1;
//sendedtTxt.setInputType(InputType.TYPE_NULL);
// Disable the open bluetooth button,the close bluetooth button,the
// open bluetooth button
//openBtn.setClickable(false);
//discoverBtn.setClickable(false);
// Get the device MAC address, which is the last 17 chars in the
// View
String info = item.message;
String address = info.substring(info.length() - 17);
BlueToothAddress = address;
// String name = info.substring()
if (click == 1) {
clientThread ct = new clientThread();
ct.start();
}
};
};
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
unregisterReceiver(myReceiver);
super.onDestroy();
}
}
得到了 NullPointerException ,但我似乎无法找到问题所在。我试图删除任何可能的阵列相关的东西,但仍然没有工作。有人帮我出去吗?
答案 0 :(得分:2)
您尚未初始化您的chatList,因此chatList.setAdapter(mAdapter);
正在提供空指针异常。
ListView chatList;
chatList.setAdapter(mAdapter); //NullPointerException
那样做,
ListView chatList;
chatList = (ListView) findViewById(R.id.chatList);
chatList.setAdapter(mAdapter); //Now OK
答案 1 :(得分:1)
看起来你还没有初始化chatList