Java.lang.IllegalArgumentException

jwidd Messages postés 30 Date d'inscription mercredi 15 août 2007 Statut Membre Dernière intervention 17 septembre 2007 - 14 sept. 2007 à 14:51
jwidd Messages postés 30 Date d'inscription mercredi 15 août 2007 Statut Membre Dernière intervention 17 septembre 2007 - 17 sept. 2007 à 14:35
bonjour tout le monde,


j'ai trouvé une api d'envoi des sms d'un téléphone mobile vers un autre, mais je n'arrive pas à résoudre l'exception genérée à l'exécution qui est: java.lang.IllegalArgumentException.


je n'ai qu'une semaine devant moi, et je dois encore faire des modifs sur cet api pour pouvoir l'adapter à mon application après qu'elle marche bien sûr.


je travaille comme Ide avec netbeans 5.5 et sur le téléphone Nokia 6600.


voilà je vous expose le code ainsi que le texte de l'exception genérée, désolée si le code est long, mais je ne me rappelle pas du lien où je l'ai téléchargé.


code:
import java.io.*;
import javax.microedition.io.*;
import javax.wireless.messaging.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;


public class WMAExample extends MIDlet  implements CommandListener, MessageListener, ItemStateListener {
  /**
   *  This command exits the midlet.
   */
  private Command exitCommand;


  /**
   *  This command sends a message.
   */
  private Command sendCommand;


  /**
   *  This is the default display.
   */
  private Display display;


  /**
   *  This is the main form.
   */
  private Form form;


  /**
   * This is the choicegroup for which we decide whether to send
   * text or binary SMS messages.
   */
  private ChoiceGroup cg;


  /**
   *  This is the Textfield containing the destination phone number.
   */
  private TextField MessageAddressField;


  /**
   *  This is the Textfield containing the message body.
   */
  private TextField TextMessageBodyField;


  /**
  *  This is the String displayed when set to send a Binary Message.
  */


  private StringItem binaryFormText;


  /**
   *  This is the connection for sending messages.
   */
  private MessageConnection con;


  /**
   * Alert that is displayed when a message is sent.
   */
  private Alert alert;
  /**
   * Image to display in the Alert.
   */
  private Image thumbUp;


  private String MessageAddress;
  private String MessageServerPort;
  private String TextMessageBody;
  private String BinaryMessageBodyFile;
  private byte[] BinaryMessageBody;


  private void log (String logMessage) {
    System.out.println (logMessage);
    if (form != null) {
      form.append(logMessage);
    }
  }


  private void init () {
    // Initialize the address, where the message will be sent to
    MessageAddress  = getAppProperty (MIDletMessageAddressAttribute);
    if (MessageAddress == null) {
      MessageAddress = DefaultMIDletMessageAddress;
    }


    // Initialize the port number, where the MIDlet is listening on.
    MessageServerPort = getAppProperty (MIDletServerPortAttribute);
    if (MessageServerPort == null) {
      MessageServerPort = DefaultMIDletServerPort;
    }


    // Initialize the message to send
    // The message can be either a text message or a binary message
    TextMessageBody = getAppProperty (MIDletMessageTextBodyAttribute);
    BinaryMessageBodyFile = getAppProperty (MIDletBinaryMessageBodyFileAttribute);


    // If there is no message defined in the JAD file, send a text message    if ((TextMessageBody null) && (BinaryMessageBodyFile null)) {
      TextMessageBody = DefaultMIDletTextMessage;
    }


    // Read the binary file from the JAR
    if (BinaryMessageBodyFile != null) {


      log ("Reading resource file: " + BinaryMessageBodyFile);


      try
      {
        InputStream is = getClass().getResourceAsStream(BinaryMessageBodyFile);


        if (is == null ) {


          // The file name in the JAD file is mistyped or
          // the file is not included in the JAR
          log ("Resource file " + BinaryMessageBodyFile +
               " not found in the JAR file.");


          // We do not have a binary message
          BinaryMessageBodyFile = null;


        } else {
          DataInputStream dataStream = new DataInputStream(is);


          byte[] tempBuffer = new byte [500];
          byte[] data = new byte[1];
          int size = 0;


          int byteRead = dataStream.read(data, 0, data.length);
          while(byteRead >= 0)
          {
            tempBuffer[size++] = data[0];
            byteRead = dataStream.read(data, 0, data.length);
          }


          dataStream.close();


          if (size >0 )
          {
            BinaryMessageBody = new byte [size];
          }


          for (int i=0; i<size; i++)
          {
            BinaryMessageBody[i] = tempBuffer [i];
          }


        }
        } catch(Exception ex)
        {
          log ("Exception: " + ex.toString());
        }
    }
  }


  /** Constructor */
  public WMAExample() {
  }


  /** Main method */
  public void startApp() {


    // Initialize MIDlet parameters from the JAD file
    init ();


    // Listen for incomming messages
    listen (MessageServerPort);


    // Create the commands
    exitCommand = new Command("Exit", Command.EXIT, 2);
    sendCommand = new Command("Send", Command.OK, 1);


    // Create the UI
    form = new Form("WMAExample");


    //create the choicegroup & add it to the form.
    cg = new ChoiceGroup(null, ChoiceGroup.EXCLUSIVE);
    cg.append("Text",null);
    cg.append("Binary",null);
    form.append(cg);
    //register the itemStateChanged listener.
    form.setItemStateListener(this);


    // Create a field for the destination address
     MessageAddressField = new TextField("Address:", MessageAddress, 20, TextField.PHONENUMBER);
     form.append(MessageAddressField);


    // Create a field for the message body
    TextMessageBodyField = new TextField("Message:", TextMessageBody, 435, TextField.ANY);
    form.append(TextMessageBodyField);


    // Add commands to the form
    form.addCommand(exitCommand);
    form.addCommand(sendCommand);
    form.setCommandListener(this);


    // Set display
    display = Display.getDisplay(this);
    display.setCurrent(form);
  }


  /** Handle pausing the MIDlet */
  public void pauseApp() {
    try
    {
      con.close();
    }
    catch (Exception ex)
    {
    }
  }


  /** Handle destroying the MIDlet */
  public void destroyApp(boolean unconditional) {
    try
    {
      con.close();
    }
    catch (Exception ex)
    {
    }
  }


  public void notifyIncomingMessage(MessageConnection mscon) {
    if (con == mscon) {
      try {
        //TextMessage receivedMessage  = (TextMessage)mscon.receive();
        Message receivedMessage = mscon.receive();
        if (receivedMessage instanceof TextMessage) {
          messageReceivedHandler( (TextMessage) receivedMessage);
        }
        if (receivedMessage instanceof BinaryMessage) {
          messageReceivedHandler( (BinaryMessage) receivedMessage);
        }
      }
      catch (Exception ex) {
        log("Exception: " + ex.toString());
      }
    }
  }


  /**
   *  This method responds to the selected command.
   *
   *  @param  c  The command that triggered this event
   *  @param  d  The displayable upon which the command that triggered the
   *             event is placed
   */
  public void commandAction(Command c, Displayable d) {
    if (c == exitCommand) {
      destroyApp(false);
      notifyDestroyed();
    }


    // Send a text message    if (c sendCommand && cg.getSelectedIndex() 0) {
      if (TextMessageBody != null) {
        String destAddress = MessageAddressField.getString();
        String messageBody = TextMessageBodyField.getString();
        sendTextMessage(con, destAddress, messageBody);
      }
    }
    // Send a binary message    else if (c sendCommand && cg.getSelectedIndex() 1) {
      if (BinaryMessageBodyFile != null) {
        String destAddress = MessageAddressField.getString();
        sendBinaryMessage(con, destAddress, BinaryMessageBody);
      }
    }
  }
  /**
   * Detects when the ChoiceGroup value is changed and removes TextMessageField
   * from the form and adds binaryFormText in it's place, and visa versa.
   * */
  public void itemStateChanged(Item item) {
    int i;  //to use in the search loop
    //test whether the item that changed is the ChoiceGroup, else exit.
    if(item.equals(cg)){
      //if BinaryMessaging selected
      if (cg.getSelectedIndex() == 1) {
        //search for the TextMessageField Object and then remove it from the form.
        //add binaryFormText to the form in its place.
        for (i = 0; i < form.size(); ++i) {
          if(form.get(i) == TextMessageBodyField) {
            form.delete(i);
            binaryFormText = new StringItem("Message:","Ready to send /test.bin");
            form.append(binaryFormText);
            break;
          }
        }
      }
      //add the TextMessageBodyField & remove binaryFormText
      else if (cg.getSelectedIndex() == 0) {
        //first search for and remove the string "str".
        for(i=0; i<form.size(); ++i){
          if(form.get(i) == binaryFormText){
            form.delete(i);
            form.append(TextMessageBodyField);
          }
        }
      }//end else if
    }//end if(item.equals(cg))
  }


  public void sendBinaryMessage
  (MessageConnection connection, String destAddress, byte[] Body) {


    // Construct the message
    BinaryMessage Message = (BinaryMessage)connection.newMessage(
        MessageConnection.BINARY_MESSAGE,
        "sms://" + destAddress + ":7500");


    // Set the payload
    Message.setPayloadData(Body);


    try
    {
      // Send the message
      connection.send(Message);


      thumbUp = Image.createImage("/thumbsup.png");
      alert = new Alert("Message Sent",
                        "Binary Message sent: " + Body.length + " bytes.",
                        thumbUp, AlertType.CONFIRMATION);
      alert.setTimeout(3000);  //3 seconds
      display.setCurrent(alert,form);
      //log ("Binary Message sent: " + Body.length + " bytes.");
    }
    catch (IOException ioex)
    {
      log("IOException: " + ioex.toString());
    }
    catch(SecurityException syex)
    {
      log("SecurityException: " + syex.toString());
    }
    catch (Exception ex)
    {
      log("Exception: " + ex.toString());
    }
  }




  public void sendTextMessage
  (MessageConnection connection, String destAddress, String Body) {


    // Construct the message
    TextMessage Message = (TextMessage)connection.newMessage(
        MessageConnection.TEXT_MESSAGE,
        "sms://" + destAddress +":7500");


    // Set the payload
    Message.setPayloadText(Body);


    try
    {
      // Send the message
      connection.send(Message);
      thumbUp = Image.createImage("/thumbsup.png");
      alert = new Alert("Message Sent",
                        "Text Message sent: " + Body,
                        thumbUp, AlertType.CONFIRMATION);
      alert.setTimeout(3000); //3 seconds
      display.setCurrent(alert, form);


     //log ("Text Message sent: " + Body);
    }
    catch (IOException ioex)
    {
      log("IOException: " + ioex.toString());
    }
    catch(SecurityException syex)
    {
      log("SecurityException: " + syex.toString());
    }
    catch (Exception ex)
    {
      log("Exception: " + ex.toString());
    }
  }


  public void messageReceivedHandler (TextMessage receivedMessage) {
    String senderAddress = receivedMessage.getAddress();
    String receivedMessageBody = receivedMessage.getPayloadText();


    log ("Text Message received: " + receivedMessageBody);
  }


  public void messageReceivedHandler (BinaryMessage receivedMessage) {
    String senderAddress = receivedMessage.getAddress();
    byte[] receivedMessageBody = receivedMessage.getPayloadData();


    log ("Binary Message received: " + receivedMessageBody.length + " bytes.");
  }


  public void listen (String MessageServerPort) {
    try
    {
      con = (MessageConnection) Connector.open(
          "sms://:" + MessageServerPort);


      con.setMessageListener(this);
    }
    catch(Exception ex)
    {
      log("Exception during listen: " + ex.toString());
    }
  }


  /* Default values, if there is nothing specified in the JAD file */
  private static final String DefaultMIDletMessageAddress = "3300001:7500";


  private static final String DefaultMIDletServerPort = "7500";


  private static final String DefaultMIDletTextMessage = "Test message";


 /* Constants */
  private static final String MIDletMessageAddressAttribute =
      new String ("Message-Address");


  private static final String MIDletServerPortAttribute =
      new String ("ServerPort");


  private static final String MIDletMessageTextBodyAttribute =
      new String ("Message-Text-Body");


  private static final String MIDletBinaryMessageBodyFileAttribute =
      new String ("Binary-Message-Body-File");
}




et l'exception est :


startApp threw an Exception
java.lang.IllegalArgumentException
java.lang.IllegalArgumentException
        at javax.microedition.lcdui.TextField.setChars(TextField.java:760)
        at javax.microedition.lcdui.TextField.setString(TextField.java:666)
        at javax.microedition.lcdui.TextField.(TextField.java:630)
        at WMAExample.startApp(WMAExample.java:189)
        at javax.microedition.midlet.MIDletProxy.startApp(MIDletProxy.java:43)
        at com.sun.midp.midlet.Scheduler.schedule(Scheduler.java:374)
        at com.sun.midp.main.Main.runLocalClass(Main.java:466)
        at com.sun.midp.main.Main.main(Main.java:120)
 

4 réponses

Twinuts Messages postés 5375 Date d'inscription dimanche 4 mai 2003 Statut Modérateur Dernière intervention 14 juin 2023 111
15 sept. 2007 à 12:43
Salut,
elle est où la ligne 189 ??? la flème de compté

------------------------------------
"On n'est pas au resto : ici on ne fait pas dans les plats tout cuits ..."

OoWORAoO
0
jwidd Messages postés 30 Date d'inscription mercredi 15 août 2007 Statut Membre Dernière intervention 17 septembre 2007
15 sept. 2007 à 15:34
désolée c'est cella là :
MessageAddressField = new TextField("Address:", MessageAddress, 20, TextField.PHONENUMBER);

voilà la méthode startApp() qui contient la ligne qui a généré l'excezption, la ligne est en rouge.

/** Main method */
  public void startApp() {



    // Initialize MIDlet parameters from the JAD file
    init ();



    // Listen for incomming messages
    listen (MessageServerPort);



    // Create the commands
    exitCommand = new Command("Exit", Command.EXIT, 2);
    sendCommand = new Command("Send", Command.OK, 1);



    // Create the UI
    form = new Form("WMAExample");



    //create the choicegroup & add it to the form.
    cg = new ChoiceGroup(null, ChoiceGroup.EXCLUSIVE);
    cg.append("Text",null);
    cg.append("Binary",null);
    form.append(cg);
    //register the itemStateChanged listener.
    form.setItemStateListener(this);



    // Create a field for the destination address
    


MessageAddressField = new TextField("Address:", MessageAddress, 20, TextField.PHONENUMBER);
     form.append(MessageAddressField);





    // Create a field for the message body
    TextMessageBodyField = new TextField("Message:", TextMessageBody, 435, TextField.ANY);
    form.append(TextMessageBodyField);



    // Add commands to the form
    form.addCommand(exitCommand);
    form.addCommand(sendCommand);
    form.setCommandListener(this);



    // Set display
    display = Display.getDisplay(this);
    display.setCurrent(form);
  }
0
jwidd Messages postés 30 Date d'inscription mercredi 15 août 2007 Statut Membre Dernière intervention 17 septembre 2007
17 sept. 2007 à 13:28
désolée je sais que je m'accable sur vous mais c'est parce que vous êtes le(la) seul(e) à me répondre sur ce forum.
je rencontre beaucoup de problèmes dans le développement de mon application, et je bosse dessus en parallèle, ce qui fait je pose beaucoup de questions indépendantes.
voilà, j'ai un autre problème :

mon application, comme je vous ai déjà dit, consiste en l'envoi des codes barres lus par un scanner bluetooth au téléphone Nokia 6600 via bluetooth.
le problème c'est que le code barre qui apparait sur le téléphone n'est enregistré nulle part.je dois pouvoir le récupérer pour l'afficher ensuite via bluetooth sur l'écran du pc et l'enregistrer par la suite dans une petite base de données.


voici la méthode qui affiche le code barre dans un mtextbox.


public void barcodeReceived(String barcode)
 {
  // Show the text field   
  if(mDisplay.getCurrent() == mList)
   mDisplay.setCurrent(mTextBox);


   mTextBox.setString(barcode);
                                
 }
il y a celle-ci aussi:


 /** This function is called when raw data has been received
  */
 public void rawDataReceived(byte[] data)
 {
        String symbols = "0123456789ABCDEF";
        StringBuffer s = new StringBuffer(3*data.length);
        int len = data[0]*0x7F+data[1];
       
        for(int i = 0; i < len; i++) {
            s.append(symbols.charAt(data[2+i] / 16));
            s.append(symbols.charAt(data[2+i] % 16));
            s.append(',');
        }
   // Show the text field   
  if(mDisplay.getCurrent() == mList)
   mDisplay.setCurrent(mTextBox);


   mTextBox.setString(s.toString());
 }
}


aidez moi, je suis coincée.
merci beaucoup.
0
jwidd Messages postés 30 Date d'inscription mercredi 15 août 2007 Statut Membre Dernière intervention 17 septembre 2007
17 sept. 2007 à 14:35
désolée encore une fois, comme c'est ma dernière semaine en stage et que je n'ai pas pu résoudre le problème d'envoi des sms que je vous ai envoyé, on me demande à chaque fois une nouvelle chose à faire.
maintenant j'ai besoin de savor un truc qui est simple mais je n'ai pas la tête de chercher dans les sujets du forum si tu veux bien sûr me renseigner.

je veux savoir comment on crée un fichier texte en java et comment on écrit dedans et comment on l'enregistre, je t'informe que mon application est mobile, c'est à dire que le fichier doit être créé et enregistré sur le téléphone (Nokia 6600).
votre aide me sera très précieuse. 
0
Rejoignez-nous