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.
Related
I am loading images in PictureScrollField from the server and want that until images are loaded from server, the PictureScrollField shows a blank image and when the image loads in image array, it repaints (redraw) the PictureScrollField like a ListField.
I read from BlackBerry documentation that every field can be invalidated (that is, we can repaint it) but when I use the PictureScrollField.invalidate() method in my program, I get an error :
The method invalidate from the type Field is not visible
The program I use is listed below
public final class GetMoreImage extends MainScreen {
public static PictureScrollField psf;
int size;
int length;
String text=null;
EncodedImage[] encodedImage;
VerticalFieldManager vmanger;
private LoadImages loadImages;
public GetMoreImage(int index) {
super(NO_VERTICAL_SCROLL | NO_VERTICAL_SCROLLBAR);
this.size=index;
try {
length=ListHome.object[size].getJSONArray("UrlArray").length();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ScrollEntry[] entries = new ScrollEntry[length];
for (int i = 0; i < length; i++) {
if(encodedImage != null && encodedImage.length > i && encodedImage[i] != null) {
EncodedImage encodedImg =ListHome.sizeImage(JPEGEncodedImage.encode(Bitmap.getBitmapResource("icon.png"),80),640,380);
Bitmap bmp=encodedImg.getBitmap();
entries[i] = new ScrollEntry(bmp, "hello", "");
}
else {
try {
text=ListHome.object[size].getJSONArray("UrlArray").getString(i).toString();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EncodedImage encodedImg =ListHome.sizeImage(JPEGEncodedImage.encode(connectServerForImage(text),80),640,380);
Bitmap bmp=encodedImg.getBitmap();
entries[i] = new ScrollEntry(bmp, "hello", "");
}
}
psf = new PictureScrollField();
psf.setData(entries, 0);
psf.setHighlightStyle(HighlightStyle.ILLUMINATE_WITH_SHRINK_LENS);
add(psf);
loadImages = new LoadImages(80, 80);
loadImages.start();
}
private class LoadImages extends Thread {
int widthL;
int heightL;
LoadImages(int width, int height) {
this.widthL = width;
this.heightL = height;
}
public void run() {
encodedImage=new EncodedImage[length];
if (ListHome.object[size] != null) {
for (int i = 0; i < length; i++) {
try {
String text=ListHome.object[size].getJSONArray("UrlArray").getString(i).toString();
EncodedImage encodedImg = JPEGEncodedImage.encode(connectServerForImage(text), 80);//Get Image from Server
encodedImage[i] = ListHome.sizeImage(encodedImg, Display.getWidth(), Display.getHeight()-100);
psf.invalidate();//This Line generate error
} catch (Exception e)
{
e.printStackTrace();
}
}
} else {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("No Data Found");
}
});
}
}
}
}
Any help will be appreciated.
Thanks
The reason you get a compile error on this line:
psf.invalidate();//This Line generate error
is because the PictureScrollField#invalidate() method is protected, not public. So, code not in PictureScrollField or a class that extends PictureScrollField cannot use it directly.
However, you don't need to use invalidate(). invalidate() is a low-level method that instructs a field to repaint. However, PictureScrollField has a higher-level method that is designed to allow you to change images, and have the field (re)draw them: PictureScrollField#setData().
Because that method is changing the user interface (UI), it should be run on the UI/main thread. This will not automatically happen if you make the call inside the run() method you are using to download the images. So, you'll need something like this inside your LoadImages class:
public void run() {
encodedImage=new EncodedImage[length];
if (ListHome.object[size] != null) {
for (int i = 0; i < length; i++) {
try {
String text=ListHome.object[size].getJSONArray("UrlArray").getString(i).toString();
EncodedImage encodedImg = JPEGEncodedImage.encode(connectServerForImage(text), 80);//Get Image from Server
encodedImage[i] = ListHome.sizeImage(encodedImg, Display.getWidth(), Display.getHeight()-100);
//psf.invalidate();//This Line generate error
entries[i] = new ScrollEntry(encodedImage[i].getBitmap(), "label", "callout");
// we must update the scroll entries on the UI/main thread:
UiApplication.getUiApplication().invokeLater(new Runnable() {
// setting the field to index 'i' will scroll to the image
// that was just downloaded
psf.setData(entries, i);
});
} catch (Exception e)
{
e.printStackTrace();
}
}
}
In order to make this work, you must change the local entries variable to a member variable in your GetMoreImage class:
public final class GetMoreImage extends MainScreen {
public static PictureScrollField psf;
private ScrollEntry[] entries;
but, you can still instantiate it (entries = new ScrollEntry[length];) in your screen's constructor, or whenever you know the correct length.
I am new to BlackBerry development. But good about android.
I want to load Images coming from the server in ListField.
I have implement like below code but not getting success:
package mypackage;
public class TempScreen extends MainScreen implements ListFieldCallback{
Bitmap[] images=null;
private ListField mylist;
private static Bitmap _bitmap;
private ImageDownloader downloader;
int size = 0;
String[] urls={
"http://www.kentnews.co.uk/polopoly_fs/damian_lewis_at_port_lympne_wild_animal_park_c_taf_1_1738362!image/2626063106.jpg_gen/derivatives/landscape_225/2626063106.jpg",
"http://www.kentnews.co.uk/polopoly_fs/damian_lewis_at_port_lympne_wild_animal_park_c_taf_1_1738362!image/2626063106.jpg_gen/derivatives/landscape_225/2626063106.jpg",
"http://www.kentnews.co.uk/polopoly_fs/damian_lewis_at_port_lympne_wild_animal_park_c_taf_1_1738362!image/2626063106.jpg_gen/derivatives/landscape_225/2626063106.jpg",
"http://www.kentnews.co.uk/polopoly_fs/damian_lewis_at_port_lympne_wild_animal_park_c_taf_1_1738362!image/2626063106.jpg_gen/derivatives/landscape_225/2626063106.jpg"};
public TempScreen()
{
images=new Bitmap[urls.length];
size = urls.length;
mylist = new ListField();
mylist.setCallback(this);
mylist.setSize(4);
mylist.setRowHeight(getFont().getHeight() * 3);
add(mylist);
Thread downloader=new Thread(new ImageDownloader());
downloader.start();
}
public void drawListRow(ListField listField, Graphics graphics, int index,
int y, int width) {
if(images[index]==null)
{
//Load placeholder image
_bitmap = Bitmap.getBitmapResource("close_btn.png");// load some bitmap
// of your choice
// here
}
else
//Load Bitmap
_bitmap = images[index];
graphics.drawText("row details", 100, y + 30);
//graphics.drawBitmap(0, y, _bitmap.getWidth(), _bitmap.getHeight(),_bitmap, 0, 0);
mylist.invalidate(index);
}
public class ImageDownloader implements Runnable
{
public void run()
{
for(int i=0; i<size;i++)
{
if(images[i]==null)
{
images[i]=connectServerForImage(urls[i].toString());//replace downloadImage method to whatever method you have to download the bitmap from url
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run()
{
mylist.invalidate();
}
});
}
}
}
}
public Object get(ListField listField, int index) {
// TODO Auto-generated method stub
return null;
}
public int getPreferredWidth(ListField listField) {
// TODO Auto-generated method stub
return 0;
}
public int indexOfList(ListField listField, String prefix, int start) {
// TODO Auto-generated method stub
return 0;
}
public static Bitmap connectServerForImage(String url) {
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
int rc;
Bitmap bitmp = null;
try {
// httpConnection = (HttpConnection)
// Connector.open(url+";interface=wifi");
httpConnection = (HttpConnection) Connector.open(url);
rc = httpConnection.getResponseCode();
// System.out.println("===============================");
Dialog.alert("beore if condition");
if (rc == HttpConnection.HTTP_OK) {
System.out.println(" ============= IN FUNCTION. . . . .");
httpInput = httpConnection.openInputStream();
InputStream inp = httpInput;
byte[] b = IOUtilities.streamToBytes(inp);
EncodedImage hai = EncodedImage.createEncodedImage(b, 0,
b.length);
bitmp = hai.getBitmap();
} else {
throw new IOException("HTTP response code: " + rc);
}
} 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;
}
}
Dont know where i am wrong. Please can any budy help me for the same.
Several problems with your code:
The BitmapLazyLoader class looks like a consumer. It holds a Thread reference. This alone is very confusing, since Runnables are intended to be passed to a Thread constructor, but Runnables should not know about the thread for the sake of encapsulation. Letting this apart, this class attempts to spawn a thread only once, but as you are creating an instance of Runnable each time a row is drawn, you'll end up spawning a considerable number of threads. This will probably end in a TooManyThreadsException being thrown as in BlackBerry the max number of threads is limited to 16 per app. Even if you don reach the limit, performance will degrade as BlackBerries, which sport a single core CPU, you shouldn't have more than 2-3 threads running at the same time. EVEN if you could spawn infinite threads, in BlackBerry you can only have X connections opened at the same time (I think X is 5 for the whole OS, not sure about this). So first of all modify the code to ensure only a single worker thread is downloading images. (and if possible, extract the thread instantiation and launch out of the Runnable class).
When the bitmap is downloaded, you are not doing anything with it. Look at the ImageDownloadCompleted method, it is empty. (BTW, the convention for methods is to start with lowercase) So you should store the bitmap somewhere and call invalidate on your list, which in turn will paint the stored bitmaps.
Hope it helps.
You can try using this link :
http://www.coderholic.com/blackberry-webbitmapfield/
You have to create a separate class named as WebBitmapField as suggested in above link.
How to use that class in your list field image objects:
For every image url create WebBitmapField object
photoList_vector is the vector through which populate elements in
list field
WebBitmapField web = new WebBitmapField("http://www.image1.png");
photoList_vector.addElement(web);
web = new WebBitmapField("http://www.image2.png");
photoList_vector.addElement(web);
Now use this vector to work on your list field......
In the above lines we try to ensure that when we simultaneously send multiple requests to get the images then each image corresponds to a particular WebBitmapField Object.
Each object is then added to vector so that it can be added to the list field.
Each url send is tied to an object of WebBitmapField.
So though request is send in a separate thread it gets tied to its associated object only
Hope it helps
:)
I have worked on this problem, earlier, and I am posting my technique here, though its not ideal solution, as it was coupled very much with Screen class, but still might be helpful.
First in your screen class have one array for bitmaps having size equal to list field items.
public class TempScreen extends MainScreen{
Bitmap[] images=null;
String[] urls={"image1_url", "image2_url".....};
public TempScreen()
{
images=new Bitmap[urls.length];
}
now in drawListRow method of ListFieldCallBack, check for the following:
public void drawListRow(ListField list, Graphics g, int index, int y, int width){
if(bitmap[index]==null)
{
//Load placeholder image
}
else
//Load Bitmap
}
Now create a thread class to download the images:
public class ImageDownloader implements Runnable
{
public void run()
{
for(int i=0; i<size;i++)
{
if(images[i]==null)
{
images[i]=downloadImage(url[i]);//replace downloadImage method to whatever method you have to download the bitmap from url
UiApplication.getUiApplication().invokeLater(new Runnable(){
public void run()
{
list.invalidate()
}
});
}
}
}
}
Now in constructor of the screen class, after setting callback to listfield, start thread:
Thread downloader=new Thread(new ImageDownloader());
downloader.start();
Edit: Change TempScreen constructor to following:
public TempScreen()
{
images=new Bitmap[urls.length];
size = urls.length;
mylist = new ListField();
mylist.setCallback(this);
mylist.setSize(4);
mylist.setRowHeight(getFont().getHeight() * 3);
add(mylist);
Thread downloader=new Thread(new ImageDownloader());
downloader.start();
}
I want to download a .txt file from http server and store it on device memory.How can i do it.I am new to it so any help would be appreciated. Thanks in advance
I am not going to code for you, But i can give you logic for it, as i have already done this kind of work.
You are going to need HttpConnection, DataInutStream,DataOutputStream and FileConnection Class for the same purpose.
Here is a link of an example, it is same as your question's requirement, you need to study it and code for your self.
Hint: Only minor changes require in that code, if you can figure it out.
Use the below code
package com.neel.java.rim.api.net;
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;
import net.rim.device.api.ui.component.Dialog;
public class FileDownloader implements Runnable {
// Holds the URL to download the file
StringBuffer url = null;
//holds the instance of the delegate screen
protected Object delegate;
public FileDownloader(String url) {
// image URL
this.url = new StringBuffer();
this.url.append(url.toString());
}
//taking the instance of the delegate
//this is the object of the active screen from where the request is made
public Object getDelegate() {
return delegate;
}
public void setDelegate(Object delegate) {
this.delegate = delegate;
}
// Thread starts the execution
public void run() {
byte[] dataArray;
InputStream input;
//url.append(updateConnSuffix()); // ad connection suffix for the data usage
HttpConnection httpConn = null;
try {
httpConn = (HttpConnection) Connector.open(url.toString());
input = httpConn.openInputStream();
dataArray = net.rim.device.api.io.IOUtilities.streamToBytes(input);
writeFile(dataArray);
} catch (IOException e) {
e.printStackTrace();
Dialog.alert("Eoor in downloading image");
}
}
public void writeFile(byte[] data){
FileConnection fc = null;
// to save in SD Card
String pFilePath = "SDCard/BlackBerry/pictures/text.txt";
/*use below path for saving in Device Memory*/
//String pFilePath = "store/home/user/pictures/text.txt";
OutputStream lStream = null;
String time = new String();
if (pFilePath != null) {
try {
fc = (FileConnection)Connector.open("file:///" + pFilePath ,Connector.READ_WRITE);
if(null == fc || fc.exists() == false){
fc.create();
}
lStream = fc.openOutputStream(fc.fileSize());
lStream.write(data);
} catch (Exception ioex) {
ioex.printStackTrace();
} finally {
if (lStream != null) {
try {
lStream.close();
lStream = null;
} catch (Exception ioex){
}
}
if (fc != null) {
try {
fc.close();
fc = null;
} catch (Exception ioex){
}
}
}
}
}
}
Here is the paint method of my custom field:
protected void paint(Graphics graphics) {
new downloadImage();
Bitmap img = downloadImage.connectServerForImage(this.poster);
graphics.drawBitmap(0, 0, 100, 150, img, LEFT, TOP);
}
Here is the connectServerForImage method:
public static Bitmap connectServerForImage(String url) {
HttpConnection httpConnection = null;
DataOutputStream httpDataOutput = null;
InputStream httpInput = null;
int rc;
Bitmap bitmp = null;
try {
httpConnection = (HttpConnection) Connector.open(url);
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;
}
I'm putting multiple instances of my custom field into a verticalfieldmanager, but the images slows the scrolling down. It seems as if every time I scroll it runs the paint method again even though the image has already been downloaded.
I'm thinking I will need to download the images in another thread? Someone lead me in the right direction.
You must start any HTTP interaction in a separate thread (no blocking call).
To avoid downloading same image multiple times cache already downloaded image. You can use image download URL as image tag to store
them.
Every time there is a event on screen, paint method will be called. So don't start download an image if it is already downloaded.
Suppose this is my NeteorkingMainScreen class which will display the text retrived from web.
public NetworkingMainScreen() {
setTitle("Networking");
urlField = new EditField("URL:", "");
textOutputField = new RichTextField();
add(urlField);
add(textOutputField);
}
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
menu.add(new MenuItem("Get", 10, 10) {
public void run() {
getURL();
}
});
private void getURL() {
HttpRequestDispatcher dispatcher = new HttpRequestDispatcher(urlField.getText(),"GET", this);
dispatcher.start();
}
//*********************************************************************************
//HttpRequestDispatcher class performs the downloading of contents of webpage.
public class HttpRequestDispatcher extends Thread {
private String url;
private String method; // GET or POST
private NetworkingMainScreen screen;
public HttpRequestDispatcher(String url, String method, NetworkingMainScreen screen){
this.url = url;
this.method = method;
this.screen = screen;
}
public void run() {
try{
HttpConnection connection = (HttpConnection)Connector.open(url);
connection.setRequestMethod(method);
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK){
screen.requestFailed("Unexpected response code: " + responseCode);
connection.close();
return;
}
String contentType = connection.getHeaderField("Content-type");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream responseData = connection.openInputStream();
byte[] buffer = new byte[10000];
int bytesRead = responseData.read(buffer);
while(bytesRead > 0) {
baos.write(buffer, 0, bytesRead);
bytesRead = responseData.read(buffer);
}
baos.close();
connection.close();
screen.requestSucceeded(baos.toByteArray(), contentType);
}
catch (IOException ex) {
screen.requestFailed(ex.toString());
}
}
}
//***************************************************************************
//WaitScreen displays animation till the downloading is completed.
class WaitScreen extends FullScreen
{
}
Now I m getting confused...
When to start the WaitScreen class. Suppose i start by creating an object of WaitScreen and pushing the screen object.
protected void makeMenu(Menu menu, int instance) {
super.makeMenu(menu, instance);
menu.add(new MenuItem("Get", 10, 10) {
public void run()
UiApplication.getUiApplication.pushScreen(new WaitScreen());
getURL();
}
});
How would my code know that it should displaying the animated Screen and display the contents of the webpages ie i mean how my code will knows downloading data has been completed. ie when i will call popScreen()?
I interface is to be used how can use the interface and what help we will get by using the interface.? Plz help
This is rather simple.
Your HttpRequestDispatcher should have a handle to the WaitScreen instance to be able to show it on start and close it upon completion.
So inside of the HttpRequestDispatcher you could (1) create the WaitScreen. (2) Push it. (3) Do the stuff the HttpRequestDispatcher should do. (4) Pop the the WaitScreen. Smth like that:
final WaitScreen waitScreen = new WaitScreen();
// just to reduce code duplication
final UiApplication app = UiApplication.getUiApplication();
// we are on the non-UI thread, so need
// to use UiApplication.invokeLater(Runnable action),
// it safely runs the passed action on the UI thread
app.invokeLater(new Runnable() {
public void run() {
app.pushScreen(waitScreen);
}
});
try {
// main networking actions go here
} catch (..) {
// error handling goes here
} finally {
// make sure we close the waitScreen
app.invokeLater(new Runnable() {
public void run() {
app.popScreen(waitScreen);
}
});
}
Here, Try this. All you have to do is put your code into the "run" function.
If you want help with the HttpRequest stuff or have trouble with the classes there, let me know. I have a web library with thread classes set up to use the classes within that post.