我正在構建一個簡單的應用程序,它可以打開設備的藍牙並將其設置爲可見。Android Studio藍牙: - 嘗試調用空對象上的虛擬方法參考
我有一個單獨的java類文件,它具有我需要的藍牙功能,並且通過該類的一個對象從另一個與我的活動相關聯的java類中調用這些文件。
這是我的代碼:
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
/**
* Created by mark on 11/11/2016.
*/
public class Bluetooth_API extends AppCompatActivity{
BluetoothAdapter blueAdp;
public Bluetooth_API() {
blueAdp = BluetoothAdapter.getDefaultAdapter();
}
protected int bluetooth_ON() {
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 0);
//blueAdp.enable(); //instead of above line - without alert dialog for permission
return 0;
}
protected int bluetooth_OFF() {
blueAdp.disable(); //
return 0;
}
protected int bluetooth_setVisible() {
if(!blueAdp.isDiscovering()) {
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE), 0);
}
return 0;
}
}
這是代碼的從被調用我的職務其他活動的部分:
scanButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent nextLayout = new Intent(getApplicationContext(), com.ai.mark.robot_dancing.Scanning_Devices.class);
startActivity(nextLayout);
blue.bluetooth_ON();
//blue.bluetooth_setVisible();
}
});
我正在下面我一旦運行錯誤我的代碼,我相信它與活動不是正確的,因爲我的藍牙功能在另一個文件(我也嘗試複製方法到我的活動課,他們工作得很好)。
錯誤:
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.ai.mark.robot_dancing, PID: 21314 java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference at android.app.Activity.startActivityForResult(Activity.java:3951) at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48) at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:77) at android.app.Activity.startActivityForResult(Activity.java:3912) at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859) at com.ai.mark.robot_dancing.Bluetooth_API.bluetooth_ON(Bluetooth_API.java:20) at com.ai.mark.robot_dancing.Bluetooth_Panel$6.onClick(Bluetooth_Panel.java:146) at android.view.View.performClick(View.java:5210) at android.view.View$PerformClick.run(View.java:21328) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5551) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
是什麼原因造成這種任何想法? 謝謝。
謝謝!我想問題是,函數返回沒有找到要附加的活動。我是否有權這樣做? – Logan
是的。 「Actvitity」的「Context」尚未在構造函數中準備好。它是在'onCreate()'事件中準備的。 –