ClassCastException with handleMessage - bluetooth

Debugging bit of code for bluetooth connection receive string etc. However, seem to be getting a ClassCastException at the line of code
String read_Message = (String) msg.obj;
But if I was to use my previous bit of code and collect the bytes and place into a string runs but doesn't collect all the data in one string.
Have I not cast something or missed something cause I know I'm missing something but can't see it.
If any more code is required I will place up, everything else is working
Thanks for any help
// The Handler that gets information back from the BluetoothService
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case MESSAGE_STATE_CHANGE:
// if (D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1)
{
case BluetoothService.STATE_CONNECTED:
break;
case BluetoothService.STATE_CONNECTING:
//mTitle.setText(R.string.title_connecting);
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
//mTitle.setText(R.string.title_not_connected);
break;
}
break;
case MESSAGE_WRITE:
//code to be entered here
break;
case MESSAGE_READ:
//Previous code
//byte[] read_Buf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
//String read_Message = new String(read_Buf, 0, msg.arg1);
String read_Message = (String) msg.obj;
if (mSmokeReadingArrayAdapter.isEmpty())
mSmokeReadingArrayAdapter.add("");
mAdapter_Text.set(0, mAdapter_Text.get(0).toString() + read_Message);
mSmokeReadingArrayAdapter.notifyDataSetChanged();
organiseString(read_Message);
break;
case MESSAGE_DEVICE_NAME:
//code to be entered here
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show(); // shows 'alert' messages
break;
}
}
};

Problem solved. It wa to do with the bluetooth service code that had been defined as a byte array rather than string

Related

Call multiple classes without switch-case or if-else

I want to know weather is is possible or not, a way to call different classes on the basis of an integer value without conditional statements like switch case?
What I am having is:
int val = // getting some value here from a method
String data = // getting some value here from a method
switch(val)
{
case 1:
{
new TempClass1(data);
break;
}
case 2:
{
new TempClass2(data);
break;
}
}
What I want is like:
int val = // getting some value here from a method
String data = // getting some value here from a method
new TempClass(val, data);
This should call the object of TempClass1 or TempClass1 as per "val"
Any help will be appreciated.
Maybe use a Factory for the classes, assuming your two classes share a base class named TempBaseClass:
class TempClassFactory {
static public TempBaseClass getTempClass(int val, String data)
{
switch(val)
{
case 1:
{
return new TempClass1(data);
break;
}
case 2:
{
return new TempClass2(data);
break;
}
default:
throw new Exception("Bad value");
}
}
}
int val = // getting some value here from a method
String data = // getting some value here from a method
TempClassFactory::getTempClass(val, data);

Microsoft Bot Framework won't send multiline messages

So I've built this bot that should respond to it's user with status messages. I want to make these messages rather clean and therefore wanted to start each new property with a new line. Only problem is that when I do this, the bot just prints the first few lines.
So this is the code I've got, I've made sure that the data is actually there.
internal static string DeviceInformation(Device device)
{
StringBuilder sb = new StringBuilder();
sb.Append($"[Name]: {device.Name}\n\n");
sb.Append($"[Location]: {device.LocationName} \n\n");
if (device.ContactLost)
{
sb.Append("[Status]:Offline!\n\n");
sb.Append($"[Time Offline]: {device.ContactLostTime} \n\n");
sb.Append($"[Time Offline]: {device.ContactLostTime} \n\n");
}
else
{
sb.Append("[Status]:online! \n\n");
}
return sb.ToString();
}
internal static string DeviceInformation(Device device, DeviceHistory statistic)
{
StringBuilder sb = new StringBuilder(DeviceInformation(device));
sb.Append($"[Time]: {statistic.CreatedTimeStamp} \n\n");
sb.Append($"[Signal]: {statistic.SignalStrength} \n\n");
sb.Append($"[Battery]: {statistic.BatteryLevel} \n\n");
Debug.WriteLine("TOSTRING " + sb.ToString());
return sb.ToString();
}
The next last line prints out this:
TOSTRING [Name]: Restroom 1
[Location]: Floor 2
[Status]:online!
[Time]: 16/05/2017 22:23:45
[Signal]: -88
[Battery]: 60
Now the bot just prints:
[Name]: Restroom 1
[Location]: Floor 2
[Time]: 16/05/2017 22:23:45
If I remove all the linebreaks \n and put everything on the same row, the bot prints the whole message.
Anyone having any idea what I can do about this?
Interesting behavior. I was able to reproduce it... I'm still looking for the root cause of the issue, however, I found a workaround for you, that is using bullets.
I updated your code in the following way:
internal static string DeviceInformation(Device device)
{
StringBuilder sb = new StringBuilder();
sb.Append($"• [Name]: {device.Name}\n\n");
sb.Append($"• [Location]: {device.LocationName}\n\n");
if (device.ContactLost)
{
sb.Append("[Status]:Offline!\n\n");
sb.Append($"[Time Offline]: {device.ContactLostTime}\n\n");
sb.Append($"[Time Offline]: {device.ContactLostTime}\n\n");
}
else
{
sb.Append("• [Status]:online!\n\n");
}
return sb.ToString();
}
internal static string DeviceInformation(Device device, DeviceHistory statistic)
{
StringBuilder sb = new StringBuilder(DeviceInformation(device));
sb.Append($"• [Time]: {statistic.CreatedTimeStamp}\n\n");
sb.Append($"• [Signal]: {statistic.SignalStrength}\n\n");
sb.Append($"• [Battery]: {statistic.BatteryLevel}\n\n");
Debug.WriteLine("TOSTRING " + sb.ToString());
return sb.ToString();
}
With that, it's working as expected in the emulator:

C# Visual Studio's Text to Answer

This is kinda of a Noobie what about I am gonna ask but I am trying to get my Program to work I do not know how to Ask a question in a text box hit the button and it outputs the answer; I Have been researching this for a while I know how to get everything else to work.
So a simple Console app example:
static void Main()
{
bool exit = false;
string response;
while (!exit)
{
Console.Write("Command ('Exit' to end): ");
response = Console.ReadLine();
switch (response)
{
case "Hey":
Console.WriteLine("Welcome");
break;
case "unicorns":
Console.WriteLine("...are awesome!");
break;
case "Exit":
exit = true;
break;
default:
Console.WriteLine("Unrecognized command!");
break;
}
}
Console.Write("Press Enter to Quit");
Console.ReadLine();
}

E_SCN_READINCOMPATIBLE Notification error thrown while scanning bar code on MC9090G

I'm using EMDK 2.5 (VS2008 and VC# and .NetCF3.5) Barcode2 class from the library to write a sample application to scan bar codes. I followed the samples available in EMDK namely CS_Barcode2Sample1 project.Every time I hardware trigger the scan the notification "E_SCN_READINCOMPATIBLE" is thrown and not able to retrieve the scanned data. The documentation doesn't say much about the cause of E_SCN_READINCOMPATIBLE notification and no luck from Google search. I tried several options including making use of Symbol.Barcode and the outcome is same.
I also tried EMDK 2.3 but the result is same.
I've pasted the whole code here....
public partial class Form1 : Form
{
private Barcode2 myBarcode2 = null;
public Form1()
{
InitializeComponent();
InitBarcode();
}
public bool InitBarcode()
{
// If the Barcode2 object is already initialized then fail the initialization.
if (myBarcode2 != null)
{
return false;
}
else // Else initialize the reader.
{
try
{
Symbol.Barcode2.Device[] AvailableDevices = Symbol.Barcode2.Devices.SupportedDevices;
if (AvailableDevices.Length == 0)
{
return false;
}
if (AvailableDevices.Length == 1)
{
//get the first available scanner in the list
Symbol.Barcode2.Device MyDevice = AvailableDevices[0];
// Create the reader, based on selected device.
myBarcode2 = new Barcode2(MyDevice);
// Attach a scan notification handler.
//this.myScanNotifyHandler = new Barcode2.OnScanHandler(myBarcode2_ScanNotify);
myBarcode2.OnScan += myBarcode2_ScanNotify;
// Attach a status notification handler.
//this.myStatusNotifyHandler = new Barcode2.OnStatusHandler(myBarcode2_StatusNotify);
myBarcode2.OnStatus += myBarcode2_StatusNotify;
myBarcode2.Config.TriggerMode = TRIGGERMODES.HARD;
// Submit a scan.
myBarcode2.Scan(5000);
}
}
catch (OperationFailureException ex)
{
MessageBox.Show("Exception Raised 1");
return false;
}
catch (InvalidRequestException ex)
{
MessageBox.Show("Exception Raised 2");
return false;
}
catch (InvalidIndexerException ex)
{
MessageBox.Show("Exception Raised 3");
return false;
}
}
return false;
}
private void myBarcode2_ScanNotify(ScanDataCollection scanDataCollection)
{
// Checks if the BeginInvoke method is required because the OnScan delegate is called by a different thread
if (this.InvokeRequired)
{
// Executes the OnScan delegate asynchronously on the main thread
this.BeginInvoke(new Barcode2.OnScanHandler(myBarcode2_ScanNotify), new object[] { scanDataCollection });
}
else
{
// Get ScanData
ScanData scanData = scanDataCollection.GetFirst;
int i;
switch (scanData.Result)
{
case Symbol.Barcode2.Results.SUCCESS:
String str = scanData.Text;
myBarcode2.Config.TriggerMode = TRIGGERMODES.HARD;
myBarcode2.Scan(5000);
break;
case Symbol.Barcode2.Results.E_SCN_READTIMEOUT:
break;
case Symbol.Barcode2.Results.CANCELED:
break;
case Symbol.Barcode2.Results.E_SCN_DEVICEFAILURE:
i = 93;
break;
default:
if (scanData.Result == Symbol.Barcode2.Results.E_SCN_READINCOMPATIBLE)
{
// If the failure is E_SCN_READINCOMPATIBLE, exit the application.
MessageBox.Show("Fatal Error");
this.Close();
return;
}
break;
}
}
}
private void myBarcode2_StatusNotify(StatusData statusData)
{
// Checks if the Invoke method is required because the OnStatus delegate is called by a different thread
if (this.InvokeRequired)
{
// Executes the OnStatus delegate on the main thread
this.Invoke(new Barcode2.OnStatusHandler(myBarcode2_StatusNotify), new object[] { statusData });
}
else
{
int i;
switch (statusData.State)
{
case States.IDLE:
break;
case States.READY:
break;
default:
break;
}
}
}
}
}
I've went thru this recently also, as I observed, it probably due to the scanner device is occupied by other application, where the scan request has been queued already, you can go to memory management, and kill the suspect app, and try your app again.
Refer to the Symbol FAQ

Get pressed keys in J2ME with GameCanvas

I would like to get whether (for example) the 3 key is pressed (KEY_NUM3).
I have tried getKeyStates but it only detects the game action keys.
How could I get the states of non-game action keys?
(I have overridden the keyPressed and keyReleased functions of Canvas and storing the key states in an array (I'm using a Vector for storing but I think could store them in an array too, if that's the problem), but this does not seem to be very nice)
in your keypressed use the keyCode passed in like so
protected void keyPressed(int keyCode)
{
//try catch getGameAction as can legally throw an exception
int gameAction = getGameAction(keyCode);
switch(gameAction)
{
case UP:
break;
case DOWN:
break;
case LEFT:
break;
}
switch(keyCode)
{
case KEY_NUM1:
break;
case KEY_NUM2:
break;
case KEY_NUM3;
break;
}
}
I suppose that can be
something like the code below
int key=getKeyStates();
// i mean keyStates();
if((key&down_pressed)!=0)
{
//do movements
}
but can be
if((key & Canvas.key_num3)!=0)
{
//do something
}
//you can set the super() to true in the constructor

Resources