Zxing qr scanning blackberry crash - java

I am implementing a QR code scanner for blackberry devices and I am using ZXing libraries to do so. This is for os 6+ by the way. The problem I am having is that sometimes, only sometimes, when the camera opens up to prepare scanning, the device will freeze and do a full reboot...
Otherwise it works most of the time, I am able to scan and decode the qr codes etc. However is just seems like it occasionally feels like crashing for no reason. I do not know if it is something with the camera or something in my code, but I will provide the code.
public void scanBarcode() {
// First we create a hashtable to hold all of the hints that we can
// give the API about how we want to scan a barcode to improve speed
// and accuracy.
Hashtable hints = new Hashtable();
// The first thing going in is a list of formats. We could look for
// more than one at a time, but it's much slower.
Vector formats = new Vector();
formats.addElement(BarcodeFormat.QR_CODE);
hints.put(DecodeHintType.POSSIBLE_FORMATS, formats);
// We will also use the "TRY_HARDER" flag to make sure we get an
// accurate scan
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
// We create a new decoder using those hints
BarcodeDecoder decoder = new BarcodeDecoder(hints);
// Finally we can create the actual scanner with a decoder and a
// listener that will handle the data stored in the barcode. We put
// that in our view screen to handle the display.
try {
_scanner = new BarcodeScanner(decoder, new MyBarcodeDecoderListener());
_barcodeScreen = new MyBarcodeScannerViewScreen(_scanner);
} catch (Exception e) {
return;
}
// If we get here, all the barcode scanning infrastructure should be set
// up, so all we have to do is start the scan and display the viewfinder
try {
_scanner.stopScan();
_scanner.getPlayer().start();
_scanner.startScan();
UiApplication.getUiApplication().pushScreen(_barcodeScreen);
} catch (Exception e) {
}
}
/***
* MyBarcodeDecoderListener
* <p>
* This BarcodeDecoverListener implementation tries to open any data encoded
* in a barcode in the browser.
*
* #author PBernhardt
*
**/
private class MyBarcodeDecoderListener implements BarcodeDecoderListener {
public void barcodeDecoded(final String rawText) {
//UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
UtilityDecoder.saveToHistory(rawText);
try {
UtilityDecoder.distributeBarcode(rawText);
} catch (PIMException e) {
}
}
}
I basically call scanBarcode() when I click on a button on a toolbar.
Can anyone tell me if my code is the problem, or the device, or something else? Thanks in advance for any help provided!

Try this link:
Scan Any Type of Barcode Image which Supports Blackberry
See this forun link and see the discussions of that link. Surely, you will get overall concept of barcode scanning and you will also get the Implemention of QRCode in version 5.0
Any type of Barcode scaning in 5.0

Related

QR code not decoded same string two formats

We have the string 117355|1.3,-0.6|1.68,1.25|2.95,-0.6|1.68,1.25encoded into a QR code. We have been using an online generator. The generator has produced two variations, shown here:
This one is easily decoded by our app.
This one returns the ChecksumException
Both scan fine when using a 3rd party scanning app, however, we are using the ZXING library within our app and instead of using a video feed we are using a still image, so one attempt, this is due to this being part of a wider image processing workflow.
The reason I said "two formats" is due to the sections of each QR code being different according to this. We have different strings and whenever we have the "3 dots" under the top right registration marker it scans, and when we don't the scan is unreliable.
Here is the reading section of code:
QRCodeReader reader;
try {
reader = new QRCodeReader();
Map<DecodeHintType, Object> tmpHintsMap = new EnumMap<DecodeHintType, Object>(DecodeHintType.class);
tmpHintsMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
BinaryBitmap img = new BinaryBitmap(new HybridBinarizer(
new GreyscaleLuminanceSource(greyscaleHalf, w, h)));
Result scanResult = reader.decode(img, tmpHintsMap);
return scanResult;
} catch (ChecksumException e) {
e.printStackTrace();
mError = "The QR Code could not be decoded";
} catch (NotFoundException e) {
mError = "The QR Code could not be found";
e.printStackTrace();
} catch (FormatException e) {
mError = "The QR Code Format";
e.printStackTrace();
}
return null;
As you can see I have tried the DecodeHintType.TRY_HARDER option, but this does not help. We were working with 3.2.0 and I have recently tried with 3.2.1.
We have had 22,000 of these labels printed and I need to find a solution to make this scan reliably.

JavaFX audio doesn't seem to be playing

I am fairly new to JavaFX and recently wanted to play audio with an MP3 file rather than WAV. From what I can tell, I am doing things correctly and I don't get any errors, but I also don't hear any sound.
I will post the parts of my code that matter below. If I'm missing something please let me know. Thanks.
try {
URL sound = getClass().getResource("/resources/origin.mp3");
Media hit = new Media(sound.toExternalForm());
musicPlayer = new MediaPlayer(hit);
musicPlayer.setVolume(1.0);
}
catch(Exception e) {
System.out.println("whoops: " + e);
}
checkMusic();
Check Music Method:
public void checkMusic() {
if(music)
musicPlayer.setAutoPlay(true);
else
musicPlayer.stop();
}
I also tried just musicPlayer.play(); as well.
EDIT
And yes, I am sure the code within the if statement runs, I have checked it with println, and they print out. The music boolean is just a controller for settings in the program/game.
instead of
Media hit = new Media(sound.toExternalForm());
try this:
final Media media = new Media(sound.toString());

Get number of sheets in Open Office with Java

I am using Java to automate the creation and modification of Open Office Calc documents.
I was wondering how to get the number of sheets in a spreadsheet. I can't seem to find any Count, Length, size or similar functions.
Here is my code. Thanks in advance!
public static void openDocument(String filename)
{
try
{
// Get the remote office component context
xContext = Bootstrap.bootstrap();
// Get the remote office service manager
XMultiComponentFactory xMCF = xContext.getServiceManager();
// Get the root frame (i.e. desktop) of openoffice framework.
oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
// Desktop has 3 interfaces. The XComponentLoader interface provides ability to load components.
XComponentLoader xCompLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class,
oDesktop);
PropertyValue[] loadProps = new PropertyValue[0];
xSpreadsheetComponent = xCompLoader.loadComponentFromURL(getUpdatedPath(filename), "_blank", 0, loadProps);
xStorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, xSpreadsheetComponent);
xSpreadsheetDocument = (XSpreadsheetDocument) UnoRuntime.queryInterface(XSpreadsheetDocument.class,
xSpreadsheetComponent);
xSpreadsheets = xSpreadsheetDocument.getSheets();
// Need code here to get number of sheets
}
catch (Exception e)
{
e.printStackTrace();
}
This is more of a comment (since I do not know the correct syntax for Java - maybe you need to do a .queryInterface on xSpreadsheets?), but posting as an answer to include an image. Using Bernard Marcelly's object inspection tool XRay (http://bernard.marcelly.perso.sfr.fr/index2.html) shows that an XSpreadsheets object has a method .getCount(). I tested this method using OpenOffice Basic and it works as expected.
I solved my issue using this:
int numberOfSheets = xSpreadsheets.getElementNames().length;

disable other sounds in java

I wrote a program in Java using the pi4j lib to make sound whenever a (physical) button is clicked. This program works, but it now plays all the sounds interchangeably. I want that when you click on 2,3,4 or more buttons you only hear one sound.
This is the code I hope you can help.
public class ButtonSoundsProject{
public static void main(String args[]) throws InterruptedException {
System.out.println("Toy has been started!");
// create gpio controller
final GpioController gpio = GpioFactory.getInstance();
// provision gpio pin #02 as an input pin with its internal pull down resistor enabled
GpioPinDigitalInput[] pins = {
gpio.provisionDigitalInputPin(RaspiPin.GPIO_00, PinPullResistance.PULL_DOWN),
gpio.provisionDigitalInputPin(RaspiPin.GPIO_01, PinPullResistance.PULL_DOWN),
gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN),
gpio.provisionDigitalInputPin(RaspiPin.GPIO_03, PinPullResistance.PULL_DOWN),
gpio.provisionDigitalInputPin(RaspiPin.GPIO_04, PinPullResistance.PULL_DOWN),
gpio.provisionDigitalInputPin(RaspiPin.GPIO_05, PinPullResistance.PULL_DOWN),};
final ArrayList<String> soundList = new ArrayList<String>();
soundList.add("/home/pi/Sounds/Sound1.wav");
soundList.add("/home/pi/Sounds/Sound2.wav");
soundList.add("/home/pi/Sounds/Sound3.wav");
soundList.add("/home/pi/Sounds/Sound4.wav");
soundList.add("/home/pi/Sounds/Sound5.wav");
soundList.add("/home/pi/Sounds/Sound6.wav");
soundList.add("/home/pi/Sounds/Sound7.wav");
soundList.add("/home/pi/Sounds/Sound8.wav");
soundList.add("/home/pi/Sounds/Sound9.wav");
soundList.add("/home/pi/Sounds/Sound10.wav");
soundList.add("/home/pi/Sounds/Sound11.wav");
soundList.add("/home/pi/Sounds/Sound12.wav");
// create and register gpio pin listener
GpioPinListenerDigital listener = new GpioPinListenerDigital() {
#Override
public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
// display pin state on console
final int randomNum = 0 + (int) (Math.random() * 12);
System.out.println(randomNum);
System.out.println(" --> GPIO PIN STATE CHANGE: " + event.getPin() + " = " + event.getState());
InputStream in;
try {
System.out.println(soundList.get(randomNum).toString());
String filepath = soundList.get(randomNum).toString();
in = new FileInputStream(new File(filepath));
AudioStream as = new AudioStream(in);
AudioPlayer.player.start(as);
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
gpio.addListener(listener, pins);
for (;;) {
Thread.sleep(500);
}
}
}
As stated in the comments, I can't give you advise regarding the AudioStream and AudioPlayer classes because I don't seem to have those in my JDK. Since my method is similar, I'll give you what I have, and you can hopefully take it from there.
Basically, the solution is to stop and/or "mute" that audio clip. This is how I accomplish it using the javax.sound package.:
private Clip currentAudioClip; // Keep a reference to the current clip being played
public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
// Call this every time regardless.
// If nothing is playing, this will do nothing.
stopAudio();
String filepath = soundList.get(randomNum)
URL soundFileUrl = new File(filePath).toURI().toURL();
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFileUrl);
Line.Info lineInfo = new Line.Info(Clip.class);
Line line = AudioSystem.getLine(lineInfo);
currentAudioClip = (Clip) line;
currentAudioClip.open(audioInputStream);
audioClip.start();
// Alternative if you want to loop continuously. Comment out the `.start` line to use this.
// audioClip.loop(Clip.LOOP_CONTINUOUSLY);
}
public void stopAudio(){
if(audioClip != null){
muteLine(); // A gotcha I discovered (see explanation below)
audioClip.stop();
// audioClip.loop(0); // if you chose to loop, use this instead of `.stop()`
audioClip.flush();
audioClip = null;
}
}
public void muteLine(){
BooleanControl muteControl = (BooleanControl) audioClip.getControl(BooleanControl.Type.MUTE);
if(muteControl != null){
muteControl.setValue(true); // True to mute the line, false to unmute
}
}
In short, every time a pin state change event is fired, the previous audio clip will be ceased, and a new one should play. You shouldn't get any sound overlapping with this.
Also note that this is a slight modification of my original code, so let me know if there are any issues
Note about the GOTCHA
I wrote a question over on the Raspberry PI Stackexchange about an odd problem I encountered. The problem was that I discovered my audio clip would not cease playing on command. It would continue playing for a seemingly arbitrary amount of time. The stranger thing is that I only observed this while testing the app on the raspberry; it worked perfectly fine on my local machine (and even on several other machines).
It is possible my issue is related to the "looping" of my clip; if that is the case, and you simply want the clip to play for its length and no further, you may not encounter that issue, and you can probably dispense with the "muting" code I included. However, if you do observe the same issue, at least you have a solution.
Hope this helps, let me know if you have any questions.

Remember the values entered on standalone app on the client side

We have a standalone java swing app, in which the user can print something that he drew, on a printer by giving its IP.
Now the requirement is that the app needs to remember the ip that was given the last time by this user.
What I could think of till now is (a brute one though) - keep a log file kind of storage on the client machine, and that everytime the app comes up it reads the last submitted one.
Any suggestions would be helpful.
Thanks in advance.
Here's a tutorial on using the Java Preferences API to achieve what you want.
From the article:
The Java Preferences API provides a
systematic way to handle user and
system preference and configuration
data, e.g. to save user settings,
remember the last value of a field
etc.
I would use this approach over writing any data out explicitly to a file because its platform agnostic.
More or Less that's it. Still you can review the source code for HistoryTextField component of jEdit.
http://www.jedit.org/api/org/gjt/sp/jedit/gui/HistoryTextField.html
A Sample from jEdit source:
public boolean save(Map<String, HistoryModel> models)
{
Log.log(Log.MESSAGE,HistoryModel.class,"Saving history");
File file1 = new File(MiscUtilities.constructPath(
jEdit.getSettingsDirectory(), "#history#save#"));
File file2 = new File(MiscUtilities.constructPath(
jEdit.getSettingsDirectory(), "history"));
if(file2.exists() && file2.lastModified() != historyModTime)
{
Log.log(Log.WARNING,HistoryModel.class,file2
+ " changed on disk; will not save history");
return false;
}
jEdit.backupSettingsFile(file2);
String lineSep = System.getProperty("line.separator");
BufferedWriter out = null;
try
{
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(file1), "UTF-8"));
if(models != null)
{
Collection<HistoryModel> values = models.values();
for (HistoryModel model : values)
{
if(model.getSize() == 0)
continue;
out.write('[');
out.write(StandardUtilities.charsToEscapes(
model.getName(),TO_ESCAPE));
out.write(']');
out.write(lineSep);
for(int i = 0; i < model.getSize(); i++)
{
out.write(StandardUtilities.charsToEscapes(
model.getItem(i),
TO_ESCAPE));
out.write(lineSep);
}
}
}
out.close();
/* to avoid data loss, only do this if the above
* completed successfully */
file2.delete();
file1.renameTo(file2);
}
catch(IOException io)
{
Log.log(Log.ERROR,HistoryModel.class,io);
}
finally
{
IOUtilities.closeQuietly(out);
}
historyModTime = file2.lastModified();
return true;
}
Since it is a Swing app., you might launch it using Java Web Start then persist the data using the PersistenceService. Here is a demo. of the PersistenceService.
i dont really recommend this, but you could use the registry also.

Categories