How to write data into text file in BlackBerry? - blackberry

I want to know how to write text content to a file. I have a BasicEditField and a save button. When the button is clicked, then the BasicEditField text content should be saved into a text file, so I can retrieve that file later.

Here's a link to the specifics on FileConnection. Hope that helps! itsteju beat me to it. :)

/** File connection object */
FileConnection fc = (FileConnection) Connector.open(Const.FILE_PATH);
if (fc.exists() == false) {
fc.create();// create file at the location path
}
OutputStream os = fc.openOutputStream();
os.write(log.getBytes()); // Write text to file
os.close();
fc.close();// close the file connection object

Have a look at FileConnection interface for javax.microedition.io.file

Related

How to enable annotation in PDFJS viewer

I am using PDFJS and the viewer. I do however have the problem that annotation are not shown correctly like the are in the pdfs demo viewer https://mozilla.github.io/pdf.js/web/viewer.html.
Annotation correctly displayed in pdfs demo viewer:
Here is now it is displayed in my app using Chrome:
Here is how it is displayed I Safari using my app:
This is now I initialise the pdfs viewer:
function initPdfjs() {
// Enable hyperlinks within PDF files.
pdfLinkService = new (pdfjsViewer as any).PDFLinkService({
eventBus,
});
// Enable find controller.
pdfFindController = new (pdfjsViewer as any).PDFFindController({
eventBus,
linkService: pdfLinkService,
});
const container = document.getElementById('viewerContainer');
if (container) {
// Initialize PDFViewer
pdfViewer = new (pdfjsViewer as any).PDFViewer({
eventBus,
container,
removePageBorders: true,
linkService: pdfLinkService,
findController: pdfFindController,
});
// pdfViewer.textLayerMode = Utils.enableTextSelection() ? TextLayerMode.ENABLE : TextLayerMode.DISABLE;
pdfViewer.textLayerMode = TextLayerMode.ENABLE_ENHANCE;
// See https://github.com/mozilla/pdf.js/issues/11245
if (Utils.isIos()) {
pdfViewer.maxCanvasPixels = 4000 * 4000;
}
pdfLinkService.setViewer(pdfViewer);
return;
} else {
console.error(`getElementById('viewerContainer') failed`);
}
}
What do I need to do in order to get the annotations to display correctly in my app?
I got it working. I don't know if it is the right way, but I post it in case somebody can use it.
First I setup webpack to copy the content from ./node_modules/pdfjs-dist/web/images to my dist folder so the images got included. That solved all the display errors except {{date}}, {{time}}.
new CopyPlugin({
patterns: [
{ from: './node_modules/pdfjs-dist/web/images', to: '' },
{ from: './l10n', to: 'l10n' },
],
}),
To solve the {{date}}, {{time}} problem I set up a localisation service. I did that by copying the file ng2-pdfjs-viewer-master/pdfjs/web/locale/en-US/viewer.properties to ./l10n/local.properties in my project. Then it is copied to the dist folder by above webpack plugin. I then setup the l10n service in my pdfjs by adding this code:
// initialize localization service, so time stamp in embedded comments are shown correctly
l10n = new (pdfjsViewer as any).GenericL10n('en-US');
const dir = await l10n.getDirection();
document.getElementsByTagName('html')[0].dir = dir;
and added l10n to PDFViewer initialisation:
// Initialize PDFViewer
pdfViewer = new (pdfjsViewer as any).PDFViewer({
eventBus,
container,
removePageBorders: true,
linkService: pdfLinkService,
findController: pdfFindController,
l10n,
});
And now annotations is shown correctly:
What I find a bit weird is the date format. I used en-US as locale, so I would expect it to be mm/dd/yyyy (American way), but it is dd/mm/yyyy (like a dane would prefer it). I have tried to fool around with the date settings on my Mac and language settings in Chrome, but it doesn't look like it has any effect, so I don't know what to do if an American customer complains.

Flutter: Picking images as jpg/png instead of heic on iOS

How can I pick images directly as jpg or png on iOS?
If this feature isn't available: How can I convert it very fast and don't have to wait a long time?
Edit: I want to prevent picking .heic because I have to send it to an server, which handles jpg and png and not .heic
Thanks to Mohammad Assad Arshad!
It can be solved by pub.dev/packages/file_picker.
An additional explanation:
https://pub.dev/packages/file_picker allows you to pick files/images etc. and the file type of images is .jpg
https://pub.dev/packages/multi_image_picker allows you to pick images too, but takes the original file format; e.g. .heic, .jpg, .png
i select images with filepicker https://pub.dev/packages/file_picker
FilePickerResult result;
try {
result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['jpeg', 'jpg', 'heic', 'pdf'],
);
} catch (e) {
print('Exep: ****${e}***');
}
now you can check the extention of the file, use the package path.dart as p and package https://pub.dev/packages/heic_to_jpg to convert image to jpeg
File file = File(result.files.first.path);
String fileExtension = p.extension(file.path).replaceAll('.', '');
if (fileExtension == 'heic') {
print('convert to jpeg');
String jpegPath = await HeicToJpg.convert(file.path);
file = File(jpegPath);
fileExtension = 'jpeg';
}
do not forget do the same if you use imagePicker with source camera.
you can use multi_image_picker 4.6.7 to pick image in iOS for HEIC images.

Flutter/Dart overwriting File in getApplicationDocumentsDirectory not working immediately

I'm trying to overwrite a file in my apps temporary directory but for some reason the overwrite is not taking effect until I fully hot restart my app.
I'm trying to set my _pickedImage variable to the new changedImage once it has been copied to the directory, however when using setState it is always keeping the first image that was placed into the directory and not overwriting it each time. So when I display the _pickedImage it will always show the first initial image until i fully restart, once i fully restart the app the change is taking place. The reason for wanting to do this is so that users can effectively change the image if they wish. Hope this makes sense any help would be massively appreciated
var image = await ImagePicker.pickImage(source: source, maxWidth: 800.0);
if (image != null) {
final Directory extDir = await getApplicationDocumentsDirectory();
final String dirPath = '${extDir.path}/image';
if (Directory(dirPath).existsSync()) {
print('it exists');
var dir = new Directory(dirPath);
dir.deleteSync(recursive: true);
if (Directory(dirPath).existsSync()) {
print('still exists');
} else {
//It is getting in here so seemingly its deleting the orignal directory
print('does not exist');
}
}
new Directory(dirPath).createSync(recursive: true);
String path =
'$dirPath/temporaryImage.jpg';
File changedImage = image.copySync(path);`
setState(() {
//this is where the problem lies
_pickedImage = changedImage;
});
Cache is the problem. See issue https://github.com/flutter/flutter/issues/24858
From documentation https://api.flutter.dev/flutter/painting/ImageProvider-class.html
ImageProvider uses the global imageCache to cache images.
You can use
import 'package:flutter/painting.dart'
// to clear specific cache
imageCache.evict(FileImage(processedImage));
// to clear all cache
imageCache.clear();
It did not directly solve issue I had, however, it was the key.

Customizing Font Issue in blackberry

In application i have to use custom font. First i create class that extends VerticalFieldManager class. In this class i want to use custom font. I have TTF file (name is AGENCYB.TTF). I kept this file in res/img folder. To load this file i use following code:
if (FontManager.getInstance().load("AGENCYB.TTF", "MyFont",
FontManager.APPLICATION_FONT) == FontManager.SUCCESS)
{
System.out.println("**************************IF SUCCESS*******");
try
{
FontFamily typeface = FontFamily.forName("MyFont");
myFont = typeface.getFont(Font.BOLD, 50);
label2.setFont(myFont);
}
catch (ClassNotFoundException e)
{
System.out.println(e.getMessage());
}
}
But it is not changing font of label field. I implemented code by using this link:
http://docs.blackberry.com/en/developers/deliverables/18095/BlackBerry_Java_SDK-Development_Guide--1239696-0730090812-001-6.0-US.pdf
Any idea would be great help.
Thanks
**********EDIT**************
if (FontManager.getInstance().load("AGENCYB.TTF", "AGENCYB", FontManager.APPLICATION_FONT) == FontManager.SUCCESS)
First of all, this is the BlackBerry tutorial I've used for loading custom fonts
Second of all, I don't see a return code of 8 in any of the values that the API docs says FontManager.load() returns. SUCCESS is a value of 0, so you're not successfully calling load().
http://www.blackberry.com/developers/docs/7.0.0api/net/rim/device/api/ui/FontManager.html
Returns:
FontManager.SUCCESS if font loads successfully.
FontManager.FONTS_ARRAY_FULL if too many fonts loaded.
FontManager.MISSING_TYPEFACE_NAME if typeface name is invalid.
FontManager.DUPLICATE_NAME if font name is duplicate.
FontManager.DUPLICATE_DATA if font data is duplicate.
FontManager.NO_FONT_DATA if no font data is found.
FontManager.EXCEEDS_LIMIT if font data exceeds 60k in size.
FontManager.MISS_RESOURCE if font file cannot be found.
FontManager.FAILED_TO_LOAD_FILE if font data is invalid or font format is invalid.
When I ran in the debugger on OS 5.0 and 7.1, I saw that -8 was equal to FontManager.DUPLICATE_NAME, but didn't see any code equal to 8.
Also, did you generate this font file yourself (AGENCYB.TTF)? Because your code is asking for a font named MyFont in the AGENCYB.TTF file. I wouldn't expect a font to actually be named MyFont unless it was somebody writing a Hello World program (and homemade .ttf file).
If this is a custom font, provided by a 3rd-party font library, or bought from someone else, I would expect the font names to be something other than MyFont, which is what they have in the BlackBerry sample that you probably copied your code from.
So, double-check that, and let us know if it's still not working.
Update: since it looks like you also fail when you use the string "AGENCYB" in your code, I think the problem is that you're using the wrong font name. Even though the file is AGENCYB.TTF, I bet the font name inside that file is not AGENCYB. Is this the same file that you find in Windows under C:\Windows\fonts? If so, you can use Windows (7, at least) to look at the font file.
Just double-click the .ttf file in Windows Explorer, and it should give you a preview, that shows the proper font name. That name is the name you use in the two java calls, where the sample code has "MyFont". In this case, you see that the font name is probably "Agency FB". Try that.
Update 2: I also tried loading the Agency FB font from the AGENCYR.TTF file that can be found in C:\windows\Fonts\AGENCYR.TTF on a Windows 7 machine. This exact code worked for me on a 5.0 8900 simulator:
int result = FontManager.getInstance().load("AGENCYR.TTF", "Agency FB", FontManager.APPLICATION_FONT);
if (result == FontManager.SUCCESS)
{
try
{
FontFamily typeface = FontFamily.forName("Agency FB");
Font myFont = typeface.getFont(Font.PLAIN, 50);
helloWorld.setFont(myFont);
}
catch (ClassNotFoundException ex)
{
}
}
Exactly you should check if the font desired is already loaded so it gives you a -8 or the success int and thats it!
LabelField lbl = new LabelField("This is test Label");
// IF font is already loaded then use the following
if(FontManager.getInstance().load("TickingTimebombBB_ital.ttf", "Ticking Timebomb BB", FontManager.APPLICATION_FONT) == FontManager.DUPLICATE_NAME){
Logger.debug("---font already loaded-----");
try
{
System.out.println("---load once more---");
FontFamily typeface = FontFamily.forName("Ticking Timebomb BB");
Font myFont = typeface.getFont(Font.PLAIN, 80);
lbl.setFont(myFont);
}
catch (ClassNotFoundException e)
{
Logger.error("---error-----"+e.getMessage());
}
}
and if the font is not already loaded then use the following
else if(FontManager.getInstance().load("TickingTimebombBB_ital.ttf", "Ticking Timebomb BB", FontManager.APPLICATION_FONT) == FontManager.SUCCESS) {
try
{
Logger.debug("---load first time---");
FontFamily typeface = FontFamily.forName("Ticking Timebomb BB");
Font myFont = typeface.getFont(Font.PLAIN, 80);
lbl.setFont(myFont);
}
catch (ClassNotFoundException e)
{
Logger.error("---error-----"+e.getMessage());
}
}

Using Isolated Storage Images in the HubTiles

I let the users take images in my app and save the images in the Isolated Storage. I also use HubTiles in my app but the HubTiles use a Uri in their Source property but it can't recognize the isostore:/..... Uris..
Any idea how can I fix this issue?
You are not the only one experiencing that the isostore:/ URIs are not functioning in every place an URI is expected. So it seems like you need to take the more traditional approach and load the image by hand:
// define data array to hold image data to be read from isolated storage
byte[] imageBytes;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
// open image file
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("MyPreviouslySavedImage.jpg", FileMode.Open, FileAccess.Read))
{
// allocate array large enough to hold the whole file
imageBytes = new byte[fileStream.Length];
// read all data to memory
fileStream.Read(imageBytes, 0, imageBytes.Length);
fileStream.Close();
}
}
// create memory stream and bitmap
MemoryStream memoryStream = new MemoryStream(imageBytes);
BitmapImage bitmapImage = new BitmapImage();
// memory stream is source of bitmap
bitmapImage.SetSource(memoryStream);
// finally assign image to hub tile
hubTile1.Source = bitmapImage;
This works well (if there is an image in the isostore of course).

Resources