【问题标题】:How to avoid java.lang.NumberFormatException: For input string: " " Error [duplicate]如何避免 java.lang.NumberFormatException:对于输入字符串:“”错误 [重复]
【发布时间】:2020-09-27 00:05:07
【问题描述】:

我正在使用 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

【问题讨论】:

  • 我认为它不会出现在您提供的 catch 块中。因为显示的错误没有您在 catch 块中指定的字符串。我认为它在其他地方。
  • 完全同意@DaksheshGarambha。在我看来,在com.example.scanbt.MainActivity 的初始化中,您可能正在扫描所有蓝牙设备并在那里做某事。您发布的堆栈跟踪是整个堆栈跟踪吗?您能否发布所有格式化数字的 MainActivity 代码?
  • 添加了MainActivity的所有代码
  • 似乎问题出在Double distanceVal = Double.valueOf(x.getText().toString());。因此,对于 "How to Avoid java.lang.NumberFormatException",您可以在将输入文本输入valueOf()parseDouble() 等方法之前验证输入文本,或者将方法调用包围起来使用try-catch 块捕获方法文档中指定的异常。
  • 您的字符串不为空。引起:java.lang.NumberFormatException:对于输入字符串:“chathurika-HP”。这意味着它试图获得“chathurika-HP”的双重价值。我认为您的“距离”实体有该文本。

标签: java android numberformatexception


【解决方案1】:
String deviceName = y.getText().toString() + "";

这解决了您的问题。如果您再次遇到此类错误,请像这样更改您的 try catch 块,

try {

 }catch(Exception e){}

你也可以这样改变:

device.getName().equals(deviceName+"")

【讨论】:

  • 已更改。但还是同样的错误
  • 因为有时你的 textView 会得到 null 值,如果你使用 try {}catch{} 块,它可以解决你的问题。
猜你喜欢
  • 2017-09-02
  • 2013-06-27
  • 1970-01-01
  • 2013-09-16
  • 2020-03-11
  • 2015-04-19
  • 2018-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多