Writing to a file in BlackBerry - blackberry

Hey Folks,I have pasted my code here. Dialog.inform contains a 'long' value which is a player's score. If i want to write it to a file, i need to convert it to int of byte.I am getting junk value written into the file.Can anyone help me out with this? I want to print the content of (elapsed/34)
Dialog.inform("Congrats You scored : "+(elapsed/34));
try
{
FileConnection fc = (FileConnection)Connector.open("file:///SDCard/Rashmi.txt");
// If no exception is thrown, then the URI is valid, but the file may or may not exist.
if (!fc.exists())
{
fc.create(); // create the file if it doesn't exist
}
OutputStream outStream = fc.openOutputStream();
int lp=safeLongToInt(elapsed/34);
outStream.write("Rashmi".getBytes());
outStream.write(lp);
outStream.close();
fc.close();

Okay, since you're saving the score to a file presumably you want that score to be viewable as a string. When you view that file I'm guessing that you see the word "Rashmi" followed by one junk character. The reason the variable lp is not being printed correctly is because the string value of a number is different from its numerical value. For instance the binary value of 2 is 10 whereas the ASCII value for '2' is 00110010 (or 50 in decimal). When you call outStream.write(lp) this is printing the numerical value of lp rather than its string value. In short, you need to cast the numerical value to a string. Try something like this:
String text = "Rashmi" + (elapsed/34);
outStream.write(text.getBytes());

Related

Why do I get EXC_BAD_ACCESS when using %1$s for String(format:)

I have a localized string that looks like this:
String(format: "unable_to_reach".localized(), name) //name is a string. I have also tried just "x"
The key/value pair in the localize file looks like this:
"unable_to_reach" = "Unable to reach %1$s";
Now, sometimes this works, othertimes it crashes with the EXC_BAD_ACCESS error. Why is this? isn't %1$s supposed to be used for string values?
The format specifier %1$s is %s with a positional specifier of $1 inserted into it. %s is the format specifier for a null-terminated C string. If you instead pass it a Swift String, bad things will happen. Don't do that. (It will likely cause a buffer overflow if the Swift string does not contain any null bytes.)
You want %# (or %$1#, to preserve the positional specifier.)
See the document on string format specifiers for more information.
Edit:
BTW, you should think about using Swift string interpolation instead:
let unableToReach = "unable_to_reach".localized()
let final = "\(unableToReach) \(name)"
That is more "Swifty".
Note that if you want to use localized placeholders to allow for different word ordering in different languages, you really still need to use String(format:) and the %# (or %1# positional syntax) version.

Converting type string to long

I am trying to convert the type of string to long in the following code:
PaymentReceived = String.Format(new CultureInfo("en-IN", true), "{0:n}", t.PaymentReceived),
Here t.PaymentReceived is of type long, and the PaymentReceived is of type string but I want it to be of type long.
I am using this to convert the PaymentReceived value into comma separated value.
I am trying to do as of my knowledge like
PaymentReceived = Convert.ToInt64( String.Format(new CultureInfo("en-IN", true), "{0:n}", t.PaymentReceived))
But the error is Additional information: Input string was not in a correct format.
So please help me with another solution, thank you.
The formatter n, adds additional non-numeric characters. For en-IN culture, that means a number like 1000 ends up as 1,000.00.
The Convert.ToInt64 method requires that the string be 100% numeric, including no period, which might be fine for Convert.ToDecimal, but a long is not a float. Therefore, emphatically, your string is not formatted correctly, and the error is both obvious and correct. I'm not sure what your ultimate goal here is, but it makes no sense to convert a long to a formatted string and then immediately convert it back to a long, anyways.
Assuming you have only the string and you need to format it as a long, then you need to ensure that it's formatted as a long should be. That requires:
Split on the decimal point and take just the left side:
str = str.Split(new[] { '.' })[0];
Replace any commas with empty strings:
str = str.Replace(",", "");
That assumes you know the format will something like 1,000.00. Otherwise, you may want to use a regex to replace all non-numeric characters with an empty string, instead. However, you still need to split on the decimal. Otherwise, if you just removed all non-numeric characters from something like 1,000.00, then you'd end up with 100000, a number 100 times larger than the actual string number. Also, this is all dependent on the culture. Some cultures use , as the decimal separator and . and delimiter in large numbers. If you need to handle various cultures, you'll need to adjust accordingly.

NSSet full of NSStrings. When I print the set to the console, the results are unexpected

Here's what happens:
Internal database stuff: one class has a string property on it, that stores a phone number. This number is set using the code
CFBridgingRelease(ABMultiValueCopyValueAtIndex(ABRecordCopyValue(record, kABPersonPhoneProperty), 0));
My function: finds all objects of this type, and stores phone numbers of each object in an NSMutableSet.
Debug: I print the description of the set to the console.
Results:
Some of the set's objects look as expected (the majority actually): "+64 27 0124 975"
Some are missing quotation marks: 027 7824 565
Some have weird unicode symbols: "021\U00a0026\U00a017788"
My question:
Why the difference - what does it mean, and do I need to fix anything?
NSLog with %# – as I assume you are using – has some intelligence in how it presents NSStrings as it calls the description method. If the string has anything other than alphanumerics, such as the '+' or '\' above, it will use quotes. The string with unicode characters simply has its characters encoded as shown, and they are automatically converted into this lossless format. You should be able to convert it to something prettier for the console if you really need to with something like this:
NSLog(#"%#", [NSString stringWithCString:[myString.description cStringUsingEncoding:NSASCIIStringEncoding] encoding:NSNonLossyASCIIStringEncoding]);

Integer-String Parser

I am parsing an XML document, and when I try to save the String (data) that I am reading as an Integer, I found an exception.
Integer.parseInt(data)
I also tried changing the atribute type to Byte and trying on another way but it did not work.
{Byte.parseByte(data)}
More precisely, I am doing,
{message.setType(Integer.parseInt(data));}
I have also tried with valueOf and intValue and it did not work either.
messageType was both times (int or byte).
While I am parsing the XML, I print out data and it exactly has the value and lenght that I am expecting. (value:9, length:1)

Entering Text From Delphi To Word

I'm using Delphi XE2 and use the following code to enter the letter Y into a bookmark in a Word (2010) template.
Doc.Bookmarks.Item('NS').Range.InsertAfter('Y');
Except in the document, instead of the letter Y, the number 89 appears.
Is the fault likely to be from my code or in the Word document? Any direction gratefully received.
Your literal 'Y' is a character literal rather than a string string literal. The ASCII code for Y is 89.
So, you are passing a Char rather than a string. When Word needs to get a string representation of that integer it simply converts the integer 89 to its textual representation, the string '89'.
To get around the problem you can do this:
var
Text: string;
....
Text := 'Y';
Doc.Bookmarks.Item('NS').Range.InsertAfter(Text);
The idea is that we ensure that we pass a string to InsertAfter() rather than a character. Remember that InsertAfter() receives a variant parameter and so you do need to be careful about the type of the payload stored in the variant.

Resources