QR Code Live Scanning in BlackBerry OS 6.0 - blackberry

I want to Implement a QR Code Reader In BlackBerry Os 6. I try the following Code On the Basis of KB Article How to use the Barcode API.
public class ScanScreen extends MainScreen implements BarcodeDecoderListener
{
private LabelField match;
private BarcodeScanner scanner;
public ScanScreen()
{
match = new LabelField("Scanning...");
add(match);
Vector supported = new Vector();
supported.addElement(BarcodeFormat.QR_CODE);
Hashtable hints = new Hashtable();
hints.put(DecodeHintType.POSSIBLE_FORMATS, supported);
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
BarcodeDecoder decoder = new BarcodeDecoder(hints);
try
{
scanner = new BarcodeScanner(decoder, this);
add(scanner.getViewfinder());
scanner.startScan();
}
catch (Exception e)
{
e.printStackTrace();
match.setText("Exception");
invalidate();
}
}
public void barcodeDecoded(String rawText)
{
match.setText("Found: " + rawText);
invalidate();
}
public void close()
{
try
{
scanner.stopScan();
}
catch (Exception e)
{
e.printStackTrace();
}
super.close();
}
}
The Code not working. It do not recognize QR codes. I try to focus on different QR codes. But it not decode The qrcodes.Also It not Thrown Any exceptions. Please Help me....
I tried using these Devices: BB pearl 9105 and BB Storm 9530

See the sample from the following link.It will help you
http://aliirawan-wen.blogspot.com/2011/05/barcode-scanner-for-blackberry-os-50.html

I'm painfully new to BB development, but I notice you pass "this" as the decoderlistener parameter, perhaps that's causing a problem?
BarcodeDecoder decoder = new BarcodeDecoder(hints);
BarcodeDecoderListener decoderListener = new BarcodeDecoderListener()
{
public void barcodeDecoded(String rawText)
{
displayMessage(rawText);
}
};
try
{
scanner = new BarcodeScanner(decoder, decoderListener)
add(scanner.getViewfinder());
scanner.startScan();
}
catch (Exception e)
{
e.printStackTrace();
match.setText("Exception");
invalidate();
}
}

Related

Android Studio, downloading image form url/app has stopped working

Hi could you help me find out why my app stops working when I want to download image from url, here is the code
public void getOnClick(View view) throws IOException {
urlAdress = new URL("http://www.cosmeticsurgerytruth.com/blog/wp- content/uploads/2010/11/Capri.jpg");
InputStream is = urlAdress.openStream();
filename = Uri.parse(urlAdress.toString()).getLastPathSegment();
outputFile = new File(context.getCacheDir(),filename);
OutputStream os = new FileOutputStream(outputFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
is.close();
os.close();
I was also trying to use some code from similar topics but I get same message
Your app has stopped working
and it shuts down
Caused by: android.os.NetworkOnMainThreadException
The problem is that you are trying to download the image from the UIThread. You have to create a class which extends to AsyncTask class and make the download on the doInBackground method
private class DownloadAsync extends AsyncTask<Void, Void, Void> {
private Context context;
DownloadAsync(Context context) {
this.context = context;
}
#Override
protected Void doInBackground(Void... params) {
try {
URL urlAdress = urlAdress = new URL("http://www.cosmeticsurgerytruth.com/blog/wp- content/uploads/2010/11/Capri.jpg");
InputStream is = urlAdress.openStream();
String filename = Uri.parse(urlAdress.toString()).getLastPathSegment();
File outputFile = new File(context.getCacheDir(), filename);
OutputStream os = new FileOutputStream(outputFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
is.close();
os.close();
return null;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Then you can execute like this
public void getOnClick(View view){
new DownloadAsync(this).execute();
}

LWUIT Uncaught exception: java.lang.OutOfMemoryError(stack trace incomplete)

I developed an Rss Application using LWUIT Tabs,i want to display Rss Feed Titles and images on my Lwuit Tab screen,but when i run my application i am able to display three List (title with image)items Sucessfully,after that i am facing java.lang.OutOfMemoryError(stack trace incomplete) Eventhough there are list items present?can any one help......thanks...
Here my Code:
public class Process {
protected XMLMidlet midlet;
Form form1;
Image image;
Tabs tabs;
private List myNewsList;
private Vector topnews;
private Vector topstory;
private Command cmdExit;
private Command m_backCommand;
private List newsList;
private Form form2;
Process(XMLMidlet midlet) throws IOException {
this.midlet=midlet;
topnews = new Vector();
topstory = new Vector();
tabs = new Tabs();
form1 = new Form();
form2=new Form();
try {
newsList = new List(topnews);
newsList.setScrollVisible(false);
newsList.setRenderer(new NewsListCellRenderer());
m_backCommand = new Command("Back");
cmdExit = new Command("EXIT");
tabs.addTab("Topstory", newsList);
form1.addComponent(BorderLayout.CENTER, tabs);
}
catch(Exception e){
e.printStackTrace();
} }
public void process() {
try{
String url = "http://www.teluguone.com/news/tonefeeds/news/news-1.rss";
form1.show();
ParseThread myThread = new ParseThread(this);
myThread.getXMLFeed(url);
} catch (Exception e) {
}
}
public void addNews(News newsItem) {
try{
topnews.addElement(newsItem);
newsList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
List source = (List) ae.getSource();
News selectedNewsItem = (News) source.getSelectedItem();
if (selectedNewsItem != null) {
displayCompleteNewsScreen(selectedNewsItem);
}
}
});
}
catch(OutOfMemoryError r){
}
form1.show();
}
private void displayCompleteNewsScreen(News detailNews) {
try{
form2.removeAll();
form2.repaint();
form2.addCommand(m_backCommand);
form2.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
form1.show();
}
});
HTMLComponent com=new HTMLComponent();
com.setPreferredSize(new Dimension(300,300));
com.setShowImages(false);
com.setBodyText(detailNews.getDescription());
form2.addComponent(com);
//form2.addComponent(big);
}
catch(OutOfMemoryError e){
}
form2.show();
}
}
How big are the images? What handset are we talking about here?
I am betting that the images you're getting are not being scaled down before being displayed. I believe there are methods in LWUIT to scale down the size of an image. Remember to dispose of the temp image you create after adding the image to your form.

Unable to connect BlackBerry phone with Bluetooth SPP device

I am trying to connect to a bluetooth device from the blackberry 9900 phone using the following code;
public final class AppMainScreen extends MainScreen {
private BluetoothspInfo[] spInfo;
private StreamConnection bConn;
private DataInputStream diStream;
private String text;
public AppMainScreen() {
spInfo = BluetoothSerialPort.getSerialPortInfo();
try {
bConn = (StreamConnection) Connector.open(
spInfo[0].toString(), Connector.READ);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
UiApplication.getUiApplication().invokeLater(new TextScanner());
}
// ...
// ...
// ...
}
But its always throwing the exception java.io.IOException: Unable to connect. I am not able to get the full trace.
What is the problem here, can anybody please point me in the right direction.
I am using the BlackBerry Java on BlackBerry Eclipse Plugin with Platform version 4.5.

Blackberry Java - Fixed length streaming a POST body over a HTTP connect

I'm working on some code which POSTs large packets often over HTTP to a REST server on IIS. I'm using the RIM/JavaME HTTPConnection class.
As far as I can tell HTTPConnection uses an internal buffer to "gather" up the output stream before sending the entire contents to the server. I'm not surprised, since this is how HttpURLConnect works by default as well. (I assume it does this so that the content-length is set correctly.) But in JavaSE I could override this behavior by using the method setFixedLengthStreamingMode so that when I call flush on the output stream it would send that "chunk" of the stream. On a phone this extra buffering is too expensive in terms of memory.
In Blackberry Java is there a way to do fixed-length streaming on a HTTP request, when you know the content-length in advance?
So, I never found a way to do this was the base API for HTTPConnection. So instead, I created a socket and wrapped it with my own simple HTTPClient, which did support chunking.
Below is the prototype I used and tested on BB7.0.
package mypackage;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.microedition.io.Connector;
import javax.microedition.io.SocketConnection;
public class MySimpleHTTPClient{
SocketConnection sc;
String HttpHeader;
OutputStreamWriter outWriter;
InputStreamReader inReader;
public void init(
String Host,
String port,
String path,
int ContentLength,
String ContentType ) throws IllegalArgumentException, IOException
{
String _host = (new StringBuffer())
.append("socket://")
.append(Host)
.append(":")
.append(port).toString();
sc = (SocketConnection)Connector.open(_host );
sc.setSocketOption(SocketConnection.LINGER, 5);
StringBuffer _header = new StringBuffer();
//Setup the HTTP Header.
_header.append("POST ").append(path).append(" HTTP/1.1\r\n");
_header.append("Host: ").append(Host).append("\r\n");
_header.append("Content-Length: ").append(ContentLength).append("\r\n");
_header.append("Content-Type: ").append(ContentType).append("\r\n");
_header.append("Connection: Close\r\n\r\n");
HttpHeader = _header.toString();
}
public void openOutputStream() throws IOException{
if(outWriter != null)
return;
outWriter = new OutputStreamWriter(sc.openOutputStream());
outWriter.write( HttpHeader, 0 , HttpHeader.length() );
}
public void openInputStream() throws IOException{
if(inReader != null)
return;
inReader = new InputStreamReader(sc.openDataInputStream());
}
public void writeChunkToServer(String Chunk) throws Exception{
if(outWriter == null){
try {
openOutputStream();
} catch (IOException e) {e.printStackTrace();}
}
outWriter.write(Chunk, 0, Chunk.length());
}
public String readFromServer() throws IOException {
if(inReader == null){
try {
openInputStream();
} catch (IOException e) {e.printStackTrace();}
}
StringBuffer sb = new StringBuffer();
int data = inReader.read();
//Note :: This will also read the HTTP headers..
// If you need to parse the headers, tokenize on \r\n for each
// header, the header section is done when you see \r\n\r\n
while(data != -1){
sb.append( (char)data );
data = inReader.read();
}
return sb.toString();
}
public void close(){
if(outWriter != null){
try {
outWriter.close();
} catch (IOException e) {}
}
if(inReader != null){
try {
inReader.close();
} catch (IOException e) {}
}
if(sc != null){
try {
sc.close();
} catch (IOException e) {}
}
}
}
Here is example usage for it:
MySimpleHTTPClient myConn = new MySimpleHTTPClient() ;
String chunk1 = "ID=foo&data1=1234567890&chunk1=0|";
String chunk2 = "ID=foo2&data2=123444344&chunk1=1";
try {
myConn.init(
"pdxsniffe02.webtrends.corp",
"80",
"TableAdd/234234234443?debug=1",
chunk1.length() + chunk2.length(),
"application/x-www-form-urlencoded"
);
myConn.writeChunkToServer(chunk1);
//The frist chunk is already on it's way.
myConn.writeChunkToServer(chunk2);
System.out.println( myConn.readFromServer() );
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
myConn.close();
}

send sms from background thread in blackberry using j2me

hey i made a lot of search and found some similar types of code.
I tried for gsm
method 1 gives IllegalArgumentException
try
{
MessageConnection _mc = (MessageConnection)Connector.open("sms://");
TextMessage tm = (TextMessage) _mc.newMessage(MessageConnection.TEXT_MESSAGE);
tm.setPayloadText(smsText);
tm.setAddress("965xxxxxxx");
_mc.send(tm);
_mc.close();
}catch(exception e){}
method 2: gives java.lang.error exception
try
{
MessageConnection _mc = (MessageConnection)Connector.open("sms://");
TextMessage tm = (TextMessage) _mc.newMessage(MessageConnection.TEXT_MESSAGE,
"//9790XXXXXX");
tm.setPayloadText(text);
_mc.send(tm);
_mc.close();
}catch(Exception e){}
I think the problem is with address
i also tried : but no success
+91965xxxxxxx ,
0091965xxxxxxx ,
0965xxxxxxx
How my application works----
i have created 2 applications--
1) Application 1 is a background app that is a System module as well as
startup application.
2) Another is a uiapplication
the background app runs in background.If there comes an incoming call then a flag value is set in persistent object and after checking that value as true the sms is send to that no from whom call is made.
ok try this
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;
import net.rim.device.api.system.RadioInfo;
public class SendSMS extends Thread {
private String to;
private String msg;
public SendSMS(String to, String msg) {
this.to = to;
this.msg = msg;
}
public void run() {
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + to);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
dc.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
} else {
MessageConnection mc = null;
try {
mc = (MessageConnection) Connector
.open("sms://" + to);
TextMessage m = (TextMessage) mc
.newMessage(MessageConnection.TEXT_MESSAGE);
m.setPayloadText(msg);
mc.send(m);
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
mc.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
}
}
and call like this
public void callDisconnected(int callId) {
final PhoneCall call = Phone.getCall(callId);
final String number = call.getDisplayPhoneNumber();
SendSMS sendSMS = new SendSMS(number, "message");
sendSMS.start();
super.callDisconnected(callId);
}

Resources