当前位置: 首页 > 知识库问答 >
问题:

如何避免java。lang.NumberFormatException:对于输入字符串:“”错误[重复]

颜经艺
2023-03-14

我正在用android Studio开发扫描android应用程序的蓝牙设备。有一个输入字段,当输入名称与扫描名称匹配时,我想将数据发送到firebase。下面我已经提到了我在做什么

public class MainActivity extends Activity {

private static final int REQUEST_ENABLE_BT = 1;
private static final int PERMISSIONS_REQUEST_CODE = 11;
ArrayList<Map<String, Integer>> deviceInfo = new ArrayList<>();

List<String> headerList = new ArrayList<>();
List<String> dataList = new ArrayList<>();
Snapobj snap ;
List<Snapobj > snapList = new ArrayList<Snapobj>();
public final int WRITE_PERMISSON_REQUEST_CODE =111;

ListView listDevicesFound;
Button btnScanDevice;
TextView stateBluetooth;
BluetoothAdapter bluetoothAdapter;

ArrayAdapter<String> btArrayAdapter;
FirebaseDatabase db = FirebaseDatabase.getInstance();
private DatabaseReference databaseRef;
private DatabaseReference databaseReference =  FirebaseDatabase.getInstance().getReference("BluetoothDevicesInfo");

List<DeviceInfo> deviceList;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (!havePermissions()) {
        Log.d("TAG", "Requesting permissions needed for this app.");
        requestPermissions();
    }

    setContentView(R.layout.activity_main);

    btnScanDevice = (Button)findViewById(R.id.scandevice);

    stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    listDevicesFound = (ListView)findViewById(R.id.devicesfound);
    btArrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
    listDevicesFound.setAdapter(btArrayAdapter);

    CheckBlueToothState();
    deviceList = new ArrayList<>();
    btnScanDevice.setOnClickListener(new View.OnClickListener(){
        @Override
        //On click function
        public void onClick(View view) {
            btArrayAdapter.clear();
            bluetoothAdapter.startDiscovery();
        }
    });

    registerReceiver(ActionFoundReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));


}

@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    unregisterReceiver(ActionFoundReceiver);
}

private void CheckBlueToothState(){
    if (bluetoothAdapter == null){
       // stateBluetooth.setText("Bluetooth NOT support");
    }else{
        if (bluetoothAdapter.isEnabled()){
            if(bluetoothAdapter.isDiscovering()){
               stateBluetooth.setText("Bluetooth is currently in device discovery process.");
            }else{
               stateBluetooth.setText("Bluetooth is Enabled.");
               btnScanDevice.setEnabled(true);
            }
        }else{
           // stateBluetooth.setText("Bluetooth is NOT Enabled!");
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
    }
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    if(requestCode == REQUEST_ENABLE_BT){
        CheckBlueToothState();
    }
}

private final BroadcastReceiver ActionFoundReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {

        // TODO Auto-generated method stub
        String action = intent.getAction();
        int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);

        Map<String, Integer> rssiMapper = new HashMap<>();

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {

            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            btArrayAdapter.add(device.getName() + "\nAddress : " + device.getAddress() + "\nRSSI : " + rssi+"\n");
            btArrayAdapter.notifyDataSetChanged();

            rssiMapper.put(device.getName(), rssi);
            deviceInfo.add(rssiMapper);
            System.out.println("hashmap : "+rssiMapper);

            SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

            EditText x = (EditText) findViewById(R.id.distance);
            Double distanceVal = Double.valueOf(x.getText().toString());

            EditText y = findViewById(R.id.deviceName);
            String deviceName = y.getText().toString()+ " ";

                if (device.getName().equals(deviceName+ " ")) {
                    databaseReference = db.getReference("BluetoothDevicesInfo");
                    DeviceInfo deviceInfoObj = new DeviceInfo(device.getAddress(), dateFormat.format(new Date()), rssi, distanceVal);
                    String id = databaseReference.push().getKey();
                    databaseReference.child(id).setValue(deviceInfoObj);
                } else {
                    Toast.makeText(getApplicationContext(), "Couldn't find a devices that matches your input", Toast.LENGTH_SHORT).show();
                }
        }

    }

};

private void saveValues(Map<String, Short> rssiMapper) {
    Log.d("Output", rssiMapper.toString());
}


private boolean havePermissions() {
    return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED;
}
private void requestPermissions() {
    ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_CODE);
    Log.d("TAG", "requestPermissions");
}

}

当我运行应用程序时,应用程序已停止,出现如下错误

  java.lang.RuntimeException: Error receiving broadcast Intent { act=android.bluetooth.device.action.FOUND flg=0x10 (has extras) } in com.example.scanbt.MainActivity$2@9f5f3be
    at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$-android_app_LoadedApk$ReceiverDispatcher$Args_52226(LoadedApk.java:1329)
    at android.app.-$Lambda$FilBqgnXJrN9Mgyks1XHeAxzSTk.$m$0(Unknown Source:4)
    at android.app.-$Lambda$FilBqgnXJrN9Mgyks1XHeAxzSTk.run(Unknown Source:0)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6944)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
 Caused by: java.lang.NumberFormatException: For input string: "chathurika-HP"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.lang.Double.parseDouble(Double.java:539)
    at java.lang.Double.valueOf(Double.java:503)

我能做些什么来避免NumberFormatException

共有1个答案

漆雕彬彬
2023-03-14
String deviceName = y.getText().toString() + "";

这就解决了你的问题。如果再次出现这种错误,请像这样更改try-catch块,

try {

 }catch(Exception e){}

您也可以这样更改:

device.getName().equals(deviceName+"")
 类似资料: