In my application we have to download around 10 Images from server and display it in mobile. How can I do this? Can I use same HttpConnection for full download? Is any other way for download?
You can do with this simple loop (Supposing imageList is a List with the url of the images).
HttpConnection = null;
Image image = null;
for (int i = 0; i < imageList.getSize(); i++) {
try{
String urlImage = imageList.get(i);
hc = (HttpConnection) Connector.open(urlImage);
image = Image.createImage(hc.openInputStream()));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
hc.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
You can try following method in a loop for downloading images from server.
private void downloadImage ( String URL )
{
try
{
System.out.println("URL FOR POST_DATA : "+URL);
// Open up a http connection with the Web server for both send and receive operations
httpConnection = (HttpConnection)Connector.open(URL, Connector.READ_WRITE);
// Set the request method to POST
httpConnection.setRequestMethod(HttpConnection.POST);
// Set the request headers
httpConnection.setRequestProperty(ConstantCodes.ACTION_MODE_PARAMETER,action);
httpConnection.setRequestProperty(ConstantCodes.USER_NAME_REQUEST_PARAMETER,userName);
if(eventName==null || eventName.equals(""))
eventName="default";
httpConnection.setRequestProperty(ConstantCodes.EVENT_NAME_REQUEST_PARAMETER, eventName);
httpConnection.setRequestProperty(ConstantCodes.CAMERAID_REQUEST_PARAMETER, cameraID);
// all the headers are sending now and connection chanel is establising
dis = httpConnection.openDataInputStream();
int ch = 0;
ByteArrayOutputStream bytearray = new ByteArrayOutputStream(250000);
while((ch = dis.read()) != -1)
bytearray.write(ch);
// fileByte contains whole file in bytes
byte fileByte[] = bytearray.toByteArray();
fileSize = fileByte.length;
System.out.println("Got file size : "+fileSize);
if(bytearray!=null) bytearray.close();
midlet.getLastPostedImageResponse(fileByte);
}
catch (IOException ioe)
{
ioe.printStackTrace();
System.out.println("IOException occured during getting last image data : "+ioe.getMessage());
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Eeception occurred during getting last image data : "+e.getMessage());
}
finally
{
System.out.println("Calling close from Last image posted Action");
close();
}
Related
i have created an application in J2ME that uses the following method to connect to a server. php is used on the Server side to process the requests. the application works fine on some phones like NOkia asha 303 but throws IOException on other phones what could be the problem with this code. this method is called on a different thread. i also want to ask if you use post in j2me and set the
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
do you have to urlencode the data before sending or that is handled automatically by j2me
public String sendData(String serverUrl, String dataToSend) {
String strResponse = "0"; //string to hold serverResponse
StringBuffer sb = new StringBuffer("");
HttpConnection httpConn = null;
InputStream inputStream = null;
OutputStream outStream = null;
try {
//convert the dataToSend to bytes
String strData = dataToSend; // get the data to Send and store it in a variable.
byte[] dataToSendBytes = strData.getBytes();
//open the Connection to the server.
httpConn = (HttpConnection) Connector.open(serverUrl, Connector.READ_WRITE, true);
if (httpConn != null) {
httpConn.setRequestMethod(HttpConnection.POST); // method used to send the data.
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1");
//httpConn.setRequestProperty("Content-Language", "en-US"); //language to use.
//setRequestProperty("Connection", "close") ===> could generate or Solve IOExceptions on different mobile Phones.
//httpConn.setRequestProperty("Connection", "close");
//setting the Content-length could have issues with some Servers===>
//if the dataToSend is Empty String => contentLen = 0 , else get length of the dataBytes.
String contentLen = ((dataToSend.length() > 0) ? Integer.toString(dataToSendBytes.length) : Integer.toString(0));
//httpConn.setRequestProperty("Content-length", contentLen); //not working on Emulator ....enable on shipping application.
//open the output Stream to send data to the Server.
outStream = httpConn.openOutputStream();
// send the bytes of data to the Server.===>
//outStream.write(dataToSendBytes);
//send the data bytes to the Server.
int byteLen = dataToSendBytes.length; //length of byteToSend.
for (int k = 0; k < byteLen; k++) {
//send all the databytes to the Server.
outStream.write(dataToSendBytes[k]);
}
//close the outputStream ===immediately after sending the data bytes to the Server===>eliminates the IOExceptions.
closeOutStream(outStream);
//get response code on Sending Data===> getting response code automatically flushes the output data.
ntworkResponseCode = httpConn.getResponseCode();
if (ntworkResponseCode == HttpConnection.HTTP_OK) {
//connection to the Server was okay.
if (httpConn != null) {
//read the Response From the Server-----------
inputStream = httpConn.openInputStream(); // open the inputStream.
//get server Response Content length.
int contLen = (int) httpConn.getLength();
byte[] serverResponseBytes; //byte array to store the serverResponse.
if (contLen != -1) {
//store the serverResponse to a byte array.===> using a byte buffer could be faster.
serverResponseBytes = new byte[contLen];
inputStream.read(serverResponseBytes);
//convert the bytes to String and store them to the StringBuffer.
sb.append(new String(serverResponseBytes));
} else {
//serverResponse Length not available===> read character by character could be slower.
int read;
while ((read = inputStream.read()) != -1) {
sb.append((char) read);
}
}
//store the server response in a String.
strResponse = sb.toString();
}
} else {
//connection problem occured.
//throw new IOException("Http Response Code [" + ntworkResponseCode + "]");
}
}// the httpConnection Not null.--end.
} catch (IllegalArgumentException arge) {
strResponse = CONNECTION_EXCEPTION;
} catch (ConnectionNotFoundException cone) {
//a string to show we got an exception
strResponse = CONNECTION_EXCEPTION;
} catch (IOException ioe) {
//a string to show we got an exception
strResponse = CONNECTION_EXCEPTION;
} catch (SecurityException se) {
//user cancelled the Connection Request.
strResponse = CONNECTION_EXCEPTION;
} finally {
//close all the connection streams
try {
if (inputStream != null) {
//close the inputStream
inputStream.close();
inputStream = null;
}
if (outStream != null) {
//close the outStream.
outStream.close();
outStream = null;
}
if (httpConn != null) {
//close the connection object.
httpConn.close();
httpConn = null;
}
} catch (IOException ie) {
//show exception occured.
}
}
//return server Response to the Client.
return strResponse;
}
I am developing an j2me application which is communicating with the database using servlet.
I want to store the data received from servlet into record store and display it.how this can be achieved?Please provide code examples.
Thank you in advance
public void viewcon()
{
StringBuffer sb = new StringBuffer();
try {
HttpConnection c = (HttpConnection) Connector.open(url);
c.setRequestProperty("User-Agent","Profile/MIDP-1.0, Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language","en-US");
c.setRequestMethod(HttpConnection.POST);
DataOutputStream os = (DataOutputStream)c.openDataOutputStream();
os.flush();
os.close();
// Get the response from the servlet page.
DataInputStream is =(DataInputStream)c.openDataInputStream();
//is = c.openInputStream();
int ch;
sb = new StringBuffer();
while ((ch = is.read()) != -1) {
sb.append((char)ch);
}
// return sb;
showAlert(sb.toString());//display data received from servlet
is.close();
c.close();
} catch (Exception e) {
showAlert(e.getMessage());
}
}
Put this function call where you show the response data alert
writeToRecordStore(sb.toString().getBytes());
The function definition is as below:
private static String RMS_NAME = "NETWORK-DATA-STORAGE";
private boolean writeToRecordStore(byte[] inStream) {
RecordStore rs = null;
try {
rs = RecordStore.openRecordStore(RMS_NAME, true);
if (null != rs) {
//Based on your logic either ADD or SET the record
rs.addRecord(inStream, 0, inStream.length);
return true;
} else {
return false;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
return false;
} finally {
try {
if (null != rs) {
rs.closeRecordStore();
}
} catch (RecordStoreException recordStoreException) {
} finally {
rs = null;
}
}
}
After you have saved the data, read the records store RMS-NAME and check the added index to get the response data.
.
NOTE: The assumption is the network response data is to be appended to the record store. If you want to set it to a particular record modify the method writeToRecordStore(...) accordingly.
//this code throws exception in display class.
try
{
byte[] byteInputData = new byte[5];
int length = 0;
// access all records present in record store
for (int x = 1; x <= rs.getNumRecords(); x++)
{
if (rs.getRecordSize(x) > byteInputData.length)
{
byteInputData = new byte[rs.getRecordSize(x)];
}
length = rs.getRecord(x, byteInputData, 0);
}
alert =new Alert("reading",new String(byteInputData,0,length),null,AlertType.WARNING);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert);
}
I am posting some data to server but i am getting {"status":false,"error":"Invalid API Key."} response from server. My API Key is correct but where is the problem i don't know. Please friends help me. I tried lot but i did not find solution. I have used following code for posting data to server.
public void tryingOne(String dtl){
HttpConnection httpConn = null;
InputStream is = null;
OutputStream os = null;
String url="http://api.geanly.in/ma/index?API-Key="+apikey;
String details = "&orderInfo={\"booking\":{\"restaurantinfo\":{\"id\":\"5722\"},\"referrer\":{\"id\": \"9448476530\" }, \"bookingdetails\":{\"instructions\":\"Make the stuff spicy\",\"bookingtime\": \"2011-11-09 12:12 pm\", \"num_guests\": \"5\"}, \"customerinfo\":{\"name\":\"Vinodh SS\", \"mobile\":\"9345245530\", \"email\": \"vind#gmail.com\", \"landline\":{ \"number\":\"0908998393\",\"ext\":\"456\"}}}}";
try {
System.out.println("url####"+url);
httpConn = (HttpConnection) Connector.open(url);
httpConn.setRequestMethod(HttpConnection.POST);
DataOutputStream outStream = new DataOutputStream(httpConn.openDataOutputStream());
outStream.write(details.getBytes(),0,details.length());
outStream.flush();
outStream.close();
//Reading Resp. from server
StringBuffer sb = new StringBuffer();
is = httpConn.openDataInputStream();
int chr;
while ((chr = is.read()) != -1) {
sb.append((char) chr);
}
System.out.println("Response from srvr " + sb.toString());
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (httpConn != null) {
try {
httpConn.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Please help me friends...
Thanks
you need to trim the variable "apikey".
I was getting same problem when connecting with Picasa Server.
For sending data using HttpConnection use the class in this tutorial. It also gets the response from the server.
Using the bluetooth API in j2me, I want to send a message to another mobile phone. I have been able to discover devices and services on the corresponding devices. I have also been able to connect to the services however when I try to send a message from the server to the client. The message is written but the client does not seem to receive it ..
public void startServer() throws IOException {
UUID uuid = new UUID("1101", false);
//Create the service url
String connectionString = "btspp://localhost:" + uuid + ";name=xyz";
//open server url
StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier) Connector.open(connectionString);
//Wait for client connection
System.out.println("\nServer Started. Waiting for clients to connect...");
StreamConnection connection = streamConnNotifier.acceptAndOpen();
RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
System.out.println("Remote device address: " + dev.getBluetoothAddress());
System.out.println("Remote device name: " + dev.getFriendlyName(true));
Survey.setTitle(dev.getFriendlyName(true));
//read string from spp client
try {
DataInputStream in = connection.openDataInputStream();
OutputStream writer=connection.openDataOutputStream();
String str="";
TextField textfield;
for (int i=0;i<questions.size();i++){
textfield = (TextField) questions.elementAt(i);
str += formatSurvey(textfield,i)+"&";
}
writer.write(str.getBytes(), 0, str.getBytes().length);
writer.flush();
System.out.println("Written to client "+str);
System.out.println("Reading "+in.readUTF());
try {
displaySurveyresults(str);
}
catch(Exception e){
System.out.println(e.getMessage());
}
streamConnNotifier.close();
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
switchDisplayable(null , getList1());
list1.append(servRecord.toString(), null);
System.out.println("Service discovered..."+servRecord.toString());
for (int i=0;i<servRecord.length;i++){
try {
System.out.println("Test1");
//StreamConnection con = (StreamConnection) Connector.open(servRecord[i].getConnectionURL(0 , false));
String connURL = servRecord[0].getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
// Open connection
StreamConnection con = (StreamConnection) Connector.open(connURL);
System.out.println("Test2");
DataInputStream in = con.openDataInputStream();
System.out.println("Test3"+in.readUTF());
//con.openDataOutputStream().write(142);
System.out.println("Test4 "+in.available());
byte[] bte=new byte[in.available()];
System.out.println("Test5 "+bte.length);
in.read(bte);
System.out.println("Test6");
for (int l=0;l<bte.length;l++){
System.out.println(bte[i]);
System.out.println("Test7");
stringItem.setText(stringItem.getText()+1 + bte[i]);
}
OutputStream outStream=con.openOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(outStream);
writer.write("Vimal");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
have I erred somewhere bcause these are codes from the Net?
Try replacing new UUID("1101", false); with new UUID(0x1101);.
I'm trying to play a recorded wave file. While playing, an exception is thrown at the following statement:
Player player = Manager.createPlayer(is, "audio/mpeg");
My entire code for playing the wave file is as follows:
if (types[cnt].equals("audio/x-wav")) {
Class clazz = Class.forName("RecordAudio");
InputStream is =
clazz.getResourceAsStream("file:///SDCard/BlackBerry/original.wav");
//create an instance of the player from the InputStream
Player player = Manager.createPlayer(is, "audio/mpeg");
player.realize();
player.prefetch();
//start the player
player.start();
}
What could be the problem?
The function getResourceAsStream is for pulling resources from a JAR/COD file, not from the filesystem. Plus, this is simpler than you are making it. Just pass the file name and path to createPlayer, like so:
try {
String filename = "file:///SDCard/BlackBerry/original.wav";
Player player = javax.microedition.media.Manager.Manager.createPlayer( filename );
} catch (IOException e) {
System.out.println("Error creating player");
} catch (MediaException e) {
System.out.println("Error media type");
}
I believe it is because of wrong MIME type. Try this:
String fileName = "file:///SDCard/BlackBerry/original.wav";
String mimeType = "audio/x-wav";
String types[] = javax.microedition.media.Manager
.getSupportedContentTypes(null);
for (int cnt = types.length - 1; cnt >= 0; --cnt) {
if (types[cnt].equals(mimeType)) {
InputStream is = null;
FileConnection fconn = null;
try {
fconn = (FileConnection) Connector.open(
fileName, Connector.READ);
} catch (IOException e) {
System.out.println("Error reading file");
}
try {
is = fconn.openInputStream();
} catch (IOException e) {
System.out.println("Error opening stream");
}
Player player = null;
try {
player =
javax.microedition.media.Manager.createPlayer(
is, mimeType);
} catch (IOException e) {
System.out.println("Error creating player");
} catch (MediaException e) {
System.out.println("Error media type");
}
try {
player.realize();
} catch (MediaException e) {
System.out.println("Player cannot be released");
}
try {
player.prefetch();
} catch (MediaException e) {
System.out.println("Player cannot be prefetched");
}
// start the player
try {
player.start();
} catch (MediaException e) {
System.out.println("Player cannot be started");
}
}
}
Also see in console what kind of exception was thrown.