I am trying to scan QR code with my code. My code is running fine with 5.0(Bold) and 7.1(Torch) OS phones. It is running fine with 7.1 and 5.0. but giving problem while running with 6.0 OS(Bold 9700). The problem is - "While trying to scan QR code, app scans the QR code but camera screen doesn't pop and it remains at the front. Event it is not able to hide by using Esc key". please help me to resolve the issue with os6.
Edit:
Code while opening camera screen for QR code scan:
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 QR code. We put
// that in our view screen to handle the display.
try {
_scanner = new BarcodeScanner(decoder, new LeadQRcodeDecoderListener());
_QRcodeScreen = new LeadQRcodeScannerViewScreen(_scanner);
// If we get here, all the QR code scanning infrastructure should be set
// up, so all we have to do is start the scan and display the viewfinder
_scanner.startScan();
UiApplication.getUiApplication().pushScreen(_QRcodeScreen);
}
catch (Exception e) {
e.printStackTrace();
return;
}
code for closing screen is:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
UiApplication.getUiApplication().popScreen(_QRcodeScreen);
}
});
I am calling this code after scanning of QR code.
This is a problem with OS6 in some devices that has been asked before on this site. Last one was two days ago:
Blackberry OS6 camera wont shut down after capture
AFAIK there's no API to close the camera app, so it has to be done with key injection hacks, that are tricky because they need accurate timing and as CPUs are different in some models, and also because the camera app has a different design in some OSes.
So either you use JSR135 and use a renamed Zxing package to provide a camera view contained in your app, or just follow your approach but instead of closing the camera app you just bring to foreground your own app.
I have solved my same issue for os 6. After scanning of QR code, close all player and scanner connection.
You can use-
if (_scanner != null && _scanner.getPlayer() != null) {
_scanner.getPlayer().close();
}
It is helpful to me.
This will definitely help you.
here is my code , it's working perfectly in OS 6.0 device 9830
/**
* First Invoke the QR Scanner
*/
ViewFinderScreen _viewFinderScreen =
new ViewFinderScreen(ShoopingCartScreen.this); // ShoopingCartScreen.this Current Screen Object
UiApplication.getUiApplication().pushScreen(_viewFinderScreen);
package com.application.qrScanner;
import java.util.Hashtable;
import java.util.Vector;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;
import net.rim.device.api.barcodelib.BarcodeDecoder;
import net.rim.device.api.barcodelib.BarcodeDecoderListener;
import net.rim.device.api.barcodelib.BarcodeScanner;
import net.rim.device.api.io.Base64InputStream;
import net.rim.device.api.io.http.HttpDateParser;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Keypad;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.container.MainScreen;
import com.application.data.ShoopingCartObj;
import com.application.global.Global;
import com.application.log.Log;
import com.application.main.MessageScreen;
import com.application.main.orderDetail.orderSection.InputPopUpScreen;
import com.application.main.shoopingSection.ShoopingCartScreen;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
public class ViewFinderScreen extends MainScreen
{
private BarcodeScanner _scanner;
private short _frequency = 1046;
private short _duration = 200;
private int _volume = 100;
private VideoControl vc;
private ButtonField _btnCancel;
private ShoopingCartScreen _shoopingCartScreen;
/**
* Creates a new ViewFinderScreen object
*/
public ViewFinderScreen(ShoopingCartScreen _shoopingCartScreen)
{
this._shoopingCartScreen = _shoopingCartScreen;
_btnCancel = new ButtonField("Cancel" , ButtonField.USE_ALL_WIDTH)
{
protected boolean navigationClick(int status, int time)
{
fieldChangeNotify(1);
return true;
}
};
_btnCancel.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
stopScan();
UiApplication.getUiApplication().popScreen(ViewFinderScreen.this);
}
});
// Initialize Hashtable used to inform the scanner how to
// recognize the QR code format.
Hashtable hints = new Hashtable();
Vector formats = new Vector(1);
formats.addElement(BarcodeFormat.QR_CODE);
hints.put(DecodeHintType.POSSIBLE_FORMATS, formats);
// Initialize the BarcodeDecoder
BarcodeDecoder decoder = new BarcodeDecoder(hints);
// Create a custom instance of a BarcodeDecoderListener to pop the
// screen and display results when a QR code is recognized.
BarcodeDecoderListener decoderListener = new BarcodeDecoderListener()
{
/**
* #see BarcodeDecoderListener#barcodeDecoded(String)
*/
public void barcodeDecoded(String rawText)
{
try {
String encoded = rawText;
byte[] decoded = Base64InputStream.decode( encoded );
rawText = new String(decoded);
System.out.println( new String( decoded ) );
}
catch (Throwable t) {
System.out.println( "Unable to decode string: " + t.getMessage() );
}
displayMessage(rawText);
ViewFinderScreen.this. _shoopingCartScreen.beep();
}
};
try
{
// Initialize the BarcodeScanner object and add the associated
// view finder.
_scanner = new BarcodeScanner(decoder, decoderListener);
vc = _scanner.getVideoControl();
vc.setDisplayFullScreen(true);
add(_scanner.getViewfinder());
setStatus(_btnCancel);
}
catch(Exception e)
{
displayMessage("Initilize Scanner: " + e.getMessage());
}
startScan();
}
/**
* Informs the BarcodeScanner that it should begin scanning for QR Codes
*/
public void startScan()
{
try
{
_scanner.startScan();
}
catch(MediaException me)
{
displayMessage(" Start Scan Error: " + me.getMessage());
}
}
public void stopScan()
{
try
{
Player p = _scanner.getPlayer() ;
if(p != null)
{
p.stop();
p.deallocate();
p.close();
}
}
catch (Exception e)
{
MessageScreen.msgDialog("Exception in Stop Scanning "+e.toString());
}
}
/**
* Pops the ViewFinderScreen and displays text on the main screen
*
* #param text Text to display on the screen
*/
private void displayMessage(final String text)
{
Log.d("QR Code String ", text);
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
stopScan();
}
});
}
protected boolean keyDown(int keycode, int time)
{
if (Keypad.key(keycode) == Keypad.KEY_ESCAPE)
{
stopScan();
return true;
}
return super.keyDown(keycode, time);
}
}
Related
I am currently developing an app that requires real time face detection. Right now I have the mlkit library in the app and I am using the firebase face detector. At the moment, it produces an error every time I try to detect a face from file:
DynamiteModule(13840): Local module descriptor class for com.google.android.gms.vision.dynamite.face not found.
As for the real time part, I tried using the RepaintBoundary in flutter to get a screenshot of the camera widget (almost)every frame and convert it into a binary file for face detection. But for some reason, flutter crashed every time I tried to screenshot the camera widget. It worked for other widgets.
After coming across both of these problems and spending quite a while trying to solve them, I've been thinking about just doing the camera part of the app in android/iOS native code(I would do this with OpenCV so that I can have real time detection). Is there a way I could use platform channels to implement a camera view in kotlin and swift and import that to a flutter widget? Or is there another easier way to implement this?
For the real-time access to camera image stream, I answered in another question How to access camera frames in flutter quickly that you want to use CameraController#startImageStream
import 'package:camera/camera.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(home: _MyHomePage()));
class _MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<_MyHomePage> {
dynamic _scanResults;
CameraController _camera;
bool _isDetecting = false;
CameraLensDirection _direction = CameraLensDirection.back;
#override
void initState() {
super.initState();
_initializeCamera();
}
Future<CameraDescription> _getCamera(CameraLensDirection dir) async {
return await availableCameras().then(
(List<CameraDescription> cameras) => cameras.firstWhere(
(CameraDescription camera) => camera.lensDirection == dir,
),
);
}
void _initializeCamera() async {
_camera = CameraController(
await _getCamera(_direction),
defaultTargetPlatform == TargetPlatform.iOS
? ResolutionPreset.low
: ResolutionPreset.medium,
);
await _camera.initialize();
_camera.startImageStream((CameraImage image) {
if (_isDetecting) return;
_isDetecting = true;
try {
// await doOpenCVDectionHere(image)
} catch (e) {
// await handleExepction(e)
} finally {
_isDetecting = false;
}
});
}
Widget build(BuildContext context) {
return null;
}
}
I did something this with OpenCV before, my solution was:
Start a new Activity or ViewController on Android and iOS respectively via platform channel. Example:
class FaceScanPlugin(val activity: Activity) : MethodCallHandler, PluginRegistry.ActivityResultListener {
var result: Result? = null
companion object {
#JvmStatic
fun registerWith(registrar: Registrar): Unit {
val channel = MethodChannel(registrar.messenger(), "com.example.facescan")
val plugin = BarcodeScanPlugin(registrar.activity())
channel.setMethodCallHandler(plugin)
registrar.addActivityResultListener(plugin)
}
}
override fun onMethodCall(call: MethodCall, result: Result): Unit {
if (call.method.equals("scan")) {
this.result = result
showFaceScanView()
} else {
result.notImplemented()
}
}
private fun showFaceScanView() {
val intent = Intent(activity, FaceScannerActivity::class.java)
activity.startActivityForResult(intent, 100)
}
override fun onActivityResult(code: Int, resultCode: Int, data: Intent?): Boolean {
if (code == 100) {
if (resultCode == Activity.RESULT_OK) {
return true
}
}
return false
}
}
Refer to Flutter QR scanner plugin on how to navigate to Android activity or iOS View.
Then do your OpenCV real-time face detection via Camera2 and AVFoundation.
Other than that, I supposed you can try out the new AndroidView or UIKitView if you want to embed the android or iOS into your Flutter app.
I created a basic Vaadin application then added my Domino Jar files.
When I run the application, I get
[com.vaadin.server.ServiceException: java.lang.NoClassDefFoundError: lotus/domino/NotesException]
I've read a bunch of articles that talk about using OSGI etc. Isn't there a simple way to access Domino data from Vaadin without all the plug-ins etc? If not can someone explain why?
This is the calling code
package com.lms.helloDomino;
import javax.servlet.annotation.WebServlet;
import com.lms.service.StarService;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import lotus.domino.NotesException;
/**
* This UI is the application entry point. A UI may either represent a browser window
* (or tab) or some part of an HTML page where a Vaadin application is embedded.
* <p>
* The UI is initialized using {#link #init(VaadinRequest)}. This method is intended to be
* overridden to add component to the user interface and initialize non-component functionality.
*/
#Theme("mytheme")
public class MyUI extends UI {
#Override
protected void init(VaadinRequest vaadinRequest) {
StarService myStarService = null;
try
{
myStarService = new StarService();
myStarService.openStarDB();
} catch ( Exception e1 )
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
final VerticalLayout layout = new VerticalLayout();
final TextField name = new TextField();
name.setCaption("Your Domino Name");
name.setValue( myStarService.getNABProfile( "" ).fullName.toString() );
Button button = new Button("Click Me");
button.addClickListener(e -> {
layout.addComponent(new Label("Thanks " + name.getValue()
+ ", it works!"));
});
layout.addComponents(name, button);
setContent(layout);
}
#WebServlet(urlPatterns = "/*", name = "MyUIServlet", asyncSupported = true)
#VaadinServletConfiguration(ui = MyUI.class, productionMode = false)
public static class MyUIServlet extends VaadinServlet {
}
}
Here is the domino code
package com.lms.service;
import lotus.domino.NotesException;
import lotus.domino.Session;
import lotus.domino.NotesFactory;
public class StarService
{
public static Session notesSession = null;
public static Session getNotesSession()
{
if( notesSession == null )
try
{
notesSession = NotesFactory.createSession( "testHostServer", "testUser", "testPassword" );
} catch ( NotesException e )
{
e.printStackTrace();
}
return notesSession;
}
public StarService() throws NotesException
{
System.out.println( "Begin StarService Constructor" );
// Setup the notes connectivity
getNotesSession();
System.out.print( getNotesSession().getUserName() );
System.out.println( "End STARService Constructor" );
}
}
Turns out it was a build path issue. A big thank you to Karsten Lehmann from mindoo.de who helped me figure this out.
I didn't realize when running an Apache web server which serves up the Vaadin application, required my Domino .jar files on it's build path as well. He showed my how to add the .jar files to Apache's as follows:
Double click the Apache server under the servers tab
Click the Open Launch Configuration
Click the Class Path Tab
Highlight User Entries and Add External Jar files.
I've been looking for this off / on for a year now. Can't believe it's finally working!!!
I have a problem using the JavaFX WebView. What I want to achieve is pre-fetching a web page in the background and visualiszing it only when the page is totally loaded.
I have made a simple exmaple program to reproduce the problem. After the page is loaded I enable a button. A Click on this button then makes the WebView visible.
The problem I have is, that if I click on the button when it gets enabled, the web page is not visible directly. Instead the following happens: At first there is a totally white panel and then after a short time the web page is visible. I don't understand why the page is not visible directly. How can I achieve it, that the web page is directly visible?
The following link points to an animated gif which shows the behaviour:
http://tinypic.com/view.php?pic=oh66bl&s=5#.Ujmv1RddWKk
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class WebViewTest extends javax.swing.JPanel {
private static JFXPanel browserFxPanel;
private WebView webView;
private WebEngine eng;
/**
* Creates new form WebViewTest
*/
public WebViewTest() {
initComponents();
Platform.setImplicitExit(false);
browserFxPanel = new JFXPanel();
Platform.runLater(new Runnable() {
public void run() {
webView = createBrowser();
Scene scene = new Scene(webView);
scene.setFill(null);
browserFxPanel.setScene(
scene);
}
});
}
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
* content of this method is always regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
pnlMain = new javax.swing.JPanel();
showWebpageButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
pnlMain.setLayout(new java.awt.BorderLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(pnlMain, gridBagConstraints);
showWebpageButton.setText("show web page");
showWebpageButton.setEnabled(false);
showWebpageButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showWebpageButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
add(showWebpageButton, gridBagConstraints);
}// </editor-fold>
private void showWebpageButtonActionPerformed(java.awt.event.ActionEvent evt) {
pnlMain.removeAll();
pnlMain.add(browserFxPanel, BorderLayout.CENTER);
WebViewTest.this.invalidate();
WebViewTest.this.revalidate();
}
// Variables declaration - do not modify
private javax.swing.JPanel pnlMain;
private javax.swing.JButton showWebpageButton;
// End of variables declaration
private WebView createBrowser() {
Double widthDouble = pnlMain.getSize().getWidth();
Double heightDouble = pnlMain.getSize().getHeight();
final WebView view = new WebView();
view.setMinSize(widthDouble, heightDouble);
view.setPrefSize(widthDouble, heightDouble);
eng = view.getEngine();
eng.load("http://todomvc.com/architecture-examples/angularjs/#/");
eng.getLoadWorker().workDoneProperty().addListener(new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
final double workDone = eng.getLoadWorker().getWorkDone();
final double totalWork = eng.getLoadWorker().getTotalWork();
if (workDone == totalWork) {
showWebpageButton.setEnabled(true);
}
}
});
return view;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JFrame f = new JFrame("Navigator Dummy");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setSize(new Dimension(1024, 800));
final WebViewTest navDummy = new WebViewTest();
f.getContentPane().add(navDummy);
f.setVisible(true);
}
});
}
}
JFX needs a "stage" to show up its face. Modify your codes as following and it will work perfectly
/**
* Creates new form WebViewTest
*/
private Stage stage; // insert this line
public WebViewTest() {
initComponents();
Platform.setImplicitExit(false);
browserFxPanel = new JFXPanel();
Platform.runLater(new Runnable() {
public void run() {
webView = createBrowser();
Scene scene = new Scene(webView);
scene.setFill(null);
stage = new Stage(); // <<<
stage.setScene(scene); // <<<
browserFxPanel.setScene(scene);
}
});
}
...
private void showWebpageButtonActionPerformed(java.awt.event.ActionEvent evt) {
pnlMain.removeAll();
pnlMain.add(browserFxPanel, BorderLayout.CENTER);
WebViewTest.this.invalidate();
WebViewTest.this.revalidate();
stage.show(); // <<< afer click Button
}
I am working on blackberry project where i want to download image & save it in sd card in blackberry. By going through many sites i got some code & based on that i wrote the program but when it is executed the output screen is displaying a blank page with out any response. The code i am following is..
code:
public class BitmapDemo extends UiApplication
{
public static void main(String[] args)
{
BitmapDemo app = new BitmapDemo();
app.enterEventDispatcher();
}
public BitmapDemo()
{
pushScreen(new BitmapDemoScreen());
}
static class BitmapDemoScreen extends MainScreen
{
private static final String LABEL_X = " x ";
BitmapDemoScreen()
{
//BitmapField bmpFld1=new BitmapField(connectServerForImage("http://images03.olx.in/ui/3/20/99/45761199_1.jpg"));
//add(bmpFld1);
setTitle("Bitmap Demo");
// method for saving image in sd card
copyFile();
// Add a menu item to display an animation in a popup screen
MenuItem showAnimation = new MenuItem(new StringProvider("Show Animation"), 0x230010, 0);
showAnimation.setCommand(new Command(new CommandHandler()
{
public void execute(ReadOnlyCommandMetadata metadata, Object context)
{
// Create an EncodedImage object to contain an animated
// gif resource.
EncodedImage encodedImage = EncodedImage.getEncodedImageResource("animation.gif");
// Create a BitmapField to contain the animation
BitmapField bitmapFieldAnimation = new BitmapField();
bitmapFieldAnimation.setImage(encodedImage);
// Push a popup screen containing the BitmapField onto the
// display stack.
UiApplication.getUiApplication().pushScreen(new BitmapDemoPopup(bitmapFieldAnimation));
}
}));
addMenuItem(showAnimation);
}
private static class BitmapDemoPopup extends PopupScreen
{
public BitmapDemoPopup(BitmapField bitmapField)
{
super(new VerticalFieldManager());
add(bitmapField);
}
protected boolean keyChar(char c, int status, int time)
{
if(c == Characters.ESCAPE)
{
close();
}
return super.keyChar(c, status, time);
}
}
}
public static Bitmap connectServerForImage(String url) {
System.out.println("image url is:"+url);
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
int rc;
Bitmap bitmp = null;
try {
httpConnection = (HttpConnection) Connector.open(url,Connector.READ_WRITE);
rc = httpConnection.getResponseCode();
if (rc != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + rc);
}
httpInput = httpConnection.openInputStream();
InputStream inp = httpInput;
byte[] b = IOUtilities.streamToBytes(inp);
EncodedImage hai = EncodedImage.createEncodedImage(b, 0, b.length);
return hai.getBitmap();
} catch (Exception ex) {
System.out.println("URL Bitmap Error........" + ex.getMessage());
} finally {
try {
if (httpInput != null)
httpInput.close();
if (httpDataOutput != null)
httpDataOutput.close();
if (httpConnection != null)
httpConnection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return bitmp;
}
public static void copyFile() {
// TODO Auto-generated method stub
EncodedImage encImage = EncodedImage.getEncodedImageResource("rim.png");
byte[] image = encImage.getData();
try {
// Create folder if not already created
FileConnection fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/images/");
if (!fc.exists())
fc.mkdir();
fc.close();
// Create file
fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/images/" + image, Connector.READ_WRITE);
if (!fc.exists())
fc.create();
OutputStream outStream = fc.openOutputStream();
outStream.write(image);
outStream.close();
fc.close();
System.out.println("image saved.....");
} catch (Exception e) {
// TODO: handle exception
//System.out.println("exception is "+ e);
}
}
}
This is the code which i am using. Not getting any response except blank page.. As i am new to blackberry development unable to find out what is the problem with my code. Can anyone please help me with this...... Actually i am having other doubt as like android & iphone does in blackberry simulator supports for SD card otherwise we need to add any SD card slots for this externally...
Waiting for your reply.....
To simply download and save that image to the SDCard, you can use this code. I changed your SDCard path to use the pictures folder, which I think is the standard location on BlackBerrys. If you really want to store it in images, you may just need to create the folder if it doesn't already exist.
package com.mycompany;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.file.FileConnection;
public class DownloadHelper implements Runnable {
private String _url;
public DownloadHelper(String url) {
_url = url;
}
public void run() {
HttpConnection connection = null;
OutputStream output = null;
InputStream input = null;
try {
// Open a HTTP connection to the webserver
connection = (HttpConnection) Connector.open(_url);
// Getting the response code will open the connection, send the request,
// and read the HTTP response headers. The headers are stored until requested.
if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
input = new DataInputStream(connection.openInputStream());
int len = (int) connection.getLength(); // Get the content length
if (len > 0) {
// Save the download as a local file, named the same as in the URL
String filename = _url.substring(_url.lastIndexOf('/') + 1);
FileConnection outputFile = (FileConnection) Connector.open("file:///SDCard/BlackBerry/pictures/" + filename,
Connector.READ_WRITE);
if (!outputFile.exists()) {
outputFile.create();
}
// This is probably not a robust check ...
if (len <= outputFile.availableSize()) {
output = outputFile.openDataOutputStream();
// We'll read and write this many bytes at a time until complete
int maxRead = 1024;
byte[] buffer = new byte[maxRead];
int bytesRead;
for (;;) {
bytesRead = input.read(buffer);
if (bytesRead <= 0) {
break;
}
output.write(buffer, 0, bytesRead);
}
output.close();
}
}
}
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
if (connection != null) {
connection.close();
}
if (input != null) {
input.close();
}
} catch (IOException e) {
// do nothing
}
}
}
}
This class can download an image in the background, as I suggested. To use it, you can start a worker thread like this:
DownloadHelper downloader = new DownloadHelper("http://images03.olx.in/ui/3/20/99/45761199_1.jpg");
Thread worker = new Thread(downloader);
worker.start();
This will save the file as /SDCard/BlackBerry/pictures/45761199_1.jpg. I tested it on a 5.0 Storm simulator.
There are several problems with the code posted. It's also not completely clear what you're trying to do. From the question title, I assume you want to download a jpg image from the internet, and display it.
1) You implement a method called connectServerForImage() to download an image, but then it's commented out. So, the method isn't going to download anything if it's not called.
2) Even if it's uncommented, connectServerForImage() is called here
BitmapField bmpFld1=new BitmapField(connectServerForImage("http://images03.olx.in/ui/3/20/99/45761199_1.jpg"));
This will block the main (UI) thread while it downloads your image. Even though you can do it this way, it's not a good thing to do. Instead, you could create a Thread to download the image as a background task, and then use UiApplication.invokeLater() to load the image into your BitmapField on the main/UI thread.
3) Your copyFile() method tries to copy a file named rim.png, which must be an image bundled with your application, and saves it to the SDCard. Is this really what you want? Do you want to save the downloaded image instead? This method doesn't seem to be connected to anything else. It's not saving the image downloaded from the internet, and the image it does save is never used anywhere else.
4) In copyFile(), this line
fc = (FileConnection)Connector.open("file:///SDCard/BlackBerry/images/" + image, Connector.READ_WRITE);
is passing a byte[] in as part of the filename to open (your variable named image). You should probably be adding a String name to the end of your SDCard path. As the code is, it's probably opening a file in the /SDCard/BlackBerry/images/ folder with a very long name that looks like a number. Or it might fail entirely, if there are limits on the length of filenames.
5) In Java, it's not usually a good idea to make everything static. Static should normally be used for constants, and for a very few methods like the main() method, which must be static.
Try to clean these things up, and then repost the code, and we can try to help you with your problem. Thanks.
I am trying to play a video based on the videorecordingdemo sample from JDE7.0 (code below).
I am building for OS5.0 - which is why I cannot just run the whole demo app which is written for OS7.0.
I am using the emulator (9300) and have set up a folder to be used as my sd card. I have placed a .AVI video in there. I have also tried placing the .AVI into the resources, and streaming it from there.
In both cases, when I call Player.start(), the following exception is thrown:
net.rim.device.internal.media.RimMediaException: Media unloaded while initializing
I would like to know:
What does this error mean?
How can I fix it?
Alternatively are the any really special, stringent requirements for .AVI files to play?
Update: Tried the app on a real Torch device, and it gave
net.rim.device.internal.media.UnloadedMediaException
FWIW here is the sample code - as copied directly from the videorecordingdemo sample app.
package mypackage;
/*
* VideoPlaybackScreen.java
*
* Copyright © 1998-2011 Research In Motion Ltd.
*
* Note: For the sake of simplicity, this sample application may not leverage
* resource bundles and resource strings. However, it is STRONGLY recommended
* that application developers make use of the localization features available
* within the BlackBerry development platform to ensure a seamless application
* experience across a variety of languages and geographies. For more information
* on localizing your application, please refer to the BlackBerry Java Development
* Environment Development Guide associated with this release.
*/
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.VideoControl;
import javax.microedition.media.control.VolumeControl;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
/**
* A screen for playing a video
*/
public class VideoPlaybackScreen extends MainScreen
{
private Player _videoPlayer;
private VideoControl _videoControl;
/**
* Constructs a screen to playback the video from a specified input stream
*
* #param inputStream The InputStream of the video to display
*
* #throws NullPointerException Thrown if <code>inputStream</code> is null
*/
public VideoPlaybackScreen(InputStream inputStream)
{
if (inputStream == null)
{
throw new NullPointerException("'inputStream' cannot be null");
}
try
{
_videoPlayer = javax.microedition.media.Manager.createPlayer(inputStream, "video/sbv");
initScreen();
}
catch( Exception e )
{
Dialog.alert("Exception while initializing the playback video player\n\n" + e);
}
}
/**
* Constructs the screen to playback the video from a file
*
* #param file A locator string in URI syntax that points to the video file
*/
public VideoPlaybackScreen(String file)
{
boolean notEmpty;
try
{
FileConnection fconn = (FileConnection) Connector.open(file);
notEmpty = fconn.exists() && fconn.fileSize() > 0;
fconn.close();
}
catch( IOException e )
{
Dialog.alert("Exception while accessing the video filesize:\n\n" + e);
notEmpty = false;
}
// Initialize the player if the video is not empty
if( notEmpty )
{
try
{
_videoPlayer = javax.microedition.media.Manager.createPlayer(file);
initScreen();
}
catch( Exception e )
{
Dialog.alert("Exception while initializing the playback video player\n\n" + e);
}
}
else
{
add(new LabelField("The video file you are trying to play is empty"));
}
}
/**
* Initializes the screen after the player has been created
*
* #throws Exception Thrown if an error occurs when initializing the video player, video display or volume control
*/
private void initScreen() throws Exception
{
_videoPlayer.realize();
_videoPlayer.addPlayerListener(new PlayerListener()
{
/**
* #see javax.microedition.media.PlayerListener#playerUpdate(Player, String, Object)
*/
public void playerUpdate(Player player, String event, Object eventData)
{
// Alert the user and close the screen after the video has
// finished playing.
if( event == PlayerListener.END_OF_MEDIA )
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert("Finished playing");
close();
}
});
}
}
});
// Set up the playback
_videoControl = (VideoControl) _videoPlayer.getControl("VideoControl");
Field vField = (Field) _videoControl.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE,
"net.rim.device.api.ui.Field");
add(vField);
VolumeControl vol = (VolumeControl) _videoPlayer.getControl("VolumeControl");
vol.setLevel(30);
}
/**
* #see net.rim.device.api.ui.Field#onVisibilityChange(boolean)
*/
protected void onVisibilityChange(boolean visible)
{
// If the screen becomes visible and the video player was created, then
// start the playback.
if( visible && _videoPlayer != null )
{
try
{
_videoPlayer.start();
}
catch( final Exception e )
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
// If starting the video fails, terminate the playback
Dialog.alert("Exception while starting the video\n\n" + e);
close();
}
});
}
}
}
/**
* #see net.rim.device.api.ui.Screen#onClose()
*/
public void close()
{
// Close the video player if it was created
if( _videoPlayer != null )
{
_videoPlayer.close();
}
super.close();
}
}