Unable to connect BlackBerry phone with Bluetooth SPP device - blackberry

I am trying to connect to a bluetooth device from the blackberry 9900 phone using the following code;
public final class AppMainScreen extends MainScreen {
private BluetoothspInfo[] spInfo;
private StreamConnection bConn;
private DataInputStream diStream;
private String text;
public AppMainScreen() {
spInfo = BluetoothSerialPort.getSerialPortInfo();
try {
bConn = (StreamConnection) Connector.open(
spInfo[0].toString(), Connector.READ);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
UiApplication.getUiApplication().invokeLater(new TextScanner());
}
// ...
// ...
// ...
}
But its always throwing the exception java.io.IOException: Unable to connect. I am not able to get the full trace.
What is the problem here, can anybody please point me in the right direction.
I am using the BlackBerry Java on BlackBerry Eclipse Plugin with Platform version 4.5.

Related

IncompatibleClassChangeError on Android Things

After updating to the latest Android Things preview, my app is crashing when
setting a callback on by button GPIO. I have the following button callback defined:
private class ButtonCallback extends GpioCallback {
#Override
public boolean onGpioEdge(Gpio gpio) {
boolean isPressed = false;
try {
isPressed = gpio.getValue();
} catch (IOException e) {
Log.w(TAG, "Error", e);
}
if (isPressed) {
...
}
return true;
}
}
I am registering it with the GPIO in the application as follows:
Gpio button = ...;
try {
button.registerGpioCallback(new ButtonCallback());
} catch (IOException e) {
Log.w(TAG, "Error configuring GPIO pins", e);
}
When I run my app, I get an IncompatibleClassChangeError and the app crashes:
java.lang.IncompatibleClassChangeError: Superclass com.google.android.things.pio.GpioCallback of com.google.android.things.example.MainActivity$ButtonCallback is an interface (...)
This code was working before, why has this started happening after the update?
Starting in Preview 7, many of the Peripheral I/O interfaces were converted from
abstract classes to interfaces. This was done to better facilitate testability
in apps, as interfaces are easier to mock.
Be sure to update your app to use the Preview 7 SDK:
dependencies {
compileOnly 'com.google.android.things:androidthings:0.7-devpreview'
}
Then modify your callback to implement the interface instead:
private class ButtonCallback implements GpioCallback {
#Override
public boolean onGpioEdge(Gpio gpio) {
boolean isPressed = false;
try {
isPressed = gpio.getValue();
} catch (IOException e) {
Log.w(TAG, "Error", e);
}
if (isPressed) {
...
}
return true;
}
}
Review the Android Things API reference
to verify if any of the other APIs you are calling have changed.

Try to connect to MQTT Server with a Broadcast Receiver when WiFi is connected (Paho)

I have a Broadcast receiver that checks WIFI_STATE_CHANGE to see if I have connected to a certain WiFi network. For example if I am coming home, I want a certain MQTT message to be sent. The problem I have is that it connects and sends the MQTT message, only when run the app the first time.
Process:
If I build the application and run it on the device and it recognised my home WiFi it sends the message.
I turn off Wifi from the device, and turn it back on again.
I get "Failure" which is a message when the MQTT connection to the server could not be established.
What I would need is that after I reconnect to the network, instead of "Failure" to get "Connected" but somehow it never happens...what could be wrong?
PS. I think it has to do with the fact that when WiFi is detected, the Broadcast Receiver runs the connection code, although Internet is not available at that point of time (obtaining IP etc.)
Here is the code of the Broadcast receiver:
package me.app.comehomedemo;
import ...
public class SynchronizeBroadcastReceiver extends BroadcastReceiver {
MqttAndroidClient client;
static String MQTTHOST = "myhost";
static String USERNAME = "myusername";
static String PASSWORD = "mypassword";
static String topicStr = "/topic/mac/control";
static String payload = "1";
#Override
public void onReceive(final Context context, Intent intent) {
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (info.isConnected()) {
WifiManager wifiManager = ( WifiManager ) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
Toast.makeText(context, String.valueOf(ip), Toast.LENGTH_SHORT).show();
String ssid = wifiInfo.getSSID();
if (ssid.equals("\"mySSID\"")) {
String clientId = MqttClient.generateClientId();
client = new MqttAndroidClient(context.getApplicationContext(), MQTTHOST, clientId);
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(USERNAME);
options.setPassword(PASSWORD.toCharArray());
// options.setAutomaticReconnect(true);
try {
IMqttToken token = client.connect(options);
token.setActionCallback(new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken asyncActionToken) {
// We are connected
Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
try {
client.publish(topicStr, payload.getBytes(), 0, false);
} catch (MqttException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
// Something went wrong e.g. connection timeout or firewall problems
Toast.makeText(context, "Failure", Toast.LENGTH_SHORT).show();
}
});
} catch (MqttException e) {
e.printStackTrace();
}
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer mp = MediaPlayer.create(context.getApplicationContext(), notification);
mp.start();
}
}
}
}
I have managed to solve it by waiting 2 seconds and then running the task. Used this solution and it worked. I had to wait for the Internet connection to get ready!
Since waiting 2 seconds has solved your problem, then it might be that the Wifi broadcast comes too early, before there is a connection established (like DHCP gives your phone IP and establishes the routes) for the MQTT connect and publish packets to be properly delivered.
But what happens if some other user needs to wait 10 and not 2 seconds?
My suggestion is to set the automatic reconnect option in MqttConnectOptions and then use the connection callback to publish the needed info to the broker and finally disconnect in publish callback:
private IMqttActionListener mConnectCallback = new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken token) {
try {
client.publish(topicStr, new MqttMessage(payload.getBytes()), null, mPublishCallback);
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void onFailure(IMqttToken token, Throwable ex) {
}
};
private IMqttActionListener mPublishCallback = new IMqttActionListener() {
#Override
public void onSuccess(IMqttToken token) {
// TODO disconnect
}
#Override
public void onFailure(IMqttToken token, Throwable ex) {
}
};
MqttAndroidClient client = new MqttAndroidClient(context, MQTTHOST, "my_id");
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(USERNAME);
options.setPassword(PASSWORD.toCharArray());
options.setAutomaticReconnect(true);
client.connect(options, null, mConnectCallback);

Connection being made, but content is unable to be retrieved from web service

public class ConsumeFactoryThread extends Thread {
private String url;
private HttpConnection httpConn;
private InputStream is;
private CustomMainScreen m;
private JSONArray array;
public ConsumeFactoryThread(String url, CustomMainScreen m){
System.out.println("Connection begin!");
this.url = url;
this.m = m;
}
public void finished(){
m.onFinish(array);
}
public void run(){
myConnectionFactory connFact = new myConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
System.out.println("Connection factory!");
if(connDesc != null)
{
System.out.println("Connection not null!");
httpConn = (HttpConnection) connDesc.getConnection();
is = null;
try
{
final int iResponseCode = httpConn.getResponseCode();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
System.out.println("Connection in run!");
// Get InputConnection and read the server's response
InputConnection inputConn = (InputConnection) httpConn;
try {
is = inputConn.openInputStream();
System.out.println("Connection got inputstream!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = null;
try {
data = IOUtilities.streamToBytes(is);
System.out.println("Connection got data!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = new String(data);
System.out.println("Connection Data: "+result);
try {
array = new JSONArray(result);
//finished();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
catch(IOException e)
{
System.err.println("Caught IOException: " + e.getMessage());
}
}
}
}
I'm using the blackberry torch 9800 simulator and hardware device for testing.
In the simulator I cannot retrieve the data over wifi, even though the connection to wifi is found. It works when the mobile network is enabled.
Now, when I replace my web service with the Twitter api, I get the data regardless of transport type. I tried adding ;deviceside=false to my url, but nothing. It's not https or anything.
I just want my web service accessed! I know nothing about this mds,bis,bes,bis_b junk.
EDIT:
Jeez. I'm realizing it may be my site. Not using the web service and just retrieving the page, www.example.com, I get nothing. But, google.com or any other site I use retrieves the html. Am I missing headers!?!
Try appending ;interface=wifi to the end of your URL, this will force the simulator to use your simulated Wi-Fi connection, which is your PC's network connection.
You will need to have setup Wi-Fi on the simulator by going to Manage Connections->Set Up Wi-Fi Network, then connect to Default WLAN Network.

QR Code Live Scanning in BlackBerry OS 6.0

I want to Implement a QR Code Reader In BlackBerry Os 6. I try the following Code On the Basis of KB Article How to use the Barcode API.
public class ScanScreen extends MainScreen implements BarcodeDecoderListener
{
private LabelField match;
private BarcodeScanner scanner;
public ScanScreen()
{
match = new LabelField("Scanning...");
add(match);
Vector supported = new Vector();
supported.addElement(BarcodeFormat.QR_CODE);
Hashtable hints = new Hashtable();
hints.put(DecodeHintType.POSSIBLE_FORMATS, supported);
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
BarcodeDecoder decoder = new BarcodeDecoder(hints);
try
{
scanner = new BarcodeScanner(decoder, this);
add(scanner.getViewfinder());
scanner.startScan();
}
catch (Exception e)
{
e.printStackTrace();
match.setText("Exception");
invalidate();
}
}
public void barcodeDecoded(String rawText)
{
match.setText("Found: " + rawText);
invalidate();
}
public void close()
{
try
{
scanner.stopScan();
}
catch (Exception e)
{
e.printStackTrace();
}
super.close();
}
}
The Code not working. It do not recognize QR codes. I try to focus on different QR codes. But it not decode The qrcodes.Also It not Thrown Any exceptions. Please Help me....
I tried using these Devices: BB pearl 9105 and BB Storm 9530
See the sample from the following link.It will help you
http://aliirawan-wen.blogspot.com/2011/05/barcode-scanner-for-blackberry-os-50.html
I'm painfully new to BB development, but I notice you pass "this" as the decoderlistener parameter, perhaps that's causing a problem?
BarcodeDecoder decoder = new BarcodeDecoder(hints);
BarcodeDecoderListener decoderListener = new BarcodeDecoderListener()
{
public void barcodeDecoded(String rawText)
{
displayMessage(rawText);
}
};
try
{
scanner = new BarcodeScanner(decoder, decoderListener)
add(scanner.getViewfinder());
scanner.startScan();
}
catch (Exception e)
{
e.printStackTrace();
match.setText("Exception");
invalidate();
}
}

How can I get FilePicker working properly on certain BlackBerry handsets?

I'm implementing a Filepicker in my app to allow users to choose photos from their phones. The code I'm using is as follows:
Calling the Filepicker:
try
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
FilePicker fp = FilePicker.getInstance();
fileListener = new FilePickListener();
fp.setListener(fileListener);
fp.show();
}
});
}
catch (Exception e)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Please check your data card..");
}
});
}
And the method to get the filename in my FilePickListener:
public void selectionDone(String str)
{
this.currFileName = str;
int index = str.lastIndexOf('/');
Dialog.alert("Filename: "+str.substring(index+1).trim());
}
This works perfectly in most handsets that I've tried it on (which have been a mix of handsets with some running OS5 and some running OS6). But on some, like the 8900 (running OS v5.0.0.411) it doesn't work properly. The Filepicker gets called and appears, but when any file gets selected, the selectionDone method doesn't get called. I've tested it on two separate 8900s and both have the same problem.
Does anyone have an idea why it works on certain handsets and not other?
You are a victim of a known RIM issue: FilePicker throws ControlledAccessException.
The issue is marked as "Fixed". However there is no info in which OS version they fixed it. (Is it so difficult to tell such a useful info?)
But from the comments to the issue:
We experience the very same issue with OS 5.0.0.321 on a Bold 9700. However, the issue does NOT appear on OS 5.0.0.464
so my guess would be they fixed it in OS 5.0.0.464. But that's not the end - in OS 6 FilePicker appears broken in early versions of OS 6 again. The conclusion - just don't use it. Use a custom file browser screen to pick a file. There is a sample in SDK 4.7.0 named FileExplorerDemo, check it for implementation details.
This is a known issue. FilePicker does not open on some devices and return an error, like the 8900 device. You can catch this error on some devices by adding the catch (Error e) { }
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
FilePicker fp = FilePicker.getInstance();
fileListener = new FilePickListener();
fp.setListener(fileListener);
fp.show();
}
});
}
catch (Exception e)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Please check your data card..");
}
});
}
catch (Error e)
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("This device does not support File Picker");
}
});
}

Resources