我正在构建一个使用蓝牙与rc船通信的应用程序。但它在设备上崩溃说:“不幸的是,Wheeler App已经停止了。”所以,我在模拟器中运行它,知道在第111行抛出空指针异常,因为它不是真正的设备,试图找出抛出运行时异常的内容,说“无法启动活动ComponentInfo” 这是我的完整代码 -
package com.in2gravity.wheeler;
package com.in2gravity.wheeler;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private BluetoothAdapter mBluetoothAdapter;
private BluetoothDevice mDevice;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
Handler mHandler;
private byte[] up, down, left, right, g1, g2, g3, g4, launch, dock;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Buttons Enlisting
Button upnavbutton , downnavbutton, leftnavbutton, rightnavbutton,gearup1, gearup2, geardown1, geardown2, launchbutton, dockbutton;
// texts Enlisting & id registration
TextView propellerText = (TextView)findViewById(R.id.propellerText);
TextView in2gravityText = (TextView)findViewById(R.id.in2gravityText);
TextView timerText = (TextView)findViewById(R.id.timerText);
// imageview enlisting & id registration
ImageView appLogo = (ImageView)findViewById(R.id.appLogo);
//chronometer enlisting & id registration
Chronometer timer = (Chronometer)findViewById(R.id.chronometer1);
//button id registration
upnavbutton = (Button)findViewById(R.id.upnavbutton);
downnavbutton = (Button)findViewById(R.id.downnavbutton);
leftnavbutton = (Button)findViewById(R.id.leftnavbutton);
rightnavbutton = (Button)findViewById(R.id.rightnavbutton);
gearup1 = (Button)findViewById(R.id.gearbutton3);
gearup2 = (Button)findViewById(R.id.gearbutton4);
geardown2 = (Button)findViewById(R.id.gearbutton2);
geardown1 = (Button)findViewById(R.id.gearbutton1);
launchbutton = (Button)findViewById(R.id.launchbutton);
dockbutton = (Button)findViewById(R.id.dockbutton);
// setting onclick listener to this class
upnavbutton.setOnClickListener(this);
downnavbutton.setOnClickListener(this);
leftnavbutton.setOnClickListener(this);
rightnavbutton.setOnClickListener(this);
launchbutton.setOnClickListener(this);
dockbutton.setOnClickListener(this);
gearup1.setOnClickListener(this);
gearup2.setOnClickListener(this);
geardown2.setOnClickListener(this);
geardown1.setOnClickListener(this);
// converting strings to bytes for further use
up = "u".getBytes();
down = "d".getBytes();
left = "l".getBytes();
right = "r".getBytes();
launch = "L".getBytes();
dock = "D".getBytes();
g1 = "1".getBytes();
g2 = "2".getBytes();
g3 = "3".getBytes();
g4 = "4".getBytes();
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
byte[] writeBuf = (byte[]) msg.obj;
int begin = (int)msg.arg1;
int end = (int)msg.arg2;
switch(msg.what) {
case 1:
String writeMessage = new String(writeBuf);
writeMessage = writeMessage.substring(begin, end);
break;
}
}
};
Intent enableBluetooth = null;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter== null){
String tag = null;
// no bluetooth support!
Log.e(tag, "Bluetooth is not supported in this device");
}
if(!mBluetoothAdapter.isEnabled()){
enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 1);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0){
for(BluetoothDevice device : pairedDevices){
mDevice = device;
}
}
mConnectThread = new ConnectThread(mDevice);
mConnectThread.start();
// if (savedInstanceState == null) {
// getFragmentManager().beginTransaction()
// .add(R.id.container, new PlaceholderFragment()).commit();
// }
}
连接线程类:
private class ConnectThread extends Thread{
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
public ConnectThread(BluetoothDevice device){
BluetoothSocket tmp =null;
mmDevice= device;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {}
// TODO Auto-generated catch block
mmSocket =tmp;
}
public void run() {
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) {
return;
}
}
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
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 = new byte[1024];
int begin = 0;
int bytes = 0;
while (true) {
try {
bytes += mmInStream.read(buffer, bytes, buffer.length - bytes);
for(int i = begin; i < bytes; i++) {
if(buffer[i] == "#".getBytes()[0]) {
mHandler.obtainMessage(1, begin, i, buffer).sendToTarget();
begin = i + 1;
if(i == bytes - 1) {
bytes = 0;
begin = 0;
}
}
}
} catch (IOException e) {
break;
}
}
}
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { e.printStackTrace(); }
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.launchbutton:
//when launch button pressed
mConnectedThread.write(launch);
break;
case R.id.dockbutton :
//when dock button pressed
mConnectedThread.write(dock);
break;
case R.id.upnavbutton :
//when dock button pressed
mConnectedThread.write(up);
break;
case R.id.downnavbutton :
//when dock button pressed
mConnectedThread.write(down);
break;
case R.id.leftnavbutton :
//when dock button pressed
mConnectedThread.write(left);
break;
case R.id.rightnavbutton :
//when dock button pressed
mConnectedThread.write(right);
break;
case R.id.gearbutton1 :
//when dock button pressed
mConnectedThread.write(g1);
break;
case R.id.gearbutton2 :
//when dock button pressed
mConnectedThread.write(g2);
break;
case R.id.gearbutton3 :
//when dock button pressed
mConnectedThread.write(g4);
break;
case R.id.gearbutton4 :
//when dock button pressed
mConnectedThread.write(g3);
break;
}
}
}
logcat的:
04-10 06:27:33.389:D / dalvikvm(2489):GC_FOR_ALLOC释放了51K,5%免费 2977K / 3124K,暂停64ms,总计68ms
04-10 06:27:33.629:D / dalvikvm(2489):GC_FOR_ALLOC释放5K,4%免费3425K / 3568K,暂停5ms,总计5ms
04-10 06:27:33.729:E / BluetoothAdapter(2489):蓝牙装订器为空
04-10 06:27:33.729:E /(2489):此设备不支持蓝牙
04-10 06:27:33.729:D / AndroidRuntime(2489):关闭虚拟机
04-10 06:27:33.729:W / dalvikvm(2489):threadid = 1:线程退出时未捕获异常(group = 0xb3cd2b20)
04-10 06:27:33.829:E / AndroidRuntime(2489):致命异常:主
04-10 06:27:33.829:E / AndroidRuntime(2489):进程:com.in2gravity.wheeler,PID:2489
04-10 06:27:33.829:E / AndroidRuntime(2489):java.lang.RuntimeException:无法启动活动ComponentInfo
{com.in2gravity.wheeler / com.in2gravity.wheeler.MainActivity}:java.lang.NullPointerException
04-10 06:27:33.829:E / AndroidRuntime(2489):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-10 06:27:33.829:E / AndroidRuntime(2489):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-10 06:27:33.829:E / AndroidRuntime(2489):在android.app.ActivityThread.access $ 800(ActivityThread.java:135)
04-10 06:27:33.829:E / AndroidRuntime(2489):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1196)
04-10 06:27:33.829:E / AndroidRuntime(2489):在android.os.Handler.dispatchMessage(Handler.java:102)
04-10 06:27:33.829:E / AndroidRuntime(2489):在android.os.Looper.loop(Looper.java:136)
04-10 06:27:33.829:E / AndroidRuntime(2489):在android.app.ActivityThread.main(ActivityThread.java:5017)
04-10 06:27:33.829:E / AndroidRuntime(2489):at java.lang.reflect.Method.invokeNative(Native Method)
04-10 06:27:33.829:E / AndroidRuntime(2489):at java.lang.reflect.Method.invoke(Method.java:515)
04-10 06:27:33.829:E / AndroidRuntime(2489):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:779)
04-10 06:27:33.829:E / AndroidRuntime(2489):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-10 06:27:33.829:E / AndroidRuntime(2489):at dalvik.system.NativeStart.main(Native Method)
04-10 06:27:33.829:E / AndroidRuntime(2489):引起:java.lang.NullPointerException
04-10 06:27:33.829:E / AndroidRuntime(2489):at com.in2gravity.wheeler.MainActivity.onCreate(MainActivity.java:112)
04-10 06:27:33.829:E / AndroidRuntime(2489):在android.app.Activity.performCreate(Activity.java:5231)
04-10 06:27:33.829:E / AndroidRuntime(2489):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-10 06:27:33.829:E / AndroidRuntime(2489):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-10 06:27:33.829:E / AndroidRuntime(2489):... 11更多
activity_main.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=".MainActivity" >
<ImageView
android:id="@+id/appLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:contentDescription="@string/app_logo"
android:src="@drawable/wheelerapp_logo2" />
<Button
android:id="@+id/upnavbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/appLogo"
android:layout_centerHorizontal="true"
android:background="@drawable/upnavbutton" />
<Button
android:id="@+id/downnavbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/upnavbutton"
android:layout_below="@+id/appLogo"
android:background="@drawable/upnavbutton"
android:rotation="180" />
<Button
android:id="@+id/rightnavbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="8dp"
android:layout_toRightOf="@+id/appLogo"
android:background="@drawable/rightnavbutton" />
<Chronometer
android:id="@+id/chronometer1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/downnavbutton"
android:layout_alignLeft="@+id/leftnavbutton"
android:layout_marginLeft="16dp"
android:text="Chronometer"
tools:ignore="HardcodedText" />
<TextView
android:id="@+id/propellerText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/leftnavbutton"
android:layout_alignLeft="@+id/launchbutton"
android:text="@string/Propeller_Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/in2gravityText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/chronometer1"
android:layout_alignBottom="@+id/chronometer1"
android:layout_alignLeft="@+id/propellerText"
android:text="@string/in2gravity_text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="@+id/launchbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/rightnavbutton"
android:layout_alignRight="@+id/rightnavbutton"
android:layout_marginRight="14dp"
android:background="@android:color/holo_green_light"
android:text="@string/launchbutton_text" />
<Button
android:id="@+id/dockbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/rightnavbutton"
android:layout_alignLeft="@+id/chronometer1"
android:background="@android:color/holo_red_light"
android:text="@string/Dockbutton_text" />
<Button
android:id="@+id/leftnavbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/rightnavbutton"
android:layout_marginRight="10dp"
android:layout_marginTop="7dp"
android:layout_toLeftOf="@+id/appLogo"
android:background="@drawable/leftnavbutton" />
<Button
android:id="@+id/gearbutton3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/launchbutton"
android:layout_alignBottom="@+id/launchbutton"
android:layout_marginLeft="8dp"
android:layout_toRightOf="@+id/upnavbutton"
android:background="@android:color/holo_blue_light"
android:text="@string/gearup2_text" />
<Button
android:id="@+id/gearbutton4"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/gearbutton3"
android:layout_toLeftOf="@+id/upnavbutton"
android:background="@android:color/holo_purple"
android:text="@string/gearup1_text" />
<Button
android:id="@+id/gearbutton1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/rightnavbutton"
android:layout_toLeftOf="@+id/downnavbutton"
android:background="@android:color/holo_orange_light"
android:text="@string/geardown2_text" />
<Button
android:id="@+id/gearbutton2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/gearbutton3"
android:layout_alignTop="@+id/gearbutton1"
android:background="@android:color/holo_orange_dark"
android:text="@string/geardown1_text" />
<TextView
android:id="@+id/timerText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/leftnavbutton"
android:layout_alignParentLeft="true"
android:layout_marginLeft="9dp"
android:text="@string/timer_text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
androidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.in2gravity.wheeler"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:icon="@drawable/wheelerapp_logo2"
android:label="@string/app_name"
android:theme="@style/AppBaseTheme" android:allowBackup="true">
<activity
android:screenOrientation="landscape"
android:name="com.in2gravity.wheeler.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
注意:我在此应用中使用自定义按钮,如果有帮助的话。这里的10个按钮中有一个(所有按钮都以相同的方式构建) upnavbutton.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_enabled="true"
android:state_pressed="true" android:drawable="@drawable/upnavbutton_pressed" />
<item android:state_enabled="true"
android:drawable="@drawable/upnavbutton_normal" />
</selector>
答案 0 :(得分:0)
我研究了一些导致此错误的案例,发现有时它是由我们设置内容视图的xml视图引起的。和在这个程序中一样,我首先在fragment_main.xml
文件上构建了按钮和其他视图,然后在按钮监听器上遇到了空指针异常。我认为它可能以任何方式与程序冲突。
因此,我将整个xml复制粘贴到activity_main.xml
,然后删除fragment_main.xml
。并且还注释了片段的layoutinflater。这导致了视图中的污染等问题。
之后我运行程序,它运行正常。