我是一名新程序员,最近我有一个错误但无法解决
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.Bl
uetoothChat/com.example.android.BluetoothFileTran.FileTranActivity}:
java.lang.NullPointerException
logcat堆栈跟踪
04-26 10:19:43.613: E/BluetoothChat(21754): +++ ON CREATE +++
04-26 10:19:44.213: E/CheckPermission(21754): _bluetooth code = 1
04-26 10:19:44.213: E/BluetoothChat(21754): ++ ON START ++
04-26 10:19:44.233: E/BluetoothChat(21754): + ON RESUME +
04-26 10:19:44.233: E/CheckPermission(21754): _bluetooth code = 13
04-26 10:19:45.643: E/BluetoothChat(21754): - ON PAUSE -
04-26 10:19:47.223: E/BluetoothChat(21754): + ON RESUME +
04-26 10:19:55.093: E/BluetoothChat(21754): - ON PAUSE -
04-26 10:20:21.363: E/AndroidRuntime(21754): FATAL EXCEPTION: main
04-26 10:20:21.363: E/AndroidRuntime(21754): Process: com.example.android.BluetoothChat, PID: 21754
04-26 10:20:21.363: E/AndroidRuntime(21754): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.BluetoothChat/com.example.android.BluetoothFileTran.FileTranActivity}: java.lang.NullPointerException
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2190)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.access$800(ActivityThread.java:139)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.os.Looper.loop(Looper.java:136)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.main(ActivityThread.java:5049)
04-26 10:20:21.363: E/AndroidRuntime(21754): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): at java.lang.reflect.Method.invoke(Method.java:515)
04-26 10:20:21.363: E/AndroidRuntime(21754): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:818)
04-26 10:20:21.363: E/AndroidRuntime(21754): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:634)
04-26 10:20:21.363: E/AndroidRuntime(21754): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
04-26 10:20:21.363: E/AndroidRuntime(21754): at dalvik.system.NativeStart.main(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): Caused by: java.lang.NullPointerException
04-26 10:20:21.363: E/AndroidRuntime(21754): at com.example.android.BluetoothFileTran.FileTranActivity.onCreate(FileTranActivity.java:66)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.Activity.performCreate(Activity.java:5293)
04-26 10:20:21.363: E/AndroidRuntime(21754): at de.robv.android.xposed.XposedBridge.invokeOriginalMethodNative(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): at de.robv.android.xposed.XposedBridge.handleHookedMethod(XposedBridge.java:631)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.Activity.performCreate(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2154)
04-26 10:20:21.363: E/AndroidRuntime(21754): ... 12 more
这是Bluetoooth.java
package com.example.android.BluetoothChat;
import com.example.android.BluetoothChat.R;
import com.example.android.BluetoothChat.service.BluetoothChatService;
import com.example.android.BluetoothFileTran.FileTranActivity;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class BluetoothChat extends Activity {
public static final String SEND_FILE_NAME = "sendFileName";
public static final int REQUEST_FILE = 1000;
private static String mSendFileName ;
private Handler mOthHandler;
private static String mAddress ;
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
private String mConnectedDeviceName = null;
private ArrayAdapter<String> mConversationArrayAdapter;
private StringBuffer mOutStringBuffer;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothChatService mChatService = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
setContentView(R.layout.main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
@Override
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
if (mChatService == null) setupChat();
}
}
private void setupChat() {
Log.d(TAG, "setupChat()");
mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
mConversationView = (ListView) findViewById(R.id.in);
mConversationView.setAdapter(mConversationArrayAdapter);
mOutEditText = (EditText) findViewById(R.id.edit_text_out);
mOutEditText.setOnEditorActionListener(mWriteListener);
mSendButton = (Button) findViewById(R.id.button_send);
mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView view = (TextView) findViewById(R.id.edit_text_out);
String message = view.getText().toString();
sendMessage(message);
}
});
mChatService = new BluetoothChatService(this, mHandler);
mOutStringBuffer = new StringBuffer("");
}
@Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
if (mChatService != null) {
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
mChatService.start();
}
}
}
private TextView.OnEditorActionListener mWriteListener =
new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
//EditorInfo.IME_NULL KeyEvent.ACTION_UP
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
if(D) Log.i(TAG, "END onEditorAction");
return true;
}
};
@Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
}
@Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
@Override
public void onDestroy() {
super.onDestroy();
if (mChatService != null) mChatService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
}
private void sendMessage(String message) {
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
byte[] send = message.getBytes();
mChatService.write(send);
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
break;
case MESSAGE_DEVICE_NAME:
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
// mAddress = msg.getData().getString(DEVICE_ADDRESS);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
mAddress = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mAddress);
mChatService.connect(device);
}
break;
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
setupChat();
} else {
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
break;
case REQUEST_FILE:
if (resultCode == Activity.RESULT_OK) {
mSendFileName = data.getExtras().getString(SEND_FILE_NAME);
doSendFileByBluetooth();
}
break;
}
}
private void doSendFileByBluetooth() {
String filePath = mSendFileName.trim();
if(!filePath.equals("null")){
if(null == mOthHandler){
HandlerThread handlerThread = new HandlerThread("other_thread");
handlerThread.start();
mOthHandler = new Handler(handlerThread.getLooper());
}
mOthHandler.post(new Runnable() {
@Override
public void run() {
ContentValues cv = new ContentValues();
String uri = "file://" + mSendFileName.trim();
cv.put("uri", uri);
cv.put("destination", mAddress.trim());
cv.put("direction", 0);
Long ts = System.currentTimeMillis();
cv.put("timestamp", ts);
getContentResolver().insert(Uri.parse("content://com.android.bluetooth.opp/btopp"), cv);
}
});
}else {
Toast.makeText(BluetoothChat.this, "请选择要发送的文件!", Toast.LENGTH_LONG).show();
}
}
private void ensureDiscoverable() {
if(D) Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.option_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.scan:
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
return true;
case R.id.discoverable:
ensureDiscoverable();
return true;
case R.id.file_transport:
Intent fileIntent = new Intent(this, FileTranActivity.class);
startActivityForResult(fileIntent, REQUEST_FILE);
return true;
}
return false;
}
}
这里是FileTranActivity.java
package com.example.android.BluetoothFileTran;
import java.io.File;
import com.example.android.BluetoothChat.BluetoothChat;
import com.example.android.BluetoothChat.R;
import com.example.android.BluetoothFileTran.adapter.AdapterManager;
import com.example.android.BluetoothFileTran.adapter.FileListAdapter;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class FileTranActivity extends Activity {
ListView mFileListView;
FileListAdapter mFileListAdapter;
AdapterManager mAdapterManager;
private Handler mOtherHandler;
private Runnable updateFileListRunnable;
private File file;
private String sdcardPath;
private String path;
Button mBackBtn;
Button mEnsureBtn;
Button mCancelBtn;
TextView mLastClickView;
TextView mNowClickView;
private boolean isSelected = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.file_list);
setResult(Activity.RESULT_CANCELED);
mFileListView = (ListView) findViewById(R.id.fileListView);
mBackBtn = (Button) findViewById(R.id.selectFileBackBtn);
mEnsureBtn = (Button) findViewById(R.id.selectFileEnsureBtn);
mCancelBtn = (Button) findViewById(R.id.selectFileCancelBtn);
sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
path = sdcardPath;
mAdapterManager = BluetoothApplication.getInstance().getAdapterManager();
mFileListView.setAdapter(mAdapterManager.getFileListAdapter());
mAdapterManager.updateFileListAdapter(path);
mFileListView.setOnItemClickListener(mFileListOnItemClickListener);
mBackBtn.setOnClickListener(mBackBtnClickListener);
mEnsureBtn.setOnClickListener(mEnsureBtnClickListener);
mCancelBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
FileTranActivity.this.finish();
}
});
}
private OnItemClickListener mFileListOnItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
file = (File) mFileListView.getAdapter().getItem(position);
if(file.isFile()){
if(null != mLastClickView){
mLastClickView.setTextColor(Color.WHITE);
}
mNowClickView = (TextView) view.findViewById(R.id.fileNameTV);
mNowClickView.setTextColor(Color.BLUE);
isSelected = true;
mLastClickView = mNowClickView;
}else {
path = file.getAbsolutePath();
updateFileList();
}
}
};
private OnClickListener mBackBtnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
if(path.equals(sdcardPath)){
return ;
}
path = path.substring(0, path.lastIndexOf("/"));
updateFileList();
}
};
private OnClickListener mEnsureBtnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
if(!isSelected){
Toast.makeText(FileTranActivity.this, "请选择文件!", Toast.LENGTH_LONG).show();
return ;
}
Intent intent = new Intent();
intent.putExtra(BluetoothChat.SEND_FILE_NAME, file.getAbsolutePath());
setResult(Activity.RESULT_OK, intent);
FileTranActivity.this.finish();
}
};
private void updateFileList() {
if(null != mLastClickView){
mLastClickView.setTextColor(Color.WHITE);
mLastClickView = null;
isSelected = false;
}
if(null == updateFileListRunnable){
updateFileListRunnable = new Runnable() {
@Override
public void run() {
mAdapterManager.updateFileListAdapter(path);
}
};
}
if(null == mOtherHandler){
HandlerThread handlerThread = new HandlerThread("other_thread");
handlerThread.start();
mOtherHandler = new Handler(handlerThread.getLooper());
}
mOtherHandler.post(updateFileListRunnable);
}
}
然后,我发现它指出了FileTranActivity.java中的错误
mAdapterManager = BluetoothApplication.getInstance().getAdapterManager();
所以,这是BluetoothApplication.java
package com.example.android.BluetoothFileTran;
import com.example.android.BluetoothFileTran.adapter.AdapterManager;
import com.example.android.BluetoothFileTran.adapter.util.TouchObject;
import android.app.Application;
public class BluetoothApplication extends Application {
private static BluetoothApplication application;
private AdapterManager mAdapterManager;
private TouchObject mTouchObject;
@Override
public void onCreate() {
super.onCreate();
if(null == application){
application = this;
}
mTouchObject = new TouchObject();
}
public static BluetoothApplication getInstance(){
return application;
}
public AdapterManager getAdapterManager() {
return mAdapterManager;
}
public void setAdapterManager(AdapterManager adapterManager) {
this.mAdapterManager = adapterManager;
}
public TouchObject getTouchObject() {
return mTouchObject;
}
public void setTouchObject(TouchObject touchObject) {
this.mTouchObject = touchObject;
}
}
和AdapterManager.java
package com.example.android.BluetoothFileTran.adapter;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Handler;
import com.example.android.BluetoothChat.R;
import com.example.android.BluetoothFileTran.adapter.FileListAdapter;
public class AdapterManager {
private Context mContext;
private FileListAdapter mFileListAdapter;
private List<BluetoothDevice> mDeviceList;
private List<File> mFileList;
private Handler mainHandler;
public AdapterManager(Context context){
this.mContext = context;
}
public FileListAdapter getFileListAdapter(){
if(null == mFileListAdapter){
mFileList = new ArrayList<File>();
mFileListAdapter = new FileListAdapter(mContext, mFileList, R.layout.file_list_item);
}
return mFileListAdapter;
}
public void clearDevice(){
if(null != mDeviceList){
mDeviceList.clear();
}
}
public void addDevice(BluetoothDevice bluetoothDevice){
mDeviceList.add(bluetoothDevice);
}
public void changeDevice(int listId, BluetoothDevice bluetoothDevice){
mDeviceList.remove(listId);
mDeviceList.add(listId, bluetoothDevice);
}
public void updateFileListAdapter(String path){
mFileList.clear();
mFileList.addAll(getFileList(path));
if(null == mainHandler){
mainHandler = new Handler(mContext.getMainLooper());
}
mainHandler.post(new Runnable() {
@Override
public void run() {
mFileListAdapter.notifyDataSetChanged();
}
});
}
public List<BluetoothDevice> getDeviceList() {
return mDeviceList;
}
public static List<File> getFileList(String path){
List<File> fileList = new ArrayList<File>();
File[] files = new File(path).listFiles();
if(files.length > 0){
List<File> allFolder = new ArrayList<File>();
List<File> allFile = new ArrayList<File>();
for(File file : files){
if(file.isFile()){
allFile.add(file);
}else {
allFolder.add(file);
}
}
fileList.addAll(allFolder);
fileList.addAll(allFile);
}
return fileList;
}
}
我的xml是
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.BluetoothChat"
android:versionCode="1"
android:versionName="1.0" xmlns:tools="http://schemas.android.com/tools">
<uses-sdk
android:minSdkVersion="6"
android:targetSdkVersion="18" tools:ignore="OldTargetApi"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:label="@string/app_name"
android:icon="@drawable/ic_launcher"
android:theme="@style/AppTheme" >
<activity android:name="com.example.android.BluetoothChat.BluetoothChat"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.android.BluetoothChat.DeviceListActivity"
android:label="@string/select_device"
android:theme="@android:style/Theme.Dialog"
/>
<activity android:name="com.example.android.BluetoothFileTran.FileTranActivity"
android:label="@string/select_file"
android:theme="@android:style/Theme.Dialog"
/>
</application>
</manifest>
答案 0 :(得分:0)
在 AndroidManifest
中注册 BluetoothFileTran
类作为 application
标签中的应用程序名称:
&lt; application&#xA;机器人:allowBackup = “真” &#XA;机器人:名字= “com.example.android.BluetoothFileTran” &#XA; ...&#xA;
&#xA;&#xA; 如果没有这个, BluetoothFileTran
将不会加载, onCreate 代码>永远不会被调用。
这将在 BluetoothApplication.getInstance()
中返回一个空引用,这会引起您的 NullPointerException
。
参考 < &p>&#xA;&#xA;
注意:清单中的包 package =“com.example.android.BluetoothChat”
与 BluetoothFileTran <的包不同/ code>位于(不在其中一个孩子中)。我建议你在清单标签中使用
com.example.android
包而不是 com.example.android.BluetoothChat
。