J2ME http post error - Nokia Asha SDK 1.0 - java-me

I am making a http-post request from my J2ME app for Nokia Asha 501(s40). I'm using the Nokia Asha SDK 1.0 for development.
Once the app tries to make http connection it goes directly into the finally clause of try-catch statement without throwing any exceptions.
In the emulator, the following message is displayed - "Something went wrong with running this app" - Screenshot-link
I then tried the sample http-post source code given in the Nokia developer forum and got the same result.
The code is given below.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class HttpPOST extends MIDlet implements CommandListener {
private static String defaultURL = "http://localhost/api/signin";
private Display myDisplay = null;
private Form mainScreen;
private TextField requestField;
private Form resultScreen;
private StringItem resultField;
Command sendCommand = new Command("SEND", Command.OK, 1);
Command backCommand = new Command("BACK", Command.OK, 1);
public HttpPOST()
{
myDisplay = Display.getDisplay(this);
mainScreen = new Form("Type in a URL:");
requestField = new TextField(null, defaultURL, 100, TextField.URL);
mainScreen.append(requestField);
mainScreen.addCommand(sendCommand);
mainScreen.setCommandListener(this);
}
public void startApp() {myDisplay.setCurrent(mainScreen);}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void commandAction(Command c, Displayable s)
{
if (c == sendCommand)
{
String urlstring = requestField.getString();
String resultstring = sendPostRequest(urlstring);
resultScreen = new Form("POST Result:");
resultField = new StringItem(null, resultstring);
resultScreen.append(resultField);
resultScreen.addCommand(backCommand);
resultScreen.setCommandListener(this);
myDisplay.setCurrent(resultScreen);
}
else if (c == backCommand)
{
requestField.setString(defaultURL);
myDisplay.setCurrent(mainScreen);
}
}
public String sendPostRequest(String urlstring)
{
HttpConnection hc = null;
DataInputStream dis = null;
DataOutputStream dos = null;
String message = "";
String requeststring = "email=test#gmail.com&password=1234";
try
{
hc = (HttpConnection) Connector.open(urlstring, Connector.READ_WRITE);
hc.setRequestMethod(HttpConnection.POST);
dos = hc.openDataOutputStream();
byte[] request_body = requeststring.getBytes();
for (int i = 0; i < request_body.length; i++)
{
dos.writeByte(request_body[i]);
}
// flush outdos.flush();
dis = new DataInputStream(hc.openInputStream());
int ch;
while ((ch = dis.read()) != -1)
{
message = message + (char) ch;
}
}
catch (IOException ioe)
{
message = "ERROR";
}
finally
{
try
{
if (hc != null)
hc.close();
}
catch (IOException ignored)
{
}
try
{
if (dis != null)
dis.close();
}
catch (IOException ignored)
{
}
try
{
if (dos != null)
dos.close();
}
catch (IOException ignored)
{
}
}
return message;
}
}
Somebody please help me out in solving this issue.
Thanks in advance.

Please find below an example. It will helpful to somebody. It is tested in Nokia Asha 501, It is perfectly working.
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
public class GetNpost extends MIDlet implements CommandListener
{
private Display display; // Reference to Display object
private Form fmMain; // The main form
private Alert alError; // Alert to error message
private Command cmGET; // Request method GET
private Command cmPOST; // Request method Post
private Command cmExit; // Command to exit the MIDlet
private TextField tfAcct; // Get account number
private TextField tfPwd; // Get password
private StringItem siBalance;// Show account balance
private String errorMsg = null;
GetNetworkConnection getObject = null;
PostNetworkConnection postObject = null;
GetNpost mainObject = null;
public GetNpost()
{
display = Display.getDisplay(this);
mainObject = this;
// Create commands
cmGET = new Command("GET", Command.SCREEN, 2);
cmPOST = new Command("POST", Command.SCREEN, 3);
cmExit = new Command("Exit", Command.EXIT, 1);
// Textfields
tfAcct = new TextField("Account:", "", 5, TextField.NUMERIC);
tfPwd = new TextField("Password:", "", 10, TextField.ANY | TextField.PASSWORD);
// Balance string item
siBalance = new StringItem("Balance: $", "");
// Create Form, add commands & componenets, listen for events
fmMain = new Form("Account Information");
fmMain.addCommand(cmExit);
fmMain.addCommand(cmGET);
fmMain.addCommand(cmPOST);
fmMain.append(tfAcct);
fmMain.append(tfPwd);
fmMain.append(siBalance);
fmMain.setCommandListener(this);
}
public void startApp()
{
display.setCurrent(fmMain);
}
public void pauseApp()
{ }
public void destroyApp(boolean unconditional)
{ }
public void commandAction(Command c, Displayable s)
{
if (c == cmGET || c == cmPOST)
{
try
{
if (c == cmGET){
getObject = new GetNetworkConnection();
getObject.start();
}
else{
postObject = new PostNetworkConnection();
postObject.start();
}
}
catch (Exception e)
{
System.err.println("Msg: " + e.toString());
}
}
else if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
}
/*--------------------------------------------------
* Access servlet using GET
*-------------------------------------------------*/
private void lookupBalance_withGET() throws IOException
{
HttpConnection http = null;
InputStream iStrm = null;
boolean ret = false;
// Data is passed at the end of url for GET
// don't use localhost as a ip
String url = "http://(ip address):(port)/ServerSide/hello" + "?" +
"account=" + tfAcct.getString() + "&" +
"password=" + tfPwd.getString();
try
{
http = (HttpConnection) Connector.open(url);
//----------------
// Client Request
//----------------
// 1) Send request method
http.setRequestMethod(HttpConnection.GET);
// 2) Send header information - none
// 3) Send body/data - data is at the end of URL
//----------------
// Server Response
//----------------
iStrm = http.openInputStream();
// Three steps are processed in this method call
ret = processServerResponse(http, iStrm);
}
finally
{
// Clean up
if (iStrm != null)
iStrm.close();
if (http != null)
http.close();
}
// Process request failed, show alert
if (ret == false)
showAlert(errorMsg);
}
/*--------------------------------------------------
* Access servlet using POST
*-------------------------------------------------*/
private void lookupBalance_withPOST() throws IOException
{
HttpConnection http = null;
OutputStream oStrm = null;
InputStream iStrm = null;
boolean ret = false;
// Data is passed as a separate stream for POST (below)
// don't use localhost as a ip
String url = "http://(ip address):(port)/ServerSide/hello";
try
{
http = (HttpConnection) Connector.open(url);
//----------------
// Client Request
//----------------
// 1) Send request type
http.setRequestMethod(HttpConnection.POST);
// 2) Send header information. Required for POST to work!
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
oStrm = http.openOutputStream();
// If you experience connection/IO problems, try
// removing the comment from the following line
// http.setRequestProperty("Connection", "close");
// 3) Send data/body
// Write account number
byte data[] = ("account=" + tfAcct.getString()).getBytes();
oStrm.write(data);
// Write password
data = ("&password=" + tfPwd.getString()).getBytes();
oStrm.write(data);
// For 1.0.3 remove flush command
// See the note at the bottom of this file
// oStrm.flush();
//----------------
// Server Response
//----------------
iStrm = http.openInputStream();
// Three steps are processed in this method call
ret = processServerResponse(http, iStrm);
}
catch(Exception e){
System.out.println("Error in Post: "+e.getMessage());
}
finally
{
// Clean up
if (iStrm != null)
iStrm.close();
if (oStrm != null)
oStrm.close();
if (http != null)
http.close();
}
// Process request failed, show alert
if (ret == false)
showAlert(errorMsg);
}
/*--------------------------------------------------
* Process a response from a server
*-------------------------------------------------*/
private boolean processServerResponse(HttpConnection http, InputStream iStrm) throws IOException
{
//Reset error message
errorMsg = null;
// 1) Get status Line
if (http.getResponseCode() == HttpConnection.HTTP_OK)
{
// 2) Get header information - none
// 3) Get body (data)
int length = (int) http.getLength();
String str;
if (length != -1)
{
byte servletData[] = new byte[length];
iStrm.read(servletData);
str = new String(servletData);
}
else // Length not available...
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1)
bStrm.write(ch);
str = new String(bStrm.toByteArray());
bStrm.close();
}
// Update the string item on the display
siBalance.setText(str);
return true;
}
else
// Use message from the servlet
errorMsg = new String( http.getResponseMessage());
return false;
}
/*--------------------------------------------------
* Show an Alert
*-------------------------------------------------*/
private void showAlert(String msg)
{
// Create Alert, use message returned from servlet
alError = new Alert("Error", msg, null, AlertType.ERROR);
// Set Alert to type Modal
alError.setTimeout(Alert.FOREVER);
// Display the Alert. Once dismissed, display the form
display.setCurrent(alError, fmMain);
}
public class GetNetworkConnection extends Thread{
public void run(){
try {
mainObject.lookupBalance_withGET();
}
catch(Exception e){
System.out.println("Error in Get Connection: "+e.getMessage());
}
}
}
public class PostNetworkConnection extends Thread{
public void run(){
try {
mainObject.lookupBalance_withPOST();
}
catch(Exception e){
System.out.println("Error in Post Connection: "+e.getMessage());
}
}
}
}
The server side code is, (It is a servlet. Name is hello.java)
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author thirumalvalavan
*/
#WebServlet(name = "hello", urlPatterns = {"/hello"})
public class hello extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// /*TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet hello</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet hello at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
// */
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
String acct = request.getParameter("account"),
pwd = request.getParameter("password");
System.out.println("Hello Get Method::: " + acct + " " + pwd);
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet hello</title>");
out.println("</head>");
out.println("<body>");
out.print("<h1>Hi Get Method: </h1> <br> <h2> Your Account is: " + acct + "<br> Your pwd is: " + pwd + "</h2>");
out.println("</body>");
out.println("</html>");
out.close();
}
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
String acct = request.getParameter("account"),
pwd = request.getParameter("password");
System.out.println("Hello Post Method::: " + acct + " " + pwd);
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet hello</title>");
out.println("</head>");
out.println("<body>");
out.print("<h1>Hi Post Method: </h1> <br> <h2> Your Account is: " + acct + "<br> Your pwd is: " + pwd + "</h2>");
out.println("</body>");
out.println("</html>");
out.close();
}
/**
* Returns a short description of the servlet.
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

Related

Download File using download manager and save file based on click

I have my download manager, and it work perfect if I try to download a file. But I have a problem.
I have 4 CardView in my activity and I set it onClickListener, so when I click one CardView it will download the file.
Here is the code to call the download function
cardviewR1 = findViewById(R.id.card_viewR1);
cardviewR1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pDialogDL = new ProgressDialog(this);
pDialogDL.setMessage("A message");
pDialogDL.setIndeterminate(true);
pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialogDL.setCancelable(true);
final DownloadTask downloadTask = new DownloadTask(this);
downloadTask.execute(R1Holder);
pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
});
and here is the download function
private class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
private PowerManager.WakeLock mWakeLock;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
return null;
}
total += count;
// publishing the progress....
if (fileLength > 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
pDialogDL.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
pDialogDL.setIndeterminate(false);
pDialogDL.setMax(100);
pDialogDL.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
mWakeLock.release();
pDialogDL.dismiss();
if (result != null)
Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
}
}
The code work in my app, but the problem is, when I try to add second CardView which is like this
cardviewR2 = findViewById(R.id.card_viewR2);
cardviewR2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pDialogDL = new ProgressDialog(this);
pDialogDL.setMessage("A message");
pDialogDL.setIndeterminate(true);
pDialogDL.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialogDL.setCancelable(true);
final DownloadTask downloadTask = new DownloadTask(this);
downloadTask.execute(R2Holder);
pDialogDL.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
}
});
}
});
Yes it will download the second file, but it will overwrite the first file. I think the problem is right here
output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/"+getString(R.string.r1)+"_"+NameHolder+".zip");
Anyone can help me with this code?
I need your help, Thanks
Fixed it by create a new Download Class separately in different file with activity, so the AsyncTask will be call again and again
thanks

Create an custom appender in log4j which stores the log in memory

I want to create an custom appender using log4j in java programatically which stores the log in memory(Certain size will be defined for e.g. say DEFAULT_SIZE=20) & as soon as memory is full(there are 20 logs in memory) create an json array of those logs and send it to the server. Along with log message i also want information such as (class, file name,line number,method name,level etc.)
Help is appreciated.!!!
Updated ::
Below is the source code developed by me for the same . Problem which i am facing is i get line number, method name,file name as "?".I dont understand what is the reason.
package com.any.logger;
import java.util.ArrayList;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
public class Log4jAppender extends AppenderSkeleton {
private static final int DEFAULT_BUFFER_SIZE = 20;
private ArrayList<LoggingEvent> buffer;
private int bufferSize;
public Log4jAppender() {
this.bufferSize = Log4jAppender.DEFAULT_BUFFER_SIZE;
this.buffer = new ArrayList<LoggingEvent>();
}
public void close() {
}
public boolean requiresLayout() {
return false;
}
#Override
protected void append(LoggingEvent loggingEvent) {
synchronized (buffer) {
if (buffer.size() >= bufferSize) {
try {
System.out.println("Hello");
Log4jService service = new Log4jService(new ArrayList<LoggingEvent>
(buffer));
System.out.println("Buff >");
service.start();
} catch (Exception e) {
System.err.println("Failed to write logs");
e.printStackTrace();
} finally {
buffer.clear();
}
}
}
buffer.add(loggingEvent);
}
}
package com.any.logger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.log4j.Level;
import org.apache.log4j.spi.LoggingEvent;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
#SuppressWarnings("rawtypes")
public class Log4jService implements Runnable {
private ArrayList<LoggingEvent> buffer;
private Thread t;
private boolean flag;
public Log4jService(ArrayList<LoggingEvent> buffer) {
this.buffer = new ArrayList<LoggingEvent>(buffer);
this.flag = false;
}
public void start() {
if (!flag) {
this.flag = true;
this.t = new Thread(this);
this.t.start();
}
}
public void run() {
if (flag) {
String json = getLogJson(buffer);
}
}
/**
* Method to get the json log
*
* #param logEvents
* arrayList of log events
* #return an String which is json file
* #throws JSONException
*/
private String getLogJson(ArrayList<LoggingEvent> logEvents) {
System.out.println("In getLogJson");
JSONObject logger = new JSONObject();
try {
JSONArray logs = new JSONArray();
String message = "";
String time = "";
String level = "";
String tag = "";
String file = "";
String exceptionName = "";
String exceptionReason = "";
String line = "";
String clas = "";
String method = "";
int index = 0;
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (Iterator i = logEvents.iterator(); i.hasNext();) {
LoggingEvent logEvent = (LoggingEvent) i.next();
boolean chk=logEvent.locationInformationExists();
System.out.println("Check :: "+chk);
clas=logEvent.getClass().toString();
JSONObject log = new JSONObject();
message = logEvent.getMessage().toString();
time = String.valueOf(formatter.format(logEvent.getTimeStamp()));
level = logEvent.getLevel().toString();
if (chk) {
System.out.println("hello");
file = logEvent.getLocationInformation().getFileName();
line = logEvent.getLocationInformation().getLineNumber();
method = logEvent.getLocationInformation().getMethodName();
}
if (logEvent.getLevel() == Level.ERROR || logEvent.getLevel() ==
Level.FATAL) {
exceptionReason = message;
}
log.put("message", message);
log.put("time", time);
log.put("level", level);
log.put("tag", tag);
log.put("file", file);
log.put("exceptionName", exceptionName);
log.put("exceptionReason", exceptionReason);
log.put("line", line);
log.put("class", clas);
log.put("method", method);
logs.put(index, log);
index++;
}
JSONObject logsObj = new JSONObject();
logsObj.put("logs", logs);
logger.put("log", logsObj);
System.out.println("Logs Array :: " + logsObj);
System.out.println("Logger Object :: " + logger);
} catch (Exception e) {
e.printStackTrace();
}
return logger.toString();
}
}
I would look at the source code for log4j2 and use an existing appender as a template for my custom appender. SocketAppender and TCPSocketManager may be good places to start.
http://logging.apache.org/log4j/2.0/log4j-core/xref/org/apache/logging/log4j/core/net/TCPSocketManager.html
Currently the buffering is based on the number of bytes, not event count. If you follow the existing appender/manager pattern then in your custom appender manager you will need to have a large enough buffer and flush every 20 events. (Perhaps also flush after some timeout? You may only get 19 events and nothing after that...)
You could also do the buffering in the appender, keep a list of event objects there and only call pass them to the manager to be written after some threshold is reached.
The default Layout for SocketAppender will use java serialization. You'll need to roll your own JasonLayout. The log event object has all the details you mentioned.

Pass String from thread to UI for display

I am new to android and java programming. I am try to write a program to read data via bluetooth.
I trying to pass a String apple which I decipher from my bluetooth input data from my thread to my UI for display CalibrationActivity.
I am using handler for the passing.
I keep getting force quit. Can anyone please advice me how can I solve this problem.
Below is my entire code of my extend Thread.
package com.android.backend.data.bluetooth;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.android.AutoActivity;
import com.android.CalibrationActivity;
import com.android.ui.UIManager;
public class Connection extends Thread {
final Connection tt = this;
private final String TAG = "Connection"; // Class name for logging
public boolean connected = false;
public BluetoothSocket bSocket = null;
public InputStream mmInStream = null;
public OutputStream mmOutStream = null;
public ArrayList<String> message = new ArrayList<String>();
public BluetoothDevice currentDevice = null;
public UIManager mgr;
public boolean connectFailure = false;
public boolean stopAutoConnect = false;
public String type = null;
public AutoActivity ff;
public void bsocketcancel() {
try {
bSocket.close();
} catch (IOException e) { }
}
public Connection(UIManager mgr, BluetoothDevice device, String message,
String type) {
this.mgr = mgr;
currentDevice = device;
this.message.add(message);
this.type = type;
}
public Connection(UIManager mgr, BluetoothDevice device, ArrayList<String> message,
String type) {
this.mgr = mgr;
currentDevice = device;
this.message = message;
this.type = type;
}
#Override
public void run() {
if (type.compareToIgnoreCase("Manual") == 0) {
Log.d("thread", "manual");
if (!connected)
connect(currentDevice);
if (bSocket != null){
for(String msg : message)
write(msg.getBytes());
}
mgr.hideConnectingProgressBox();
if(connected){
mgr.connectedDialog();
System.out.println("Maunal connected");
}
Log.d("thread", "hideprogressBox");
if (!connected)
mgr.showConnectionErrBox();
}
if (type.compareToIgnoreCase("auto") == 0){
Log.d("thread", "auto");
stopConnection();
int i = 0;
while (true) { //Set to 5 second
if (!connected)
connect(currentDevice);
if (bSocket != null){
for(String msg : message)
write(msg.getBytes());
}
mgr.hideConnectingProgressBox();
Log.d("thread", "hideprogressBox");
if (!connected) {
mgr.connecting();
}
if (connected) {
mgr.connectedDialog();
bsocketcancel();
System.out.println("Auto connected");
//BluetoothManager.getInstance().disconnectAll(); // cut all connection after transmit
break;
}
if(stopAutoConnect){
mgr.cancelconnecting();
break;
}
}
}
if (type.compareToIgnoreCase("calibrate") == 0) {
Log.d("thread", "calibrate");
if (!connected)
connect(currentDevice);
if (bSocket != null){
for(String msg : message)
write(msg.getBytes());
}
mgr.hideConnectingProgressBox();
if(connected){
mgr.connectedDialog();
mgr.msgsent();
System.out.println("Calibration connected");
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytes;
String apple = "";
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
if ( bytes != -1){
while ((bytes==bufferSize)&&(buffer[bufferSize-1] != 0)){
apple = apple + "_" + new String(buffer, 0, bytes);
bytes = mmInStream.read(buffer);
}
apple = apple + new String(buffer, 0, bytes -1);
System.out.println("message " + apple);
//pass data to UI CalibrationActivity
System.out.println("message out " + apple);
Message msga = mhandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("key", apple);
msga.setData(bundle);
mhandler.sendMessage(msga);
}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
break;
}
}
}
Log.d("thread", "hideprogressBox");
if (!connected){
mgr.showConnectionErrBox();
}
}
}
public void connect(BluetoothDevice device) {
currentDevice = device;
BluetoothSocket tmp = null;
BluetoothManager.getInstance().getBluetoothAdapter().cancelDiscovery();
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
// tmp = device
// .createRfcommSocketToServiceRecord(BluetoothManager.SerialPortServiceClass_UUID);
Method m = device.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
tmp = (BluetoothSocket) m.invoke(device, 1);
// } catch (IOException e) {
// Log.e(TAG, "create() failed", e);
// return;
} catch (Exception e) {
Log.e(TAG, "Socket connection failed", e);
return;
}
bSocket = tmp;
try {
bSocket.connect();
} catch (IOException e1) {
Log.e(TAG, "Connection err", e1);
connectFailure = true;
return;
}
if (tmp != null) {
// Get Input/output stream for Socket
try {
mmInStream = bSocket.getInputStream();
mmOutStream = bSocket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
return;
}
}
connected = true;
connectFailure = false;
}
private Handler mhandler;
public void read(){
Log.i(TAG, "Read is running");
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytes;
String a = "";
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
if ( bytes != -1){
while ((bytes==bufferSize)&&(buffer[bufferSize-1] != 0)){
a = a + new String(buffer, 0, bytes);
bytes = mmInStream.read(buffer);
}
a = a + new String(buffer, 0, bytes -1);
System.out.println("message " + a);
}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
break;
}
}
}
public void write(byte[] buffer) {
if (mmOutStream != null) {
try {
mmOutStream.write(buffer);
Log.d(TAG, "Message Sent");
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
} else {
//mgr.showConnectionErrBox();
}
}
public void stopConnection() {
try {
if(bSocket != null)
bSocket.close();
Log.e(TAG, "Connection closed");
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
public BluetoothDevice getCurrentDevice() {
return currentDevice;
}
public void setCurrentDevice(BluetoothDevice currentDevice) {
this.currentDevice = currentDevice;
}
public ArrayList<String> getMessage() {
return message;
}
public void setMessage(ArrayList<String> message) {
this.message = message;
}
}
Below is the affect portion
if(connected){
mgr.connectedDialog();
mgr.msgsent();
System.out.println("Calibration connected");
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytes;
String apple = "";
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
if ( bytes != -1){
while ((bytes==bufferSize)&&(buffer[bufferSize-1] != 0)){
apple = apple + "_" + new String(buffer, 0, bytes);
bytes = mmInStream.read(buffer);
}
apple = apple + new String(buffer, 0, bytes -1);
System.out.println("message " + apple);
//pass data to UI CalibrationActivity
System.out.println("message out " + apple);
Message msga = mhandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("key", apple);
msga.setData(bundle);
mhandler.sendMessage(msga);
}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
break;
}
}
}
Below is the code for my Calibration Activity
package com.android;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import com.android.SimpleGestureFilter.SimpleGestureListener;
import com.android.backend.data.Playlist;
import com.android.backend.data.PlaylistManager;
import com.android.backend.data.SwitchBar;
import com.android.backend.data.bluetooth.BluetoothManager;
import com.android.backend.data.bluetooth.Connection;
import com.android.ui.UIManager;
import com.android.ui.playlist.PlaylistEntryList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
//public class CalibrationActivity extends Activity{
public class CalibrationActivity extends Activity implements SimpleGestureListener{
String gotBread;
public void handleMessage(Message msg)
{ switch(msg.what){
case 2:
Bundle got = getIntent().getExtras();
gotBread = got.getString("key");
TextView aa = (TextView) this.findViewById(R.id.stringinput);
aa.setText(gotBread);
break;
}
}
private SimpleGestureFilter detector;
#Override
public boolean dispatchTouchEvent(MotionEvent me){
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onSwipe(int direction) {
// TODO Auto-generated method stub
//final MainActivity tt = this;
String str = "";
switch (direction) {
//case SimpleGestureFilter.SWIPE_RIGHT : str = "Swipe Right";
case SimpleGestureFilter.SWIPE_RIGHT : this.finish();
break;
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
break;
case SimpleGestureFilter.SWIPE_DOWN : str = "Swipe Down";
break;
case SimpleGestureFilter.SWIPE_UP : str = "Swipe Up";
break;
}
//Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
#Override
public void onDoubleTap() {
// TODO Auto-generated method stub
//Toast.makeText(this, "Double Tap", Toast.LENGTH_SHORT).show();
//Do Nothing for now future development
}
private PlaylistManager playlistMgr;
private PlaylistEntryList playlistView; // Data for listview, stores current
// playlist in memory
public String createdNameList; // Indicated the name of currently Name of
// playlist that is being created
public Dialog dialog_customizePL, dialog_createPL, dialog_customizePLms; // Dialog boxes for
// Playlist creation
public UIManager uiMgr = new UIManager();
public String CONNECTED_DEVICE_MAC;
public String dialogboxtext;
public Connection Conn;
int i = 0;
protected void onPause() {
super.onPause();
//BluetoothManager.getInstance().disconnectAll();
unregisterReceiver(mRvcau); //Sequence is important
System.exit(0); // Kill off all thread to prevent connectiong lost popup
// I use system because is a calibration so I want user not to leave the activity else cannot calibrate
}
protected void onResume() { //restart bluetooth is accidently off it
super.onResume();
BluetoothManager.getInstance().init();
BluetoothManager.getInstance().getBluetoothAdapter().enable();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED); // IntentFilter class is important to declare for below filter
registerReceiver(mRvcau,filter); // mRvcau is the location of logic, filter is message identify by android
filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED); // Future deveploment
registerReceiver(mRvcau,filter);
filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); // Future deveploment
registerReceiver(mRvcau,filter);
filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED); // Future deveploment
registerReceiver(mRvcau,filter);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.remotedevicecalibration);
detector = new SimpleGestureFilter(this,this); ////////////////// For Gesture
playlistMgr = PlaylistManager.getInstance();
initUI();
uiMgr.initPlayListUI(this);
}
int connect = 0; // Check connection
int disconnect = 0; // Check disconnection
int requestdisconnect = 0;
int connectstatuschanges = 0;
public BroadcastReceiver mRvcau = new BroadcastReceiver(){ // The new is instantiate the class **always read from the back
// The line from the back is creating an instantiate of this class
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//AutoActivity.this.finish();
connect = 1; // prevent activity from exiting
System.out.println("ACTION_ACL_CONNECTED " + connect);
}
else
{
connect = 0;
System.out.println("ACTION_ACL_CONNECTED " + connect);
}
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) { //future development
disconnect = 1;
System.out.println("ACTION_ACL_DISCONNECTED " + disconnect);
}
else
{
disconnect = 0;
System.out.println("ACTION_ACL_DISCONNECTED " + disconnect);
}
if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) { //future development
requestdisconnect = 1;
System.out.println("ACTION_ACL_DISCONNECT_REQUESTED " + requestdisconnect);
}
else
{
requestdisconnect = 0;
System.out.println("ACTION_ACL_DISCONNECT_REQUESTED " + requestdisconnect);
}
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { //future development
connectstatuschanges = 1;
System.out.println("ACTION_BOND_STATE_CHANGED " + connectstatuschanges);
}
else
{
connectstatuschanges = 0;
System.out.println("ACTION_BOND_STATE_CHANGED " + connectstatuschanges);
}
}
};
/**
* Init layout component. Define Listener for Buttons and Dataset for
* ListViews
*/
#SuppressLint("ParserError")
public void initUI() {
Button Orange = (Button) findViewById(R.id.CalibrationOrange); // new method on test using image
Orange.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
activiteSingleConnection(20);
}
});
Button Blue = (Button) findViewById(R.id.CalibrationBlue); // new method on test using image icon to on the switch
Blue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
activiteSingleConnection(21);
}
});
Button Green = (Button) findViewById(R.id.CalibrationGreen); // new method on test using image icon to on the switch
Green.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
activiteSingleConnection(22);
}
});
loadDataToMem();
}
public void activiteSingleConnection(int i) {
BluetoothManager btMgr = BluetoothManager.getInstance();
BluetoothDevice device = btMgr.getBluetoothAdapter().getRemoteDevice(
CONNECTED_DEVICE_MAC);
ArrayList<String> msg = new ArrayList<String>();
if(i == 20){
msg.add("N");
}
if(i == 21){
msg.add("J");
}
if(i == 22){
msg.add("I");
}
CharSequence fruit = null;
TextView aa = (TextView) this.findViewById(R.id.stringinput);
aa.setText(fruit);
btMgr.calibratesentMessage(uiMgr, device, msg);
}
public void loadDataToMem() {
try {
String str = "";
//StringBuffer buf = new StringBuffer();
FileInputStream input = this.openFileInput("bone.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(
input));
if (input != null) {
while ((str = reader.readLine()) != null) {
String[] buff = str.split(",");
TextView topView = (TextView) this
.findViewById(R.id.remotedevicecalibrationtextview1);
TextView bottomView = (TextView) this
.findViewById(R.id.remotedevicecalibrationtextView2);
topView.setText("Name : " + buff[0]);
bottomView.setText("Mac : " + buff[2]);
this.CONNECTED_DEVICE_MAC = buff[2];
Log.d("loadDataToMem", str);
}
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Below are my log cat error message
09-13 10:50:33.640: W/dalvikvm(2086): threadid=9: thread exiting with uncaught exception (group=0x40015560)
09-13 10:50:33.667: E/AndroidRuntime(2086): FATAL EXCEPTION: Thread-10
09-13 10:50:33.667: E/AndroidRuntime(2086): java.lang.NullPointerException
09-13 10:50:33.667: E/AndroidRuntime(2086): at com.android.backend.data.bluetooth.Connection.run(Connection.java:196)
Hope someone can advice me how to solve. Thank You.

Camera snapshot in J2ME Null Pointer Exception

I've spent long on this but no success yet. In my application to capture image and send to the server, I get NullPointerException below;
java.lang.NullPointerException: 0
at Files.CameraMIDlet.snap(CameraMIDlet.java:120)
at Files.CameraForm.commandAction(CameraForm.java:116)
at javax.microedition.lcdui.Display$ChameleonTunnel.callScreenListener(), bci=46
at com.sun.midp.chameleon.layers.SoftButtonLayer.processCommand(), bci=74
at com.sun.midp.chameleon.layers.SoftButtonLayer.soft2(), bci=173
at com.sun.midp.chameleon.layers.SoftButtonLayer.keyInput(), bci=78
at com.sun.midp.chameleon.CWindow.keyInput(), bci=38
at javax.microedition.lcdui.Display$DisplayEventConsumerImpl.handleKeyEvent(), bci=17
at com.sun.midp.lcdui.DisplayEventListener.process(), bci=277
at com.sun.midp.events.EventQueue.run(), bci=179
at java.lang.Thread.run(Thread.java:722)
The errors happen at byte[] image = videoControl.getSnapshot("encoding = jpeg"); in the CameraMIDlet and also at midlet.snap(); in the CameraForm, in the code below.
The code for CameraForm is here:
package Files;
import javax.microedition.media.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.control.*;
import java.io.IOException;
class CameraForm extends Form implements CommandListener {
private final CameraMIDlet midlet;
private final Command exitCommand;
private Command captureCommand = null;
private Command showImageCommand = null;
private Player player = null;
private static VideoControl videoControl = null;
private boolean active = false;
private StringItem messageItem;
public CameraForm(CameraMIDlet midlet) {
super("Camera");
this.midlet = midlet;
messageItem = new StringItem("Message", "start");
append(messageItem);
exitCommand = new Command("EXIT", Command.EXIT, 1);
addCommand(exitCommand);
setCommandListener(this);
try {
//creates a new player and set it to realize
player = Manager.createPlayer("capture://video");
player.realize();
//Grap the Video control and set it to the current display
videoControl = (VideoControl) (player.getControl("VideoControl"));
if (videoControl != null) {
append((Item) (videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE, null)));
captureCommand = new Command("CAPTURE", Command.SCREEN, 1);
addCommand(captureCommand);
messageItem.setText("OK");
} else {
messageItem.setText("No video control");
}
} catch (IOException ioe) {
messageItem.setText("IOException: " + ioe.getMessage());
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
} catch (SecurityException se) {
messageItem.setText("Security Exception: " + se.getMessage());
}
}
* the video should be visualized on the sreen
* therefore you have to start the player and set the videoControl visible
synchronized void start() {
if (!active) {
try {
if (player != null) {
player.start();
}
if (videoControl != null) {
videoControl.setVisible(true);
//midlet.snap();
}
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
} catch (SecurityException se) {
messageItem.setText("Security Exception: " + se.getMessage());
}
active = true;
}
}
* to stop the player. First the videoControl has to be set invisible
* than the player can be stopped
synchronized void stop() {
if (active) {
try {
if (videoControl != null) {
videoControl.setVisible(false);
}
if (player != null) {
player.stop();
}
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
}
active = false;
}
}
* on the captureCommand a picture is taken and transmited to the server
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
midlet.cameraFormExit();
} else {
if (c == captureCommand) {
midlet.snap();
}
}
}
}
The code for CameraMIDlet is below:
package Files;
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.microedition.media.control.*;
import java.io.IOException;
import javax.microedition.media.MediaException;
public class CameraMIDlet extends MIDlet {
private CameraForm cameraSave = null;
private DisplayImage displayImage = null;
CameraForm captureThread;
private static VideoControl videoControl;
private StringItem messageItem;
public CameraMIDlet() {
}
/*
* startApp()
* starts the MIDlet and generates cameraSave, displayImage, database
*
**/
public void startApp() {
Displayable current = Display.getDisplay(this).getCurrent();
if (current == null) {
//first call
cameraSave = new CameraForm(this);
displayImage = new DisplayImage(this);
Display.getDisplay(this).setCurrent(cameraSave);
cameraSave.start();
} else {
//returning from pauseApp
if (current == cameraSave) {
cameraSave.start();
}
Display.getDisplay(this).setCurrent(current);
}
}
public void pauseApp() {
if (Display.getDisplay(this).getCurrent() == cameraSave) {
cameraSave.stop();
}
}
public void destroyApp(boolean unconditional) {
if (Display.getDisplay(this).getCurrent() == cameraSave) {
cameraSave.stop();
}
}
private void exitRequested() {
destroyApp(false);
notifyDestroyed();
}
void cameraFormExit() {
exitRequested();
}
/**
* restart the camera again
*
*/
void displayCanvasBack() {
Display.getDisplay(this).setCurrent(cameraSave);
cameraSave.start();
}
/**
* the byte[] of the image should be transmitted to a server
*
**/
void buildHTTPConnection(byte[] byteImage) {
displayImage.setImage(byteImage);
Display.getDisplay(this).setCurrent(displayImage);
HttpConnection hc = null;
OutputStream out = null;
try {
//enode the image data by the Base64 algorithm
String stringImage = Base64.encode(byteImage);
// URL of the Sevlet
String url = new String(
"http://ip-adress:8080/C:/Users/HASENDE/Documents/NetBeansProjects/Mobile/pics");
// Obtain an HTTPConnection
hc = (HttpConnection) Connector.open(url);
// Modifying the headers of the request
hc.setRequestMethod(HttpConnection.POST);
// Obtain the output stream for the HttpConnection
out = hc.openOutputStream();
out.write(stringImage.getBytes());
} catch (IOException ioe) {
StringItem stringItem = new StringItem(null, ioe.toString());
} finally {
try {
if (out != null)
out.close();
if (hc != null)
hc.close();
} catch (IOException ioe) {
}
}
// ** end network
}
/**
* stop the camera, show the captured image and transmit the image to a server
**/
void transmitImage(byte[] image) {
cameraSave.stop();
Display.getDisplay(this).setCurrent(displayImage);
buildHTTPConnection(image);
}
public void snap(){
try {
byte[] image = videoControl.getSnapshot("encoding = jpeg");
transmitImage(image);
messageItem.setText("Ok");
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
}
}
}
By identifying the statement that throws NPE you get 99% close to finding the bug:
byte[] image = videoControl.getSnapshot("encoding = jpeg");
NPE in above statement means videoControl is null. Now if you look at it closer, you may notice that in CameraMIDlet, videoControl is initialized with null and never changes to anything else - that's why you are getting NPE. By the way, from CameraForm code it looks like you intended to use videoControl object that is defined there, didn't you.
Side note. CameraForm seems to be designed to used in multiple threads (there are synchronized modifiers) - if this is the case, you better make sure that videoControl is also obtained from it in a synchronized way. Also in that case, add volatile modifier in definition of active flag:
private volatile boolean active = false; // in CameraForm
For Capturing photo use canvas instead of Form,
Check follwing code for Photo Capture
public class ImageCaptureCanvas extends Canvas {
UrMidlet midlet;
VideoControl videoControl;
Player player;
SnapShotCanvas snap;
private Display display;
public ImageCaptureCanvas(UrMidlet midlet) throws MediaException {
this.midlet = midlet;
this.display = Display.getDisplay(midlet);
this.setFullScreenMode(true);
try {
player = Manager.createPlayer("capture://image");
player.realize();
videoControl = (VideoControl) player.getControl("VideoControl");
} catch (Exception e) {
dm(e.getClass().getName());
}
videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
try {
videoControl.setDisplayLocation(0,0);
videoControl.setDisplaySize(getWidth(), getHeight());
} catch (MediaException me) {
try {
videoControl.setDisplayFullScreen(true);
} catch (MediaException me2) {
}
}
dm("icc10");
videoControl.setVisible(true);
dm("icc11");
player.start();
this.display.setCurrent(this);
}
public void dm(String message) {
Form form = new Form("Error");
form.append(message);
display.setCurrent(form);
}
public void paint(Graphics g) {
}
protected void keyPressed(int keyCode) {
boolean prv=false;
int actn=getGameAction(keyCode);
switch (keyCode) {
case KEY_NUM5:
prv=true;
Thread t = new Thread() {
public void run() {
try {
byte[] raw = videoControl.getSnapshot(null);
Image image = Image.createImage(raw, 0, raw.length);
snap = new SnapShotCanvas(image);
display.setCurrent(snap);
} catch (Exception e) {
dm(e.getClass().getName() + " " + e.getMessage());
}
}
};
t.start();
break;
}
if(!prv){
switch (actn) {
case Canvas.FIRE:
Thread t1 = new Thread() {
public void run() {
try {
byte[] raw = videoControl.getSnapshot(null);
Image image = Image.createImage(raw, 0, raw.length);
snap = new SnapShotCanvas(image);
display.setCurrent(snap);
} catch (Exception e) {
dm(e.getClass().getName() + " " + e.getMessage());
}
}
};
t1.start();
break;
}
}
}
}
SnapShotCanvas Code here
class SnapShotCanvas extends Canvas {
private Image image;
public SnapShotCanvas(Image image) {
this.image = image;
setFullScreenMode(true);
}
public void paint(Graphics g) {
g.drawImage(image, getWidth() / 2, getHeight() / 2, Graphics.HCENTER | Graphics.VCENTER);
}
}

Getting error while calling library jar file in j2me

I have created a login page with webservice in j2me. But while running I am getting error. Can anyone please help? My code is:
public class Login extends MIDlet implements CommandListener {
//the main form
Form mainForm = null;
//the text-boxes for the input
TextField txtBoxA = null;
TextField txtBoxB = null;
//the result label
//the Exit command
Command cmdExit = null;
Command cmdAdd = null;
//the Display reference
Display display = null;
public Login() {
{
//construct the main form
mainForm = new Form("kSOAP Example");
//construct the controls
txtBoxA = new TextField("UserName:", null, 50, TextField.ANY);
txtBoxB = new TextField("Password:", null, 50, TextField.ANY);
// result = new StringItem("Result:", null);
//add controls to the form
mainForm.append(txtBoxA);
mainForm.append(txtBoxB);
// mainForm.append(result);
//construct commands
cmdExit = new Command("Exit", Command.EXIT, 1);
cmdAdd = new Command("Add", Command.SCREEN, 1);
//add commands
mainForm.addCommand(cmdAdd);
mainForm.addCommand(cmdExit);
}
}
public void startApp() {
if (display == null) {
display = Display.getDisplay(this);
}
//display the main form
display.setCurrent(mainForm);
//register the command listener
mainForm.setCommandListener(this);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == cmdExit) {
this.destroyApp(false);
this.notifyDestroyed();
} else if (c == cmdAdd) {
//callWebServiceMethod();
Library lib=new Library();
lib.init();
}
}
my jar file coding is library.jar
public class Library {
String METHOD_NAME = "ValidateLogin_M";
String SOAP_ACTION ="http://64.244.69.235:81/MobileApp/ValidateLogin_M";
String NAMESPACE ="http://64.244.69.235:81/MobileApp/";
String URL ="http://64.244.69.235:81/MobileApp/service1.asmx";
public Library() {
// TODO Auto-generated constructor stub
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Library lib=new Library();
lib.init();
}
public void init()
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
String user= "gsrtestnew#gmail.com";
String password= "123456";
request.addProperty("UserID",user);
request.addProperty("Password",password);
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransport j2meHttpTransport = new HttpTransport(URL);
try {
j2meHttpTransport.call(SOAP_ACTION, envelope);
SoapObject content = (SoapObject) envelope.bodyIn;
String sum = content.getProperty(0).toString();
// result.setText(sum);
System.out.println("##########"+sum);
JSONArray jsonobj = new JSONArray(sum.toString());
System.out.println("Json obj length:: " + jsonobj.length());
if(jsonobj.length() == 0)
{
}
for(int i=0; i<jsonobj.length(); i++)
{
JSONObject jobj = jsonobj.getJSONObject(i);
String CustID = jobj.getString("CustID");
System.out.println("CustID is :: "+CustID);
String Email = jobj.getString("Email");
System.out.println("Email is :: "+Email);
String FirstName = jobj.getString("FirstName");
System.out.println("FirstName is :: "+FirstName);
String LastName = jobj.getString("LastName");
System.out.println("LastName is :: "+LastName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have imported the jar file and called as Library class. But still I am getting error.
My error is
Starting emulator in execution mode
Installing suite from: http://127.0.0.1:49412/WebApplication.jad
TRACE: <at java.lang.Error: ClassFormatError: 56>, Exception caught in Display class
java.lang.Error: ClassFormatError: 56
at com.web.application.Login.commandAction(Login.java:95)
at javax.microedition.lcdui.Display$ChameleonTunnel.callScreenListener(), bci=46
at com.sun.midp.chameleon.layers.SoftButtonLayer.processCommand(), bci=74
at com.sun.midp.chameleon.layers.SoftButtonLayer.commandSelected(), bci=11
at com.sun.midp.chameleon.layers.MenuLayer.pointerInput(), bci=170
at com.sun.midp.chameleon.CWindow.pointerInput(), bci=76
at javax.microedition.lcdui.Display$DisplayEventConsumerImpl.handlePointerEvent(), bci=19
at com.sun.midp.lcdui.DisplayEventListener.process(), bci=296
at com.sun.midp.events.EventQueue.run(), bci=179
at java.lang.Thread.run(Thread.java:722)
This has already been answered - jvm cannot load a class due to difference in version - cf - ClassFormatError: 56 while using hessian in j2me
Recompile with
javac -target 1.4 ...

Resources