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;
}
Related
I have the following code to connect to a Bluetooth device:
class BiSymConnectThread extends Thread {
BluetoothDevice mDevice;
public BiSymConnectThread(BluetoothDevice device) throws SecurityException, NoSuchMethodException {
mDevice = device;
UUID uuid = mDevice.getUuids()[0].getUuid();
try {
biSymSocket = mDevice.createInsecureRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
Log.e("Error", "Could not connect!");
}
}
public void cancel() {
interrupt();
try {
Log.i("Treadmill", "in connect thread cancellation");
if (biSymSocket != null) {
biSymSocket.close();
}
} catch (IOException localIOException) {
Log.e("Treadmill", "exception + " + localIOException.getMessage());
}
}
public void run() {
try {
if (biSymSocket.isConnected()) {
biSymSocket.close();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new IOException();
}
}
biSymSocket.connect();
eventHandler.obtainMessage(MESSAGE_CONNECT_BISYM, 0, 0, "").sendToTarget();
BluetoothConnectionService.setSocket(biSymSocket);
BluetoothConnectionService.sendMessage(biSymSocket, "S");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Log.e("Error", "InterruptedException: " + e.getMessage(), e);
throw new IOException();
}
} catch (IOException e) {
Log.e("Error", "IOException: " + e.getMessage(), e);
eventHandler.obtainMessage(MESSAGE_ERRORCONNECT_BISYM, 0, 0, "").sendToTarget();
if (biSymSocket != null) {
try {
biSymSocket.close();
} catch (IOException e1) {
Log.e("Error", "Can't close socket!");
}
}
}
synchronized (this) {
biSymConnectThread = null;
}
}
}
If I attempt to reconnect to the device, I get the following error:
RFCOMM_CreateConnection - already opened state:2, RFC state:4, MCB state:5
In the other question asking about this error, someone mentions the isConnected() method. However, in my case, isConnected() returns false and the connection still fails.
Does anyone know what is the problem here? It appears this is some obscure error, since there doesn't seem to be anything on the web about this.
I am not able to join the room. I have gone through the documentation XMPP Instant Room Error
Here is how i am creating instant room:
try {
UserSearchManager usm = new UserSearchManager(Utils.connection);
List<DomainBareJid> services = usm.getSearchServices();
String roomjid = "myroom#" + services.get(0);
mucJid = JidCreate.entityBareFrom(roomjid);
Log.d(TAG, mucJid.toString());
// Create the nickname.
nickname = Resourcepart.from(roomjid);
Log.d(TAG, nickname.toString());
} catch (XmppStringprepException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
}
// Get the MultiUserChatManager
manager = MultiUserChatManager.getInstanceFor(Utils.connection);
// Get a MultiUserChat using MultiUserChatManager
MultiUserChat muc = manager.getMultiUserChat(mucJid);
// Create the room and send an empty configuration form to make this an instant room
try {
// Prepare a list of owners of the new room
Set<Jid> owners = JidUtil.jidSetFrom(new String[] { "54321#rahul", "12345#rahul" });
muc.create(nickname)
.getConfigFormManager()
.setRoomOwners(owners)
.submitConfigurationForm();
muc.sendConfigurationForm(new Form(DataForm.Type.submit));
muc.join(nickname);
EntityBareJid invitemucJid = JidCreate.entityBareFrom("12345#rahul");
muc.invite(invitemucJid, "testing");
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (MultiUserChatException.MucAlreadyJoinedException e) {
e.printStackTrace();
} catch (MultiUserChatException.MissingMucCreationAcknowledgeException e) {
e.printStackTrace();
} catch (MultiUserChatException.NotAMucServiceException e) {
e.printStackTrace();
} catch (XmppStringprepException e) {
e.printStackTrace();
} catch (MultiUserChatException.MucConfigurationNotSupportedException e) {
e.printStackTrace();
}
The MUC room is getting created successfully. But when i am checking through Invitation Listener and trying to join the room. It is giving error.
The Invitation listener code is as follow:
try {
Resourcepart nickname = Resourcepart.from(room.getRoom().toString());
room.join(nickname);
Log.d(TAG, "room status---> " + room.isJoined());
runOnUiThread(new Runnable() {
#Override
public void run() {
if (room.isJoined()) {
Toast.makeText(FriendListActivity.this, "Joined", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(FriendListActivity.this, "Not joined", Toast.LENGTH_SHORT).show();
}
}
});
} catch (XmppStringprepException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (MultiUserChatException.NotAMucServiceException e) {
e.printStackTrace();
}
Below is screen shot of the stack Trace
As per the documentation it says that the MUC room is locked. But I have created instant room along with default configuration.
Maybe it's a network error, I do somethings wrong if I use Wifi but get corrcet result with cellular network.
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
}
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");
}
As the title explains I'm having a hard time sending some data via Bluetooth to my PC. I'm trying to establish a connection with my android phone as client and my PC as server. When I'm trying to actually establish a connection via BluetoothSocket.connect() my phone prompts for a pin. After entering it my PC also prompts for the same pin but before I can enter it, the connect() - method throws an IOException. I assume that the connect()-Method times out before I can enter the correct pin on my PC, but how can I get it to wait long enough for me to enter the PIN?
EDIT: After Re-Pairing the PC with my Phone it worked, because the pairing dialog doesn't appear in my app anymore. If I unpair the PC and start my app, the pairing dialog pops up but disappears after several seconds and the socket throws an exception ("connection reset by peer"). Apparently the connection is reset before the pairing is done, but why?
Here is my code:
private void connectToDevice(BluetoothDevice device)
{
mBluetoothAdapter.cancelDiscovery();
BluetoothSocket socket = null;
try
{
socket = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101- 0000- 1000-8000-00805F9B34FB"));
}
catch (IOException e)
{
Log.e("HeliRemote", "Couldn't get socket.");
return;
}
try
{
socket.connect();
}
catch (IOException e)
{
try
{
socket.close();
}
catch (IOException e1)
{
Log.e("HeliRemote", "Couldn't close connection");
}
// That's the message I get in LogCat
Log.e("HeliRemote", "Couldn't connect to Socket.");
return;
}
Log.i("HeliRemote", "connected.");
}
I would be glad if somebody could give me any good words of advice regarding the problem.
Method m = mBluetoothDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
mBluetoothSocket = (BluetoothSocket) m.invoke(mBluetoothDevice, 1);
// mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
}
catch (IOException eConnectException)
{
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
} catch (SecurityException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (NoSuchMethodException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (IllegalArgumentException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (IllegalAccessException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
} catch (InvocationTargetException e) {
Log.d(TAG, "CouldNotConnectToSocket", e);
closeSocket(mBluetoothSocket);
}
}
try this one...