Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Highlighted
New Developer
Posts: 23
Registered: ‎04-01-2010
My Device: 9700
My Carrier: student

sms demo error

i building my first application that have sending sms. i try to use sms demo but unfortunatelly when i'm going to send sms i got java io exeption, is there any way to solve thsi error ???

 

my code is the following: ( same as the smsdemo in sdk 5.0)



package com.rim.samples.device.smsdemo;

import net.rim.device.api.io.*;
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;

import javax.microedition.io.*;
import java.util.*;
import java.io.*;
import javax.wireless.messaging.*;

 
public class SmsDemo extends UiApplication  
{  
    private static final int MAX_PHONE_NUMBER_LENGTH = 32;    
    
    private static String NON_ZERO_PORT_NUMBER = "3590";    
        
    private EditField _sendText;
    private EditField _address;
    private EditField _status;
    private ListeningThread _listener;
    private SendThread _sender;            
    private Connection _conn;
    private String _port = "0";   
    
    // Cached for improved performance
    private StringBuffer _statusMsgs = new StringBuffer();     


    /**
     * Determines whether the currently active WAF is CDMA
     * @return True if currently active WAF is CDMA, otherwise false
     */
    private static boolean isCDMA()
    {
        return (RadioInfo.getActiveWAFs() & RadioInfo.WAF_CDMA) == RadioInfo.WAF_CDMA;
    }
    
    /**
     * Sends an SMS message
     */
    private MenuItem _sendMenuItem = new MenuItem("Send", 100, 10)
    {        
        public void run()
        {       
            String text = _sendText.getText();
            String addr = _address.getText();      
            
            if (addr.length() == 0)
            {
                Dialog.alert("Destination field cannot be blank");
                _address.setFocus();
            }
            else if(text.length() == 0)
            {
                Dialog.alert("Message field cannot be blank");
                _sendText.setFocus();                
            }
            else
            {
                _sender.send(addr, text, _port);                
            }
        }
    };     
    
    
    /**
     * Entry point for application
     * @param args Command line arguments (not used)
     */
    public static void main(String[] args)
    {
        // Create a new instance of the application and make the currently
        // running thread the application's event dispatch thread.
        SmsDemo sms  = new SmsDemo();
        sms.enterEventDispatcher();
    }
    
        
    /**
     * This thread listens for any incoming messages
     */
    private class ListeningThread extends Thread
    {
        private boolean _stop;
        
        /**
         * Stops this thread from listening for messages
         */
        private synchronized void stop()
        {
            _stop = true;
            
            try
            {                
                if( _conn != null )
                {                    
                    _conn.close();
                }
            }
            catch (IOException ioe)
            {                
            }
        }   

        /**
         * Listens for incoming messages until stop() is called
         * @see #stop()
         * @see java.lang.Runnable#run()
         */
        public void run()
        {
            try
            {               
                _conn =  Connector.open("sms://:" + _port);
                for(;Smiley Wink
                {
                    if ( _stop )
                    {
                        return;
                    }
                    MessageConnection msgConn = (MessageConnection)_conn;
                    Message m = msgConn.receive();

                    receivedSmsMessage(m);                  
                }
            }
            catch (IOException ioe)
            {                             
                updateStatus(ioe.toString());
            }
        }
    }
    

    /**
     * A simple abstraction of an SMS message, used by the SendThread class
     */
    private static final class SmsMessage
    {
        private String _address;  
        private String _port;      
        private String _msg;    
        
        
        /**
         * Creates a SMS message
         * @param address The address of the recipient of the SMS message
         * @param msg The message to send
         */
        public SmsMessage(String address, String msg, String port)
        {
            _address = address;   
            _port = port;         
            _msg = msg;
        }
        
        
        /**
         * Returns a Message object representing this SMS message
         * @param mc The MessageConnection source with which to create the Message from
         * @return The Message object representing the SMS message
         */
        public Message toMessage(MessageConnection mc)
        {      
            // If the user chose to have messages routed to the inbox (port = 0),
            // we need to specify an address without a port number.
            String addressString = "//" + _address + ( _port.equals(NON_ZERO_PORT_NUMBER) ?  ":" + _port : "" );
            
            TextMessage m = (TextMessage) mc.newMessage(MessageConnection.TEXT_MESSAGE , addressString);
            m.setPayloadText(_msg);
            
            return m;
        }
        
        
        /**
         * Returns a Datagram object representing this SMS message
         * @param datagramConnectionBase The DatagramConnectionBase object with which to create the Datagram from
         * @return The Datagram object representing the SMS message
         */
        public Datagram toDatagram(DatagramConnectionBase datagramConnectionBase) throws IOException
        {       
            DatagramBase datagram = null;                            
            byte[] data = _msg.getBytes("ISO-8859-1");
            datagram = (DatagramBase) datagramConnectionBase.newDatagram();
            SmsAddress smsAddress = new SmsAddress("//" + _address);
            SMSPacketHeader smsPacketHeader = smsAddress.getHeader();
            smsPacketHeader.setMessageCoding(SMSPacketHeader.MESSAGE_CODING_ISO8859_1);
            datagram.setAddressBase(smsAddress);            
            datagram.write(data, 0, data.length);         
            
            return datagram;
        }
    }

    
    /**
     * A thread to manage outbound transactions
     */
    private class SendThread extends Thread
    {
        private boolean _stopped = false;        

        // Create a vector of SmsMessage objects with an initial capacity of 5.
        // For this implementation it is unlikely that more than 5 msgs will be
        // queued at any one time.
        private Vector _msgs = new Vector(5);       

        
        /**
         * Queues message send requests to send later
         * @param address The address to send the message to
         * @param msg The message to send
         */
        public void send(String address, String msg, String port)
        {
            SmsMessage message = new SmsMessage(address, msg, port);
            synchronized (this._msgs)
            {
                if (! this._stopped)
                {
                    this._msgs.addElement(message);
                    this._msgs.notifyAll();
                }
            }
        }


        /**
         * Stops this thread from sending any more messages
         */
        public void stop()
        {
            synchronized (this._msgs)
            {
                this._stopped = true;
                this._msgs.notifyAll();
                this._msgs.removeAllElements();       

                try
                {
                    if ( _conn != null )
                    {
                        _conn.close();
                    }
                }
                catch (IOException ioe )
                {                
                }             
            }
        }
        

        /**
         * Sends any queued messages until stop() is called
         * @see #stop()
         * @see java.lang.Runnable#run()
         */
        public void run()
        {
            while (true)
            {
                final SmsMessage smsMessage;
                synchronized (this._msgs)
                {
                    if (this._stopped)
                    {
                        return;
                    }
                    else if (this._msgs.isEmpty())
                    {
                        try
                        {
                            this._msgs.wait();
                        }
                        catch (InterruptedException ie)
                        {
                            return;
                        }
                    }                    

                    if (this._stopped)
                    {
                        return;
                    }
                    else
                    {
                        smsMessage = (SmsMessage) this._msgs.elementAt(0);
                        this._msgs.removeElementAt(0);
                    }
                }
                try
                {
                    if(isCDMA())
                    {
                        DatagramConnectionBase dcb = (DatagramConnectionBase)_conn;
                        dcb.send(smsMessage.toDatagram(dcb));
                    }
                    else
                    {
                        MessageConnection mc = (MessageConnection)_conn;
                        mc.send(smsMessage.toMessage(mc));
                    }
                }
                catch (IOException ioe)
                {                    
                    updateStatus(ioe.toString());
                }
            }
        }
    }
    
      
    /**
     * This screen acts as the main screen to allow the user to send and
     * receive messages.
     */
    private class SmsDemoScreen extends MainScreen
    {      
        /**
         * Default constructor
         */
        private SmsDemoScreen()
        {
            setTitle("SMS Demo");
            
            _address = new EditField("Destination:", "", MAX_PHONE_NUMBER_LENGTH, EditField.FILTER_PHONE);
            add(_address);
            _sendText = new EditField("Message:", "");
            add(_sendText);
            add(new SeparatorField());
    
            _status = new EditField();
            add(_status);
            
            addMenuItem(_sendMenuItem);
        }
        
        
        /**
         * Prevent the save dialog from being displayed
         *
         * @see net.rim.device.api.ui.container.MainScreen#onSavePrompt()
         */
        public boolean onSavePrompt()
        {
            return true;
        }    

        
        /**
         * Closes the application
         *
         * @see net.rim.device.api.ui.Screen#close()
         */
        public void close()
        {           
            _listener.stop();                               
            _sender.stop();           
            
            super.close();
        }
    }
    

    /**
     * Default constructor
     */
    public SmsDemo()
    {      
        invokeLater(new Runnable()
        {
            
            public void run()
            {
                if(!isCDMA())
                {
                    int result = Dialog.ask(Dialog.D_YES_NO, "Send messages to inbox?", Dialog.YES);
                    if (!(result == Dialog.YES))
                    {
                        // If user chooses to not have message routed to inbox,
                        // we need to specify an arbitrary non-zero port number.
                        _port = NON_ZERO_PORT_NUMBER;
                    }          
                }
                
                _listener = new ListeningThread();
                _listener.start();                  
        
                _sender = new SendThread();
                _sender.start();     
            }
        });          
        
        SmsDemoScreen screen = new SmsDemoScreen();
        pushScreen(screen);
    }
    

    /**
     * Update the GUI with the data just received
     * @param msg The new status message to display on screen
     */
    private void updateStatus(final String msg)
    {
         System.err.println(msg);
         
        invokeLater(new Runnable()
        {
            /**
             * Updates the GUI's status message
             * @see java.lang.Runnable#run()
             */
            public void run()
            {
                
                // Clear the string buffer
                _statusMsgs.delete(0, _statusMsgs.length());
                
                _statusMsgs.append(_status.getText());
                _statusMsgs.append('\n');
                _statusMsgs.append(msg);
                _status.setText(_statusMsgs.toString());
            }
        });

    }
    

    /**
     * Some simple formatting for a received SMS message
     * @param m The message just received
     */
    private void receivedSmsMessage(Message m)
    {
        String address = m.getAddress();
        String msg = null;
        
        if ( m instanceof TextMessage )
        {
            TextMessage tm = (TextMessage) m;
            msg = tm.getPayloadText();
        }
        
        StringBuffer sb = new StringBuffer();
        sb.append("Received:");
        sb.append('\n');
        sb.append("Destination:");
        sb.append(address);
        sb.append('\n');
        sb.append("Data:");
        sb.append(msg);
        sb.append('\n');

        updateStatus(sb.toString());
    }   
}

 

regards

Developer
Posts: 4,764
Registered: ‎07-21-2008
My Device: Not Specified

Re: sms demo error

Can you tell us what line of code throws the exception?

 

New Member
Posts: 1
Registered: ‎07-25-2011
My Device: 9300
My Carrier: XL

Re: sms demo error

Hey, I encounter the same issue here...

 

I just installed SmsDemo application on my phone (Blackberry 9300) but when i run the application and send simple message, it throws java.io.IOException

 

Destination: 9011

Message: Test

 

i set all the application permission to "allow" but nothing happens

 

please help

Developer
Posts: 29
Registered: ‎03-10-2011
My Device: Not Specified

Re: sms demo error

The error may be because of port number.. try giving it as "0" ..