0

I am developing Bluetooth devices scanning android application with Android Studio. There is an input field and when the input name match with the scanned name I want to send the data to firebase. Below I have mentioned what I am doing

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");
}

}

When I run the app, App has stopped and there is an error like below

  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)

What can I do to avoid that NumberFormatException

6
  • 2
    I don't think it is going in the catch block you provided. Because the error shown doesn't have the string you specified in catch block. I think its somewhere else. Commented Jun 8, 2020 at 4:40
  • 1
    Completely agree with @DaksheshGarambha. To me it looks like in the init of your com.example.scanbt.MainActivity you're probably scanning for all Bluetooth devices and doing something there. Is your posted stacktrace the entire stacktrace? Could you post all code of MainActivity that formats numbers? Commented Jun 8, 2020 at 5:12
  • Added the all code of MainActivity Commented Jun 8, 2020 at 6:08
  • 2
    Seems like the problem is Double distanceVal = Double.valueOf(x.getText().toString());. So, as for "How to avoid java.lang.NumberFormatException" you'll either validate the input text before feeding it into methods like valueOf(), parseDouble() and such or you surround the method call with a try-catch block that catches the Exception(s) specified in the method's documentation. Commented Jun 8, 2020 at 8:00
  • 1
    Your String is not empty. Caused by: java.lang.NumberFormatException: For input string: "chathurika-HP". That means it is trying to get double value of "chathurika-HP". I think your "distance" entity has that text. Commented Jun 8, 2020 at 12:48

1 Answer 1

1
String deviceName = y.getText().toString() + "";

This solve your problem.If you again get this kind of error, change your try catch block like this,

try {

 }catch(Exception e){}

And also you can change this like this :

device.getName().equals(deviceName+"")
Sign up to request clarification or add additional context in comments.

2 Comments

changed. But still same error
Because sometimes your textView gets null value,if you use try {}catch{} block , it can resolve your problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.