i got this warning from my j2me code that try to connecto to database using php and httpconnection,,

Warning: To avoid potential deadlock, operations that may block, such as
networking, should be performed in a different thread than the
commandAction() handler.

pls help..

Dani AI

Generated

Short summary: the emulator warning is telling that any operation that can block (network I/O, file access, etc.) should not run inside the commandAction event handler; moving the HTTP work to a separate thread (as recommended and hinted) is the correct move and prevents the MIDP event loop from freezing or deadlocking. The symptom in many J2ME/WTK threads is exactly that the UI prompt or event handling stops while the phone/emulator waits for a network permission or response. (stackoverflow.com)

Most likely cause of the login check always "succeeding" is server- or protocol-level mismatch rather than the thread switch. Common server bugs: using mysql_fetch_array() incorrectly and then testing the result as a numeric count, or emitting extra text/whitespace/BOM before/after the intended token. On the server use mysql_num_rows($result) (or better: mysqli/PDO APIs) to test whether the SELECT returned rows; also make the script echo a single predictable token (plain text or JSON) and avoid any extra HTML, notices or trailing whitespace (omit the closing ?> in pure-PHP files). Those two fixes eliminate many client-side parsing surprises. (php.net)

On the Java side, treat the network thread as a worker and marshal any UI changes back to the event stream. Trim and compare the server string with equals(...) (not ==) and guard against null. Example pattern (adapt to the MIDlet instance and error handling already used):

final String resp = new String(data /* bytes from server */).trim();
Display.getDisplay(myMidlet).callSerially(new Runnable() {
  public void run() {
    if ("valid".equals(resp)) {
      display.setCurrent(nextForm); // success
    } else {
      display.setCurrent(new Alert("Login failed", resp, null, AlertType.ERROR));
    }
  }
});

Use callSerially or setCurrent from the worker only for short UI work; long UI tasks must still be avoided. (docs.oracle.com)

Quick checklist: reproduce the POST with curl/Postman to see the raw response; log the raw bytes/length on the phone before parsing; make the PHP return a tiny fixed token (e.g. OK/ERR); trim on the client and compare with equals; and migrate away from deprecated mysql_* to mysqli/PDO with prepared statements and hashed passwords for real deployments.

Recommended Answers

All 5 Replies

It's suggesting that you use threading to avoid your application from hanging while a process is waiting for resources. For example if you have a mobile IM application for a mobile if you don't use threading and one device trys to send a message but has to wait for resources before it can successfully send the message, no other devices can send a message untill that first device finishes sending it's message. However with threading each device can create it's own session and send the symotaniously.

Have a look at the 'How do i' link on THIS LINK, the subject of the application might not be relevant to your app but it may explain dead lock a bit better.

Hope this helps.

you posted generic link

post your code or have look at Beginning J2ME: From Novice to Professional - chapter 10

Yeah sorry there is a link towards the bottom of the link i posted which is about deadlock in mobile development but i cannot access due to banns in work for some reason

I treid too, but there is issue with msdn website as when link clicked page start to load and then suddenly redirect to different section.
Anyway, the above mention book chapter is what all what one needs to do.

i try to use thread in my code,, and it was successfull..

so i tried this code

public void commandAction(Command c, Item item) {
        // TODO Auto-generated method stub

        if(item == login){
            new Thread (this).start();
        }


public void run() {

        String hasil = null;
        String userName = username.getString();
        String passWord = password.getString();


        try {
            hasil = new String(connect.load(userName,passWord));
            Alert alarm = new Alert("LOGIN");
            alarm.setTimeout(Alert.FOREVER);
            alarm.setString(hasil);
            display.setCurrent(alarm);
        } catch (IOException ex) {
            Alert alarm = new Alert("LOGIN");
            alarm.setTimeout(Alert.FOREVER);
            alarm.setString(hasil);
            display.setCurrent(alarm);
        }

    }

it was successfull,,but then, after i login,,i want it to redirect into other class,, whenever i add "if else" after

hasil = new String(connect.load(userName,passWord));

they redirect but didnt detect wrong or not,, even i put wrong id and pw,, they still running to my other class which they shouldnt go,,

this is my ConnectServer code..

    private String url;
    private Form form;

    public ConnectServer(String url){
        this.url = url;
    }

    public byte[] load(String user, String pass) throws IOException{

        byte[] byteBuffer = null;

        HttpConnection hc = (HttpConnection) Connector.open(this.url);
        try {
            hc.setRequestMethod(HttpConnection.POST);
            hc.setRequestProperty("User-Agent",
                    "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
            hc.setRequestProperty("Accept_Language", "en-US");
            //Content-Type is must to pass parameters in POST Request
            hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            OutputStream os = hc.openOutputStream();
            String userName = "username=" + user;
            String passWord = "&password=" + pass;
            os.write(userName.getBytes());
            os.write(passWord.getBytes());
            if (hc.getResponseCode() == HttpConnection.HTTP_OK) {
                InputStream is = hc.openInputStream();

                try {
                    int len = (int) hc.getLength();
                    if (len > 0) {
                        byteBuffer = new byte[len];
                        DataInputStream dis = new DataInputStream(is);
                        dis.readFully(byteBuffer);
                    } else {
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[512];
                        int count;
                        while ((count = is.read(buffer)) >= 0) {
                            bos.write(buffer, 0, count);
                        }
                        byteBuffer = bos.toByteArray();
                    }
                } finally {
                    is.close();
                }
            }

        } finally {
            hc.close();
        }

        return byteBuffer;
    }

and this is my php code

<?php
 $user = "root";
 $pass = "1234";
 $host = "localhost";
 $db = "lms";

 $conn = mysql_connect($host,$user,$pass);
 mysql_select_db($db);

 if(!$conn){echo"Gagal Koneksi ke Database";}

$flag = false;

if($_POST['username'] != "" and $_POST['password'] != "")
{
 $username = $_POST['username'];
 $password = $_POST['password'];
 $flag = true;
}
else
{
 echo"username dan password harus diisi";
}

if($flag == true)
{
 $sql = "SELECT * FROM employee WHERE emp_other_id = '".$username."' AND emp_password = '".$password."'";
 $hasil = mysql_query($sql);
 $jmlacc = mysql_fetch_array($hasil);

 if($jmlacc > 0)
 {
 echo"valid";
 }else{
 echo"invalid";
 }
}
?>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.