BluetoothDevice getmethod NoSuchMethodException - android

I am creating new connection class for Bluetooth device on Android Studio.I cant figure out why thrown exception in design time.
public ConnectingThread(BluetoothDevice device,MainActivity activity,BluetoothAdapter adapter) {
mainActivity=activity;
bluetoothAdapter=adapter;
BluetoothSocket temp = null;
bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}

The line:
temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
has the potential to throw a NoSuchMethodException. You do not have a catch block to handle this exception. So you have to add another catch block under your existing catch block as follows:
catch(NoSuchMethodException e){
//Insert code here
}
Also, that line of code will later throw the following exceptions so it is best to handle them as well: IllegalAccessException, and InvocationTargetException. Thus, your try-catch blocks should be as follows:
try {
temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
} catch (IOException e) {
e.printStackTrace();
}
catch(NoSuchMethodException ex){
//Insert code here
}
catch(IllegalAccessException e){
//Insert code here
}
catch(InvocationTargetException e){
//Insert code here
}
Alternatively, you could handle every single exception with the general Exception class. In this case, your code should look something like this:
try {
temp = (BluetoothSocket)bluetoothDevice.getClass().getMethod("createRfcommSocket",int.class).invoke(bluetoothDevice,1);
} catch (Exception e) {
//Enter code here
}

Related

nullpointererror + unable to bind sockets

This works in the earlier version of my app, which is basically the exact same code. The only difference is the current app uses a higher build tools and sdk compiled version, would that cause the code to error? Also the app extends FragmentActivity instead of Activity now.
One of the errors is a null pointer exception, which from logcat is due to the ServerSocket (ss) being null.
The other error is libcore.io.ErrnoException: bind failed: EADDRINUSE (Address already in use) at the line 8 in the snippet
I have tried implementing ss.setReuseAddress(true), however it doesn't work due to an unresolved symbol issue?
Any idea or pointers would be greatly appreciated!
class CommsThread implements Runnable {
private volatile boolean stopFlag = false;
private ServerSocket ss ;
private static final int SERVERPORT = 6000;
public void run() {
Socket s = null;
try {
ss = new ServerSocket(SERVERPORT); <-- bind error here
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG,"IO Error here"); <--- this is printed in log
}
try {
s = ss.accept(); <----- nullpointer exception here
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
myHandler.sendEmptyMessage(0);
while(stopFlag == false){
try {
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())), true);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
out.printf(String.valueOf(d.format(accel[0]))+"\t"+String.valueOf(d.format(accel[1]))+"\t"+String.valueOf(d.format(accel[2])) + "\tAccelerometer" + "\n");
out.printf(String.valueOf(d.format(gyro[0]))+"\t"+String.valueOf(d.format(gyro[1]))+"\t"+String.valueOf(d.format(gyro[2]))+ "\tGyroscope" + "\n");
out.printf(String.valueOf(d.format(magnet[0]))+"\t"+String.valueOf(d.format(magnet[1]))+"\t"+String.valueOf(d.format(magnet[2]))+"\tMagnetometer"+ "\n\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if( s==null)
{
stopComms();
}
*/
}
}
The NPE is due to nothing but your own faulty code structure. The real issue is the bind exception, which means something else is listening at port 6000, possibly a prior instance of the same application. Fix that, or use another port.

Why cant Android open connection with RN-41 Roving network device?

I am just trying to open socket with RN-41 microchip, as far as I know the chip listens for incoming connections all the time, is discoverable, etc.. Why do socket gets always closed directly?
private class Connect extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public Connect(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("EB46DDA9-0D00-4C34-9365-D6AA6C111D1C"));
Log.v("SOCKET SUCCESS", "HAST SOCKET");
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
try {
mmSocket.connect();
Log.v("SOCKET SUCCESS", "VERBUNDEN");
} catch (IOException connectException) {
Log.v("SOCKET SUCCESS", "KEINE VERBINDUNG");
try {
mmSocket.close();
Log.v("SOCKET SUCCESS", "SOCKET CLOSED");
} catch (IOException closeException) {
Log.v("SOCKET SUCCESS", "SOCKET CLOSE FAIL");
}
return;
}
}
I've been googling all day long and got things work. Unfortunately I still dont know why and how it works, but it works perfectly. I changed my Connect class constructor code like this:
public Connect(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
//try {
// MY_UUID is the app's UUID string, also used by the server code
//ParcelUuid[] ids = device.getUuids();
//UUID deviceID = ids[0].getUuid();
//tmp = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));//deviceID);//UUID.fromString("EB46DDA9-0D00-4C34-9365-D6AA6C111D1C"));
Method m = null;
try {
m = mmDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[] { int.class });
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
tmp = (BluetoothSocket)m.invoke(mmDevice, Integer.valueOf(1));
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.v("SOCKET SUCCESS", "HAST SOCKET");
//} catch (IOException e) { }
mmSocket = tmp;
}
Source:
Android Bluetooth SPP with Galaxy S3
P.s. If somebody would have a bit time to explain code above, I would appreciate it a lot. Thank you.

How to get message from Exception?

Following is my piece of code:\
public void LoadProjectFile(String Filename) throws Exception
{
// m_Renderer.m_Project=new Project();
refresh_project();
m_Renderer.m_SelectedProjectPath = Filename;
try {
m_Renderer.m_Project.load_file(Filename);
}
catch (Exception e)
{
//Exception a = e.getMessage();
String a= e.getMessage();
throw new Exception(a);
}
//AppFuncs.m_GisProject=m_Renderer.m_Project;
}
try
{
Map.this.mGLView.LoadProjectFile(AppFuncs.g_path);
Map.this.mGLView.requestRender();
}
catch (Exception e)
{
br=1;
b=e.getMessage();
}
Load project file throws an exception which i recieve in Map class. This exception contains message: Java.lang.exception: java.lang.exception: file not found.
I want to show only "File not found" message. so how should i get this message out from an exception?
Catch all types of exceptions instead of base Exception:
try {
m_Renderer.m_Project.load_file(Filename);
}
catch (FileNotFoundException e)
{
String a= "File not found"
throw new Exception(a);
}
catch (SomeOhterException e){
String a= "Some other message"
throw new Exception(a);
}
//at the end, but it shouldn't be necessary
catch (Exception e){
String a= "Something happend we don't know what"
throw new Exception(a);
}
Shortly: Use different class for different exception to show correct information rahter than using exception message.
Just catch the FileNotFoundException instead of an Exception.
For example:
try {
//whatever
} catch (FileNotFoundException e) {
System.out.println("File not found");
}

Socket.connect doesn't throw exception in Android

If I put a nonsense url no exception is thrown and none of the rest of my code is executed not even the rest of the asynctask that called the method that connects.
try {
socketCliente.connect(new InetSocketAddress("f", port), 2000);
} catch (UnknownHostException e) {
getError("Host doesn't exist");
return -1;
} catch (IOException e) {
getError("Could not connect: The host is down");
return -1;
}
Add another catch Statement.
catch ( Exception e ) {
Log.d(TAG, e.getMessage(),e);
Toast.makeText(getApplicationContext(), "Unexpected Error:" + e.getMessage(), Toast.LENGTH_LONG).show();
}
This will write to the log and pop up a toast to tell you what's going on.
It's very strange, can you add two more lines as follows and see what you get.
Also, in the log, pay attention to the time difference between those two lines.
try {
Log.w("SOCKET", "Trying to connect...");
socketCliente.connect(new InetSocketAddress("f", port), 2000);
Log.w("SOCKET", "Connected. No exception");
} catch (UnknownHostException e) {
getError("Host doesn't exist");
return -1;
} catch (IOException e) {
getError("Could not connect: The host is down");
return -1;
}

Problem in connection code

this is my class to connect and send commands to server i try separate connect code in method
but when i test the (SocketConnect) method i found it doesn't work.
my code
public class ConnAndSend {
static Socket socket = null;
static void SendCommand(String cmnd) {
DataOutputStream dataOutputStream = null;
try {
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(cmnd);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
};
}
// method to connect to server
static void SocketConnect(String SrvrIP,int SrvrPrt) {
// Socket socket = null;
try {
socket = new Socket(SrvrIP, SrvrPrt);
} catch (IOException e) { e.printStackTrace();}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
}
Remove the static modifier!!
Remove all the occurances of the word static
In your code:
socket = new Socket(SrvrIP, SrvrPrt);
} catch (IOException e) { e.printStackTrace();}
finally{
if (socket != null){
try {
socket.close();
you are closing the socket in finally (why?) this is wrong also!
Have you made sure your manifest file has the correct permissions?
<uses-permission android:name="android.permission.INTERNET" />
It looks like you are closing the socket before you even get a chance to use it or you are'nt calling SocketConnect before . Do you see how you you make the socket, then you close it?
socket = new Socket(SrvrIP, SrvrPrt);
} catch (IOException e) { e.printStackTrace();}
finally{
if (socket != null){
try {
socket.close();
You need to make the socket, use it to connect in your SendCommand, then close it. I'm not quite sure why you need to keep the two separate, but I believe that is your problem, you are calling close before you use the socket to connect or you simply aren't making the socket and SendCommand is using "null" to connect.

Categories

Resources