Javascript到Java NullPointerException虚拟方法

Javascript to Java NullPointerException virtual method

本文关键字:虚拟 方法 NullPointerException Java Javascript      更新时间:2023-09-26

我是安卓系统的新手,我知道JavaScript和一点Java。因此,我试图调用一个从JavaScript到Java的函数来获取蓝牙设备的列表。我一直得到这个java.lang.NullPointerException:尝试调用虚拟方法。我已经在谷歌上搜索了一天,尝试了很多不同的方法,但不知道如何做到这一点。如果我只是直接从onCreate输出,它可以工作,但我希望它在我点击网页上的按钮时运行。请帮助我的代码如下。

public class MainActivity extends CordovaActivity
{

private DeviceListAdapter mDeviceListAdapter;
private boolean mScanning;
private Handler mHandler;
private int mSelected;
private Menu mMenu;
private UUID mServiceUuid;
public BluetoothAdapter mBluetoothAdapter;

private final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        String action = intent.getAction();
        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action))
        {
            // Get the BluetoothDevice object from the Intent
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // If it's already paired, skip it, because it's been listed already
            if (device.getBondState() != BluetoothDevice.BOND_BONDED)
            {
                if (device.getType() != BluetoothDevice.DEVICE_TYPE_LE)
                {
                    mDeviceListAdapter.addDevice(device);
                    mDeviceListAdapter.notifyDataSetChanged();
                }
            }
            // When discovery is finished, change the Activity title
        }
        else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
        {
            mScanning = false;
            invalidateOptionsMenu();
        }
    }
};
private class DeviceListAdapter extends BaseAdapter
{
    private ArrayList<BluetoothDevice> mDevices;
    private LayoutInflater mInflator;
    public DeviceListAdapter()
    {
        super();
        mDevices = new ArrayList<BluetoothDevice>();
        mInflator = MainActivity.this.getLayoutInflater();
    }
    public void addDevice(BluetoothDevice device)
    {
        if(!mDevices.contains(device))
        {
            mDevices.add(device);
        }
    }
    public BluetoothDevice getDevice(int position)
    {
        return mDevices.get(position);
    }
    public void clear()
    {
        mDevices.clear();
    }
    @Override
    public int getCount()
    {
        return mDevices.size();
    }
    @Override
    public Object getItem(int i)
    {
        return mDevices.get(i);
    }
    @Override
    public long getItemId(int i)
    {
        return i;
    }
    @Override
    public View getView(int i, View view, ViewGroup viewGroup)
    {
        ViewHolder viewHolder;
        if (view == null)
        {
            view = mInflator.inflate(R.layout.listitem_device, null);
            viewHolder = new ViewHolder();
            viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
            viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
            view.setTag(viewHolder);
        }
        else
        {
            viewHolder = (ViewHolder) view.getTag();
        }
        BluetoothDevice device = mDevices.get(i);
        final String deviceName = device.getName();
        if (deviceName != null && deviceName.length() > 0)
            viewHolder.deviceName.setText(deviceName);
        else
            viewHolder.deviceName.setText("unknown device");
        viewHolder.deviceAddress.setText(device.getAddress());
        return view;
    }
}
static class ViewHolder
{
    TextView deviceName;
    TextView deviceAddress;
}

  @Override
public void onCreate(Bundle savedInstanceState)
{
        super.onCreate(savedInstanceState);
        loadUrl(launchUrl);
        Log.v("TAG","MainActivity1");
        WebView webview = new WebView(this);
        setContentView(webview);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setDatabaseEnabled(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setAllowFileAccess(true);
                webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webview.setVerticalScrollBarEnabled(false);
        webview.setHorizontalScrollBarEnabled(false);
        webview.setScrollContainer(false);
        webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
        webview.setWebChromeClient(new WebChromeClient());
        webview.addJavascriptInterface(new HelperClass(),"Hclass");
        webview.addJavascriptInterface(new MainActivity(),"btooth");
        webview.loadUrl("file:///android_asset/www/index.html");
        });
         loadActivity();
}
private void loadActivity(){
    mHandler = new Handler();
    mScanning = false;
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    this.registerReceiver(mReceiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    this.registerReceiver(mReceiver, filter);
    final BluetoothManager bluetoothManager =
            (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
    mBluetoothAdapter = bluetoothManager.getAdapter();
    if (mBluetoothAdapter == null)
    {
        Toast.makeText(this, "n support", Toast.LENGTH_SHORT).show();
    }
}
@JavascriptInterface
public String getDeviceList(){
    Log.v("TAG","getDeviceList");
    loadActivity();
    String ise = "NO";
    if (mBluetoothAdapter.isEnabled())
    {
        ise = "YES";
    }
    return ise;        
}
}

我的javascript现在看起来是这样的,我只想让它输出是否启用

 alert(window.btooth.getDeviceList());

来自logcat 的错误日志

05-07 05:04:58.050 7064-7155/com.eventsystemM2 W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Context.registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter)' on a null object reference
05-07 05:04:58.050 7064-7155/com.eventsystemM2 W/System.err:     at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:503)
05-07 05:04:58.050 7064-7155/com.eventsystemM2 W/System.err:     at com.eventsystemM2.MainActivity.loadActivity(MainActivity.java:330)
05-07 05:04:58.050 7064-7155/com.eventsystemM2 W/System.err:     at com.eventsystemM2.MainActivity.getDeviceList(MainActivity.java:368)
05-07 05:04:58.050 7064-7155/com.eventsystemM2 W/System.err:     at org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method)
05-07 05:04:58.050 7064-7155/com.eventsystemM2 W/System.err:     at org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:53)
05-07 05:04:58.050 7064-7155/com.eventsystemM2 W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
05-07 05:04:58.050 7064-7155/com.eventsystemM2 W/System.err:     at android.os.Looper.loop(Looper.java:145)
05-07 05:04:58.050 7064-7155/com.eventsystemM2 W/System.err:     at android.os.HandlerThread.run(HandlerThread.java:61)
05-07 05:04:58.050 7064-7064/com.eventsystemM2 I/chromium: [INFO:CONSOLE(230)] "Uncaught Error: Java exception was raised during method invocation", source: file:///android_asset/www/main.html (230)
05-07 05:09:57.980 7064-7064/com.eventsystemM2 V/ActivityThread: updateVisibility : ActivityRecord{11646ccf token=android.os.BinderProxy@147f9938 {com.eventsystemM2/com.eventsystemM2.MainActivity}} show : true

我认为它应该像这样工作:

webview.addJavascriptInterface(this,"btooth");

你不能只是新建一个活动。