HttpConnection Thread

Hello

I'm developing an application that connects to the Web service and receives the xml.

I use a HttpConnection class as follows

ConnectionClass extends Thread {}

Run() {}

Open a connection

get the answer

closes the connection

}

}

Then whenever I need to create a connection, I create an instance of this class and start the thread.

Application has a few flaws. Is there a better way to do it? Please suggest

Note to the qcfer35: this looks like very bad advice for me. What you do here is place an executable in the thread of events. Since the runnable will perform a blocking IO, this will almost certainly cause an application inadmissible that ends with the operating system.

Tags: BlackBerry Developers

Similar Questions

  • setStatus the right way.

    Hello

    I'm trying to understand how to properly use setStatus.

    My application works as follows.

    App.EnterEventDispatcher

    Push the new AppScreen

    AppScreen built the new screen to display

    Call httpconnection threads with m:System.NET.HttpListener.start and then displays the screen while the threads run in the background.

    I want to be able to set a status when they start and then when they finally remove the status field.

    Should I move my screen on the thread to pass object return status here or is there a better way to do.

    Thank you!

    I think you will find that this thread has a discussion around the same issues you are dealing with.  Not immeidaltey, it can then appear, but please read carefully.

    http://supportforums.BlackBerry.com/Rim/Board/message?board.ID=java_dev&message.ID=34095

  • When close HttpConnection?

    Hi guys.

    My application is using HttpConnection.

    HttpConnection variable is set by local authorities. And the application receives the data in the thread.

    You can see using my code to the following:

    private class HttpConnThread implements Runnable {   Thread thread;
    
       public void run() {      try {     HttpConnection httpConnection = null;     httpConnection = (HttpConnection)Connector.open("http://www.domain.com");   httpConnection.setRequestMethod(HttpConnection.GET);          int resp = httpConnection.getResponseCode();          if(resp == HttpConnection.HTTP_OK) {              InputStream hInput = httpConnection.openInputStream();        InputStreamReader isr = new InputStreamReader(hInput);              //.............              //........ Do somthing              //.............              hInput.close();              isr.close();              httpConnection.close();          }      } catch(Exception e) {
    
          }   }
    
       public void start() {      thread = new Thread(this);      thread.start();   }
    
       public void stop() {      thread.interrupt();   }}
    

    So, my question:

    1. What is the best way to declare my HttpConnection? local or global?

    2. When would end HttpConnection (httpConnection.close ())?

    I think that the application should call httpConnection.close () when the application exits.

    I don't know that these issue (close(), local or global), so I'm confirming their.

    Thank you guys.

    The best thing I would say is to close all open connections the finally block of the test socket {}... Also declare the variable HttpConnection, before the try block...

    Thank you

  • Updade UI thread

    Hello

    I want to show a list of message on a scree. I have to get a web service messages, showing a popUpScreen with a message waiting, while the service is invocated.

    To do that I have created a RespuestaServicio interface and three classes, MyScreen where I want to display messages, it implements RespuestaServicio methods that are called after the Web service response is obtained, PleaseWaitPopupScreen extends from PopupScreen, which has a method that receives a thread to run while the popupscreen is showed and close itself when the thread end and finally

    LlamadaWSThread is passed to the PleaseWaitPopupScreen call and that the webservice to get the list of messages.

    It's code summarized:

    public class MyScreen extends MainScreen implements RespuestaServicio{
    
        private VerticalFieldManager listaMensajes;
    
        public MyScreen() {
            super(Manager.NO_VERTICAL_SCROLL);
            HorizonlatFieldManager fondo = new HorizonlatFieldManager();
            listaMensajes = new VerticalFieldManager();
            vertical.add(listaMensajes);
            fondo.add(vertical);
            this.add(fondo);
            buscarMensajes();
        }
    
        public void buscarMensajes(){
        // Here I get some parameters like url an xml to pass to LlamadaWSThread constructor
           LlamadaWSThread serviceCaller = new LlamadaWSThread(url, this, xml);
                  PleaseWaitPopupScreen.showScreenAndWait(serviceCaller);
        }
    
        private void llenarLista(String[] campos){
            LabelField campo;
            for(int i = 0; i < campos.length; i++){
                campo = new LabelField(campos[i]);
                campo.setMargin(0, 10, 0, 10);
                listaMensajes.add(campo);
            }
        }
    
        public void requestFailed(final String message) {
           UiApplication.getUiApplication().invokeLater(new Runnable() {
                     public void run() {
                    Dialog.alert("requestFailed: "+message);
                     }
                  });
        }
    
        public void requestSucceeded(Document result) {
            String[] mensajes;
            // Here I proccess result to get mesajes...;
            llenarLista(campos);
        }
    }
    
    public class PleaseWaitPopupScreen extends PopupScreen {
    
        private static LabelField _ourLabelField = null;
    
        private PleaseWaitPopupScreen() {
            super(new VerticalFieldManager());
            ourLabelField = new LabelField("Please wait");
            this.add(urLabelField);
        }
    
        public static void showScreenAndWait(final Runnable runThis) {
            final PleaseWaitPopupScreen thisScreen = new PleaseWaitPopupScreen(text);
            Thread threadToRun = new Thread() {
                public void run() {
    
                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {
                            UiApplication.getUiApplication().pushScreen(thisScreen);
                        }
                    });
    
                    try {
                        runThis.run();
                    } catch (Exception t) {
    
                    }
    
                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {
                            if(thisScreen != null){
                                try {
                   UiApplication.getUiApplication().popScreen(thisScreen);
                } catch (Exception e) {
                   Dialog.alert(e.getMessage());
                      }
                            }
                        }
                    });
                }
            };
            threadToRun.start();
        }
    }
    
    public class LlamadaWSThread extends Thread {
        private RespuestaServicio pantalla;
        private ConstructorXml xml;
        private String url;
    
        public LlamadaWSThread(String url, RespuestaServicio pantalla, ConstructorXml xml) {
            super();
            this.url = url;
            this.pantalla = pantalla;
            this.xml = xml;
        }
    
        public  void    run()
        {
            HttpConnection  conn = null;
            OutputStream    oStream = null;
            try
            {
                conn    =   (HttpConnection)Connector.open( url );
                conn.setRequestMethod( HttpConnection.POST );
                oStream =   conn.openOutputStream();
                oStream.write( xml.getXml().getBytes() );
                oStream.flush();
    
                      InputStream is = conn.openInputStream();
                byte [] response = IOUtilities.streamToBytes(is);
                is.close();
                ByteArrayOutputStream   baos  =  new ByteArrayOutputStream();
                baos.write( response );
                DocumentBuilderFactory  dbf =   DocumentBuilderFactory.newInstance();
                DocumentBuilder db  =   dbf.newDocumentBuilder();
                Document    doc =   db.parse( new ByteArrayInputStream( baos.toByteArray() ) );
                pantalla.requestSucceeded(doc);
            }
            catch (Exception except)
            {
                pantalla.requestFailed(except.toString());
            }
        }   
    
    }
    

    My problem is that I'm getting this exception:

    IllegalStateExeption: UI engine accesed without hoding the lock of the event

    When you call llenarLista (...)  of requestSucceeded (...) who is called to LlamadaWSThread

    Please reread what I proposed. You missed a part on the displacement of campo in the body of the loop for?

    What you see, it's quite normal - plan you a change in the user interface that will update the display with the contents of an object, once you're done. Then you quickly change the contents of this object before all your regular screen updates has a chance to be executed. No wonder that all of these updates are only the last value of this object.

    Compare your loop for:

    for (int i = 0; i < campos.length; ++i) {
      final String campo = campos[i];
      UiApplication.getUiApplication().invokeLater(new Runnable() {
        public void run() {
          listaMensajes.add(new LabelField(campo));
        }
      });
    }
    

    You see the difference?

  • Maximum HttpConnection without connections exceeded

    Hello and good day,

    Please, what is the most effective way to manage http connections in a case where, for example I need to load data from people and display like this:

    name of the image

    --------------    --------------------------

    name of the image

    ---------------  ----------------------------

    now I have to display @ 200 +, so I downloaded all the names first and created a pool of threads to manage the download of images, I have an exception when the downloading more than 20 images by doing a httpconnection is there a way to share the httpconnection knowing that the url of the picture is different for each line, I really need to know Thank you.

    We use three threads in a queue of orders where we throw just runnables (with a reminder for the result).
    We have changed the number, a few times, but 3 seemed the best (without real analysis, because it was not so important)

  • Download the image via httpConnection very slowly

    I've been wroted a function to get a picture from the internet, the size of the image always in 50x50px, very small, but I have to waste a lot of time for reveiving given, here is my code:

    package code;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    import javax.microedition.io.Connector;
    import javax.microedition.io.HttpConnection;
    
    import net.rim.device.api.io.IOCancelledException;
    import net.rim.device.api.io.IOUtilities;
    import net.rim.device.api.ui.UiApplication;
    
    public class HttpUtility
    {
        private static byte[] _imageData;
        private static String _url;
    
        public static byte[] getInternetImage(String url, boolean waiting)
        {
            _url=url;
            _imageData=null;
    
            Runnable run=new Runnable()
            {
                public void run()
                {
                    byte[] data=null;
    
                    try {
                        HttpConnection httpConnection=(HttpConnection) Connector.open(_url+Function.updateConnectionSuffix());
                        InputStream inputStream=httpConnection.openInputStream();
    
                        if(inputStream.available()>0)
                        {
                            data=IOUtilities.streamToBytes(inputStream);
                            inputStream.read(data);
    
                            _imageData=data;
                        }
                    } catch(IOCancelledException e2) {Function.errorDialog(e2.toString());}
                      catch (IOException e) {Function.errorDialog(e.toString());}
                }
            };
    
            if(waiting)
            {
                UiApplication.getUiApplication().invokeAndWait(run);
            } else {
                UiApplication.getUiApplication().invokeLater(run);
            }
    
            return _imageData;
        }
    }
    

    The updateConnectionSuffix() to determine the network environment and choose a better way for httpConnection.

    Is there a problem in my code? I have no idea

    invokelater executes on the thread of the event, and not on a separate thread.
    currently you block your UI until data is available.

    See
    http://supportforums.BlackBerry.com/T5/Java-development/what-is-the-event-thread/Ta-p/446865

    Take a look at the httpdemo to see how you could do it better.

  • Uncaught exception on HttpConnection when the URL is blocked

    I access my request, a service URL web restful. Whenever the device is connected, but the URL is not accessible or non-responsive for some reason, I get an untrapped exception. All I want is to catch the exception and displays an appropriate message.

    Ideally, I'd like

    1. check whether the URL is accessible

    2. wait a little longer if the URL is accessible but slow

    Please suggest. Thank you.

    Code: (relevant articles)

        public void fieldChanged(Field field, int context) {
    
            if (field == btnOK) {
                UiApplication.getUiApplication().invokeLater(new Runnable() {
    
                    public void run() {
                                    String value=VerifyPinCode(rdPinCode.getText(),rd.getText());
    
                                    if (value.substring(0,4).equals("true")) {
                                                                            // do stuff
                                    } else {
                                        count = count++;
                                    }
                                  }
                });
    
            } else if (field == btnCancel) {
                close();
            }
    
        }
    
        public String VerifyPinCode(String PinCode, String VRN) {
            try {
    
                if (WebService.CheckConn())
                        {
                            try{
                        WebService wb = new WebService(
                                "http://webservice.somewhere.com:8088/mywebservice.svc/WebTestMethod/"
                                            + VRN
                                        + "/" + PinCode);
                               wb.start();
                        wb.join();
                        Responce = wb.Call();
                        }
                        catch(InterruptedException  ex)
                        {
                            Dialog.alert("No Internet Connection");
                        }
                    }
    
    public class WebService extends Thread {
        static HttpConnection con = null;
        static InputStream is = null;
        static StringBuffer rawResponse;
        String URL;
        public String resultant;
    
        WebService(String url) {
            URL = url + getConnectionString() + ";ConnectionTimeout=20000";
    
        }
    
        public void run() {
    
            try {
                con = (HttpConnection) Connector.open(URL, Connector.READ_WRITE,
                        true);
                int rcc = con.getResponseCode();
    
            } catch (IOException e) {
                // TODO Auto-generated catch block
                con = null;
                // Status.show(e.getMessage());
            }
    
            //catch (Exception ex) {
            // TODO Auto-generated catch block
            //con = null;
            // Status.show(e.getMessage());
            //}
    
        }
    
        public String Call() {
            try {
    
                // ConnectionTimeout=9000;";
                if (CheckConn()) {
    
                    if (con == null) {
                        rawResponse = new StringBuffer();
                        rawResponse.append("Timed out");
    
                    } else {
                        is = con.openInputStream();
                        // // Status.show("3");
    
                        byte[] responseData = new byte[10000];
                        int length = 0;
                        rawResponse = new StringBuffer();
                        while (-1 != (length = is.read(responseData))) {
                            rawResponse.append(new String(responseData, 0, length));
                            // Status.show("4");
    
                        }
                    }
                } else {
                    Status.show("Internet service is not avaiable.");
                }
                // Status.show(result);
    
            } catch (Exception ex) {
                Status.show("Internet is not responding");
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                    if (con != null) {
                        con.close();
                    }
                } catch (Exception e) {
                    // Status.show(e.getMessage());
                }
            }
            return rawResponse.toString();
    
        }
    
        public String getConnectionString() {
    
            String connectionString = "";
            if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
                connectionString = ";interface=wifi";
            }
    
            else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
                connectionString = ";deviceside=false";
            } else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
                String carrierUid = getCarrierBIBSUid();
                if (carrierUid == null) {
                    connectionString = ";deviceside=true";
                } else {
                    connectionString = ";deviceside=false;connectionUID="
                            + carrierUid + ";ConnectionType=amdeeas-public";
                }
            } else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
                connectionString = ";None";
    
            }
    
            return connectionString;
        }
    
        public String getCarrierBIBSUid() {
    
            net.rim.device.api.servicebook.ServiceRecord[] records = ServiceBook
                    .getSB().getRecords();
            int currentRecord;
    
            for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
                if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
                    if (records[currentRecord].getName().toLowerCase()
                            .indexOf("bibs") >= 0) {
                        return records[currentRecord].getUid();
                    }
                }
            }
    
            return null;
        }
    
        public static boolean CheckConn() {
            try {
                if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
                    return true;
                } else if (CoverageInfo.getCoverageStatus() >= 2) {
                    return true;
                } else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_DIRECT) {
                    return false; //false for device, true for simulator
                } else {
                    return false;
                }
            } catch (Exception ex) {
                Dialog.alert("No Internet Connection");
                return false;
            }
        }
    
    }
    

    remove the thread.join and the call to Call(), you block the user interface and the device to start a thread at all.
    To get a response from the thread, you can use the callback model, for example.

  • Too many Threads exception

    Hello everyone, hope you can help me in this question since I'm having a time really bad when using threads on my request. Basically, I am during the extraction of data from the internet using Basic authentication Http. for this, I created a style waiting screen that will show while downloading data from the Internet... all right, but when you make a reminder for updating an ObjectListField with the results of the operation (public void didReceivedResponse (byte [] data) on the example)... my code starts fadlng son as it is inside a loop for... I really have no idea what's going on... even on eclipse in debugging it continues execution of the run method of the HttpHelper class. These are the classes that I am referring:

    package login.example;
    
    import java.util.Vector;
    
    import login.example.model.Noticias;
    import login.example.networking.HttpHelper;
    import login.gui.WaitScreen;
    import net.rim.device.api.ui.Field;
    import net.rim.device.api.ui.FieldChangeListener;
    import net.rim.device.api.ui.UiApplication;
    import net.rim.device.api.ui.component.ButtonField;
    import net.rim.device.api.ui.component.LabelField;
    import net.rim.device.api.ui.component.ObjectListField;
    import net.rim.device.api.ui.component.SeparatorField;
    import net.rim.device.api.ui.container.MainScreen;
    
    import com.kruger.exceptions.ParserException;
    import com.kruger.networking.interfaces.HttpDelegate;
    import com.kruger.parsing.NoticiasJsonParser;
    
    /**
     * A class extending the MainScreen class, which provides default standard
     * behavior for BlackBerry GUI applications.
     */
    public final class LoginExampleScreen extends MainScreen implements
            FieldChangeListener, HttpDelegate {
        /**
         * Creates a new MyScreen object
         */
    
        ObjectListField objectField;
        WaitScreen waitScreen;
        ButtonField loginButton;
        Vector listaNoticias;
    
        public LoginExampleScreen() {
            // Set the displayed title of the screen
            setTitle("MyTitle");
    
            loginButton = new ButtonField("Start");
            loginButton.setChangeListener(this);
            add(loginButton);
            add(new SeparatorField());
            add(new LabelField("Noticias"));
            objectField = new ObjectListField(){
    
                protected boolean navigationClick(int status, int time) {
                    if(objectField.getSize()==0) return true;
                    Noticias noticiaSeleccionada = (Noticias) objectField.get(objectField, objectField.getSelectedIndex());
                    UiApplication.getUiApplication().pushScreen(new DetailScreen(noticiaSeleccionada));
                    return true;
    
                }
    
            };
            objectField.setEmptyString("No se han encontrado resultados",
                    LabelField.VCENTER);
            objectField.setChangeListener(this);
            add(objectField);
    
        }
    
        public void didReceivedResponse(byte[] data) {
            if (data != null) {
                waitScreen.hideScreen();
                NoticiasJsonParser noticiasParser = new NoticiasJsonParser();
                    try {
                        noticiasParser.initialize(data);
                        Vector noticias = noticiasParser.readObjects();
                        listaNoticias=noticias;
                        UiApplication.getUiApplication().invokeLater(new Runnable() {
    
                            public void run() {
                                updateNoticiasList();
    
                            }
                        });
    
                    } catch (ParserException e) {
    
                        e.printStackTrace();
                    }
    
            }
    
        }
    
        private void updateNoticiasList(){
    
            Object[] noticiasList = new Object[listaNoticias.size()];
            listaNoticias.copyInto(noticiasList);
            objectField.set(noticiasList);
        }
    
        public void didReceiveUnauthorizedResponse() {
            waitScreen.hideScreen();
            UiApplication.getUiApplication().invokeLater(new Runnable() {
                public void run() {
                    UiApplication.getUiApplication().pushScreen(new LoginScreen());
                }
            });
    
        }
    
        public void fieldChanged(Field field, int context) {
                waitScreen = new WaitScreen();
                HttpHelper helper = new HttpHelper(
                        "http://localhost:8088/simple-login/rest/noticias", null,
                        this);
                helper.setOperation(HttpHelper.GET);
                helper.start();
    
        }
    }
    
    package login.example.networking;
    
    import java.io.DataInputStream;
    import java.io.IOException;
    
    import javax.microedition.io.HttpConnection;
    
    import login.example.ApplicationPreferences;
    import net.rim.device.api.io.Base64OutputStream;
    import net.rim.device.api.io.transport.ConnectionDescriptor;
    import net.rim.device.api.io.transport.ConnectionFactory;
    import net.rim.device.api.system.DeviceInfo;
    import net.rim.device.api.util.ByteVector;
    
    import com.kruger.networking.interfaces.HttpDelegate;
    
    public class HttpHelper extends Thread {
    
        private byte[] postData;
        private String url;
        private String operation;
        private HttpDelegate delegate;
        private HttpConnection connection;
    
        public static final String GET = "GET";
        public static final String POST = "POST";
        private ConnectionFactory connectionFactory = new ConnectionFactory();
    
        public HttpHelper(String url, byte[] postData, HttpDelegate delegate) {
            this.url = url;
            this.postData = postData;
            this.delegate = delegate;
        }
    
        public HttpHelper(String url, byte[] postData, HttpDelegate delegate,
                String operation) {
            this.url = url;
            this.postData = postData;
            this.delegate = delegate;
            this.operation = operation;
        }
    
        public void run() {
            if (operation == null)
                delegate.didReceivedResponse(null);
            if (operation == GET) {
                ConnectionDescriptor connectionDescriptor = connectionFactory
                        .getConnection(url);
                DataInputStream din = null;
                final ByteVector responseBytes = new ByteVector();
                int responseCode;
                connection = (HttpConnection) connectionDescriptor.getConnection();
                String loginInfo = ApplicationPreferences.getInstance().getUsername()+":"+ApplicationPreferences.getInstance().getPassword();
                String encodedLogin;
                try {
                    encodedLogin = new String(Base64OutputStream.encode(
                            loginInfo.getBytes(), 0, loginInfo.length(), false,
                            false), "UTF-8");
                    connection.setRequestProperty("Authorization", "Basic "
                            + encodedLogin);
                    //Send the Device PIN number
                    connection.setRequestProperty("DeviceId", String.valueOf(DeviceInfo.getDeviceId()));
                    responseCode = connection.getResponseCode();
                    switch (responseCode) {
                        case HttpConnection.HTTP_UNAUTHORIZED:
                        case HttpConnection.HTTP_FORBIDDEN: {
                            Thread delegateThread=new Thread(){
                                public void run(){
                                    delegate.didReceiveUnauthorizedResponse();
                                }
                            };
                            delegateThread.start();
                            connection.close();
                            return;
                        }
                    }
                    din = connection.openDataInputStream();
                    int i = din.read();
                    while (-1 != i) {
                        responseBytes.addElement((byte) i);
                        i = din.read();
                    }
                } catch (IOException e) {
                    System.out.println(e.getMessage());
                    e.printStackTrace();
                    return;
                } finally {
                    try {
                        connection.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (responseBytes != null && responseCode != 0) {
                    Thread delegateThread=new Thread(){
                        public void run(){
                            delegate.didReceivedResponse(responseBytes.toArray());
                        }
                    };
                    delegateThread.start();
                    return;
    
                }
            } else if (operation == POST) {
                return;
            }
        }
    
        public String getOperation() {
            return operation;
        }
    
        public void setOperation(String operation) {
            this.operation = operation;
        }
    
    }
    
    package login.gui;
    
    import net.rim.device.api.system.Bitmap;
    import net.rim.device.api.system.Display;
    import net.rim.device.api.system.GIFEncodedImage;
    import net.rim.device.api.ui.Field;
    import net.rim.device.api.ui.Graphics;
    import net.rim.device.api.ui.UiApplication;
    import net.rim.device.api.ui.container.FullScreen;
    import net.rim.device.api.ui.container.VerticalFieldManager;
    
    public class WaitScreen extends FullScreen {
    
        private GIFEncodedImage _image;
        private int _currentFrame;
        private int _width, _height, _xPos, _yPos;
        private AnimatorThread _animatorThread;
        private Bitmap backgroundBitmap;
    
        public WaitScreen() {
            super(new VerticalFieldManager(), Field.NON_FOCUSABLE);
            //TODO: Correctly handle icons
            GIFEncodedImage img = (GIFEncodedImage) GIFEncodedImage.getEncodedImageResource("loading6.agif");
    
            // Store the image and it's dimensions.
            _image = img;
            _width = img.getWidth();
            _height = img.getHeight();
            _xPos = ((Display.getWidth() - _width) >> 1);
            _yPos = ((Display.getHeight() - _height) >> 1)+50;
            // Start the animation thread.
            _animatorThread = new AnimatorThread(this);
            _animatorThread.start();
            UiApplication.getUiApplication().pushScreen(WaitScreen.this);
            //TODO: handle correctly background
            backgroundBitmap=Bitmap.getBitmapResource("Wallpaper1.png");
          }
    
        protected void paintBackground(Graphics graphics) {
            super.paintBackground(graphics);
            graphics.drawBitmap(0, 0, backgroundBitmap.getWidth(), backgroundBitmap.getHeight(), backgroundBitmap, 0, 0);
        }
    
        protected void paint(Graphics graphics) {
            super.paint(graphics);
                    // Draw the animation frame.
                    graphics
                      .drawImage(_xPos, _yPos, _image
                        .getFrameWidth(_currentFrame), _image
                          .getFrameHeight(_currentFrame), _image,
                        _currentFrame, 0, 0);
        }
    
        protected void onUndisplay() {
            _animatorThread.stop();
        }
    
        private class AnimatorThread extends Thread {
            private WaitScreen _theField;
            private boolean _keepGoing = true;
            private int _totalFrames, _loopCount, _totalLoops;
            public AnimatorThread(WaitScreen _theScreen) {
                    _theField = _theScreen;
                    _totalFrames = _image.getFrameCount();
                    _totalLoops = _image.getIterations();
    
            }
    
            public synchronized void stop() {
                    _keepGoing = false;
            }
    
            public void run() {
                    while (_keepGoing) {
                            // Invalidate the field so that it is redrawn.
                            UiApplication.getUiApplication().invokeAndWait(
                              new Runnable() {
                                    public void run() {
                                            _theField.invalidate();
                                    }
                            });
                            try {
                              // Sleep for the current frame delay before
                              // the next frame is drawn.
                              sleep(_image.getFrameDelay(_currentFrame) * 10);
                            } catch (InterruptedException iex) {
                            } // Couldn't sleep.
                            // Increment the frame.
                            ++_currentFrame;
                            if (_currentFrame == _totalFrames) {
                              // Reset back to frame 0
                              // if we have reached the end.
                              _currentFrame = 0;
                              ++_loopCount;
                              // Check if the animation should continue.
    
                            }
                    }
            }
    
        }
    
        public void hideScreen(){
            _animatorThread.stop();
            UiApplication.getUiApplication().invokeAndWait(new Runnable() {
    
                public void run() {
                    UiApplication.getUiApplication().popScreen(WaitScreen.this);
    
                }
            });
        }
    }
    

    Please any help would be great... or at least an explanation of what I'm doing wrong... I'm new to using Threads. Thank you very much.

    Note that the fieldchanged event is triggered not only by the user, but also by changes programmatically, for example when you add an item to a listfield.
    You can check the context to be! = http://www.blackberry.com/developers/docs/7.1.0api/net/rim/device/api/ui/FieldChangeListener.html#PR... to filter them.

  • HttpConnection doesn't work (with username and password)

    I'm trying to get the tweet content (where I login account, say 'username' and 'password')

    using the rest of the code and does not work.

    According to the flow of Code, I do not get the answer for the POSITION

    Int State = httpConn.getResponseCode ();

    I tried to capture an Ethereal trace on my laptop and I don't see any HTTP POST also.

    So I think that I get no response to the HTTP POST.

    I don't know what the problem is. Is there any problem in SET UP?

    I use the Simulator (9550). Version of the JDK BlackBerry 5.0.0.14

    Note: If open the browser in the Simulator and use the same URL that is used in the Code, I get answer and ask user name and password. Once I entered the username and password. I get valid data to tweet.

    Can someone help me in this context

    class SocialContentMessage extends Thread {
    
        private String _AuthenticationHash;
        private String _CompleteUrl;
        private ExtendedTextBoxField _MessageField;
    
        public SocialContentMessage(final ExtendedTextBoxField messageFieldLocal) {
            _MessageField = messageFieldLocal;
            _AuthenticationHash = getAuthData("username","password");
        }
    
        public void run() {
            getUpdates("http://twitter.com/statuses/friends_timeline.xml");
        }
    
        private String getAuthData(String userName, String userPassWord) { 
    
            // Update authentication hash from current userName & userPassWord.
            byte[] toEncode = (userName + ":" + userPassWord).getBytes();
            ByteArrayOutputStream newHash = new ByteArrayOutputStream(toEncode.length);
            Base64OutputStream base64OutputStream = new Base64OutputStream(newHash);
    
            try {
                base64OutputStream.write(toEncode, 0, toEncode.length);
                base64OutputStream.flush();
                base64OutputStream.close();
            } catch (IOException ioe) {
                // Null out hash.
                newHash = null;
            }
    
            // Set authentication hash, clear password.
            return newHash.toString();
        }
    
        private final void getUpdates(String url) {
    
            try {
    
                // Open stream and poll data
                // Create post data
                URLEncodedPostData post = new URLEncodedPostData("", false);
    
                // Create connection
                StreamConnection s = null;
                _CompleteUrl = url + "?" + post.toString();
                s = (StreamConnection)Connector.open(_CompleteUrl, Connector.READ_WRITE, true);
                HttpConnection httpConn = (HttpConnection)s;
                httpConn.setRequestProperty(HttpProtocolConstants.HEADER_AUTHORIZATION,
                        "Basic "+_AuthenticationHash);
    
                // Connect and check status
                int status = httpConn.getResponseCode();
    
                //W. 8.7.K9 handle redirects: Twitter has been using these to combat DoS attacks the past few days
                if (status == HttpConnection.HTTP_TEMP_REDIRECT || status == HttpConnection.HTTP_MOVED_TEMP || status == HttpConnection.HTTP_MOVED_PERM) {
                    String newURI = httpConn.getHeaderField("Location");
                    if (newURI != null) {
                        //great, we have the new URL: go get it
                        s = null;
                        httpConn = null;
                        _CompleteUrl = newURI + "?" + post.toString();
                        s = (StreamConnection)Connector.open(_CompleteUrl, Connector.READ_WRITE, true);
                        httpConn = (HttpConnection)s;
                        httpConn.setRequestProperty(HttpProtocolConstants.HEADER_AUTHORIZATION,
                                "Basic "+_AuthenticationHash);
                        status = httpConn.getResponseCode();
                    } else {
                        //give it a second to populate
                        long begin_wait = System.currentTimeMillis();
                        while (System.currentTimeMillis() - begin_wait < 1000 || status != HttpConnection.HTTP_OK) {
                            try {
                                sleep(100);
                            } catch (InterruptedException e) {
                                // Couldn't sleep
                            }
                            status = httpConn.getResponseCode();
                        }
                    }
                }
    
                if (status == HttpConnection.HTTP_OK) {
                    // Log success
                    // Create element, null connection for testing
                    StringBuffer out = new StringBuffer();
                    InputStream in = httpConn.openInputStream();
                    byte[] b = new byte[4096];
                    for (int n; (n = in.read(b)) != -1;) {
                        out.append(new String(b, 0, n));
                    }
                    String test = out.toString();
                    // end for testing
    
                    httpConn.close();
                    httpConn = null;
                    s = null;
    
                } else {
                    // Log failure
                }
            } catch (IOException e) {
                // Log IO Exception
            }
        }
    }
    

    Problem is resolved now...

    I don't know that I need to use the MDS Simulator before starting my program...

    I got the information of existing Questions...

  • How to create a dialog box for an inner thread

    Hi all

    I am trying to create a thread in which I am trying to establish an http connection. But when there is an exception. I want to inform the user of the exception by pushing a dialogue or a modal screen. But the dialogue is not calling. Any body knows how to push the inner thread dialog box

    / public class GPRSChanlInf implements Runnable {}

    public static thread = null;

    public String getResponse (String url_final) {}

    thread = new Thread (this);
    thread. Start();
    Thread.Sleep (20);

    }

    public void run() {}
    InputStream is = null;
    OutputStream os = null;
    HttpConnection conn = null;

    try {}

    Conn = (HttpConnection) Connector.open (url_final, Connector.READ_WRITE, true);

    }

    catch (Exception e) {e.printStackTrace () ;}
    }

    Looks OK code, intervened you in the code to ensure that the dialog box is actually called?

    Also can you confirm that this code is executed by a UiApplication who has "enterEventDispatcher()."

  • Analysis of response of HttpConnection

    Hello! I have the same problem as in this thread
    http://supportforums.BlackBerry.com/T5/Java-development/parsing-response-of-HttpConnection/m-p/13985...
    When I use this code:

    httpConn = GetConnection(_url);
    responseCode = httpConn.getResponseCode();
    if(responseCode == 200)
    {
        is = httpConn.openInputStream();
        StringBuffer stringBuffer = new StringBuffer();
        byte[] byteArr = null;
    
        int ch;
        while ((ch = is.read()) != -1) {
                stringBuffer.append((char)ch);
        }
    }
    

    I get in stringBuffer:

    «Ð\u009FÑ\u0080емиÑ\u008F Ð Ñ\u0083неÑ\u0082а 2011»

    Ð\u0092 Ð\u009CоÑ\u0081кве Ñ\u0081оÑ\u0081Ñ\u0082оÑ\u008FлаÑ\u0081Ñ\u008C Ð\u0092оÑ\u0081Ñ\u008CмаÑ\u008F Ñ\u0082оÑ\u0080жеÑ\u0081Ñ\u0082веннаÑ\u008F Ñ\u0086еÑ\

    I applied the advice of Peter and with this code

    httpConn = GetConnection(_url);
    responseCode = httpConn.getResponseCode();
    responseMessage = httpConn.getResponseMessage();
    if(responseCode == 200)
    {
        is = httpConn.openInputStream();
    
        StringBuffer stringBuffer = new StringBuffer();
        byte[] byteArr = null;
        byteArr = new byte[1];
        int readIn = 0;
    
        while((readIn = is.read(byteArr)) > 0) {
                String temp = "";
                try {
                     temp = new String (byteArr, 0, readIn, "UTF-8");
                } catch (Exception e) {
                   e.printStackTrace();
                }
            stringBuffer.append(temp);
    }
    

    I get this:

    2011

    \r
    \n2011.

    As you can see, he "ate" all characters, except the numbers and English letters, but I read all of the characters, of course.

    So how can receive this content as a String or byte array without losing characters?

    Replace this:

    StringBuffer stringBuffer = new StringBuffer();
    Byte [] byteArr = null;
    byteArr = new ubyte [1];
    Int read = 0;
                   
    While ((read = is.read (byteArr)) > 0) {}
    String temp = "";
    try {}
    Temp = new String (byteArr, 0, reading, 'UTF-8');
    } catch (Exception e) {}
    e.printStackTrace ();
    }
    stringBuffer.append (temp);

    }

    with something like

    Byte [] responseBytes = IOUtilities.streamToByte (is);

    String responseString = new String (responsebytes, "UTF - 8");

    It's not good, there's a try catch missing on the one hand, but you get the idea.

    If you then take the data to a parser that takes a stream, then only convert the bytes into a string, instead feeding in a ByteArrayinputStream using responseBytes (again, I probalby had it wrong, but you get the idea).

    I think it should overcome your problems.

  • HELP Needed HttpConnection PROBLEM

    Hi I'm a Newbie to the Blackberry development... I'm trying to read data from the URL through HttpConnection. Here it is my code. When I call through Simulator code, the following code does not run... System.out.println ("MDS getResponseCode" + c.getResponseCode ()); There is no exception too... Pls help what's wrong in my code...

    Thanks in advance - Poy

    import java.io.IOException;
    import java.io.InputStream;
    java.lang.String import;
    Import javax.microedition.io.Connector;
    Import javax.microedition.io.HttpConnection;
    Import net.rim.device.api.ui.Field;
    Import net.rim.device.api.ui.FieldChangeListener;
    Import net.rim.device.api.ui.UiApplication;
    Import net.rim.device.api.ui.component.ButtonField;
    Import net.rim.device.api.ui.component.LabelField;
    Import net.rim.device.api.ui.container.MainScreen;

    Main class
    SerializableAttribute public class HttpCxn extends UiApplication {}

    Starting point
    Public Shared Sub main (String [] args) {}
    HttpCxn httpCxn = new HttpCxn();
    httpCxn.enterEventDispatcher ();
    }

    Initial screen of calls
    public HttpCxn() {}
    pushScreen (new HttpCxnScreen());
    }

    }

    class HttpCxnScreen extends form {}

    Declare my initial variables

    ButtonField submitButton = new ButtonField ("Submit", ButtonField.CONSUME_CLICK);
    HttpCxnScreen screen = this;

    Main screen, including the entries for the character/server names
    public HttpCxnScreen() {}

    Create the label of title for the main screen
    LabelField mainTitle = new LabelField ("HTTP CONNECTION", LabelField.ELLIPSIS
    | LabelField.USE_ALL_WIDTH);
    Set title to the top of the label
    setTitle (mainTitle);
    Add other elements to the form

    Add (submitButton);

    Create the feature of the "submit" button
    submitButton.setChangeListener (new FieldChangeListener() {}

    ' Public Sub fieldChanged (field field, int context) {}
    Thread postnameThread = new Thread (new ServerConnection());
    postnameThread.start ();
    }

    });

    }

    http connection class
    ServerConnection class extends Thread {}

    String url = ""http://172.24.30.27: 9091/demo/index.jsp;deviceside=false ";"

    Method called by the Send button
    public ServerConnection() {}
    System.out.println ("test");
    }

    public void run() {}
    C HttpConnection = null;
    InputStream is = null;
    Response string;
    int rc;

    try {}
    StringBuffer buffer = new StringBuffer();
    System.out.println ("URL" + URL);
    c = (HttpConnection) Connector.open (url);
    System.out.println ("AZtest" + c); My debugger not crossed this line
    Get the response code is open the connection,
    Send the request and read HTTP response headers.
    The headers are stored until asked.
    System.out.println ("MDS getResponseCode" + c.getResponseCode ());
    RC = c.getResponseCode ();
    System.out.println ("CHECK MDS" + rc);
    If (rc! = HttpConnection.HTTP_OK) {}
    System.out.println ("HTTP_OK" + RC);
    throw new IOException ("HTTP response code:" + rc);
    }

    is = c.openInputStream ();

    Get the ContentType
    The string of type = c.getType ();

    The length and process data
    int len = (int) c.getLength ();
    If (len > 0) {}
    real int = 0;
    int BytesRead = 0;
    data Byte [] = new ubyte [len];
    While ((bytesread! = len) & (real! = - 1)) {}
    real = is.read (data, bytesread, len - bytesread);
    bytesRead += real;
    }
    } else {}

    int ch;

    While ((ch = is.read (())! = - 1) {}
    ch = is.read ();
    buffer. Append ((Char) ch);
    }
    response = buffer.toString ();

    }
    } catch (Exception e) {}

    e.printStackTrace ();

    }
    }
    }
    }

    This message can help.

  • Response of HTTPConnection JSON server at BB on Wifi

    Hey there,

    I created a class that extends from the Thread:

    • Connect Wifi to my Tomcat server.
    • Request (GET method) of a resource (JSON object) on the server.
    • Lire read in response, and then analyze the JSON.

    The connection is successfully established, the response is read and then comes the analysis that is the problem. Apparently he received the JSON response in a bad shape. I think the problem is with the synchronization of threads, because I'm trying to use this response to build the user interface after the analysis.

    Here is the code:

    Class WifiThread:

    public class WifiThread extends Thread {
    
      private String _url;  private String _response; private String _interface = ";interface=wifi";
    
       public ConnectionThread(String url) {  this._url = url;   }
    
       public void run() {        HttpConnection conn = null;        InputStream in = null;        int code;
    
             try {
    
                       conn = (HttpConnection) Connector.open(this._url + this._interface, Connector.READ);            conn.setRequestMethod(HttpConnection.GET);
    
                code = conn.getResponseCode();
    
                if (code == HttpConnection.HTTP_OK) {                in = conn.openInputStream();                ByteArrayOutputStream out = new ByteArrayOutputStream();
    
                    byte[] buffer = new byte[in.available()];                int len = 0;
    
                    while (-1 != (len = inputStream.read(buffer))) {                    out.write(buffer);                                   }
    
                    out.flush();                this._response = new String(out.toByteArray());
    
                    System.out.println(this._response);
    
                    if (out != null){                    out.close();                }                if (in != null){                    in.close();                }                if (conn != null){                    conn.close();                }            }
    
            } catch (Exception e) {            System.out.println("HTTP Thread: " + e.toString());            throw e;        }   }  
    

    That's how his name:

    public myApp extends UiApplication {
    
        public myApp() {
    
              String url = "http://[IP.Address]:[Port]/[Resource]"          WifiThread thread = new WifiThread(url);          thread.start();          thread.run();
    
              String response = thread.get_response();
    
              // Parse JSON string:          JSONObject jsonObj = MyParser.fromJSON(response);
    
              // Create UI          // ...
    
        }}
    

    Any help would be great. Thank you!

    I've seen this code before:

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ubyte [] buffer = new byte [in.available ()];
    int len = 0;
    {While (-1! = (len = {inputStream.read (buffer)))}
    out. Write (buffer);
    }
    out. Flush();
    This ._response = new String (out.toByteArray ());

    Can you tell me where you got it.  I want to see if I have removed it because I think that it is inefficient and made assumptions about the encoding.

    I suspect that you are sent a stream of UTF-8 bytes, in which case you can replace the above with something like:

    Byte [] responseBytes is (in) IOUtilities.streamToBytes;.

    try {}

    This ._response = new String (responseBytes, "UTF - 8");

    catch (Exception e) {}

    throw new RuntimeException ("unexpected decoding error:" + try);

    }

    If you have additional problems can empty you out the json using something like:

    System.out.println (this._response);

    and review to ensure that it matches what you expect and are Json valid.

    I hope this helps.

  • Dial the two thread simultaneius http

    In my application I want a main (UI) Thread and two other thread that runs at the same time, now in both the wire I want HttpConnection appeal, so it is possible for both the thread do HttpCall?

    I want to know - is it possible?

    Because if one thread calls Http between another thread also do Http call connection so that it will give the error as "Stream already open" because the first thread was opened the stream and before the closing of the first stream son second thread will open the stream, so please help me on this...

    Thank you

    There is nothing on the Blackberry that will prevent both two threads made http URLs of connections to the same (or other) at the same time.

    So the answer to your question is 'Yes it is possible. "

    Ok?

  • Problem on httpconnection

    I need get the XML from the server, and I use httpconnection.  Even I use the simple code. It may also not work. What is the problem

    Show the code below:

    SerializableAttribute public class XMLTestScreen extends form {}

    public XMLTestScreen() {}

    setTitle ("HttpConnection Demo");

    try {}

    HttpConnection coon = (HttpConnection) connector

    .the ("http://www.google.com.sg");

    Int State = coon.getResponseCode ();

    If (status == HttpConnection.HTTP_OK) {}

    Dialog.Alert ("Get");

    Add (new LabelField ("get"));

    } else {}

    Dialog.Alert ("Nothing");

    Add (new LabelField ("Nothing"));

    }

    } catch (Exception e) {}

    e.printStackTrace ();

    }

    }

    }

    Unfortunately to understand any code provided to you, you're gong to have to do an apprenticeship.  RexDoug suggested a number of places, let me suggest a bit more.

    The developer's Guide is a very good read, you can pick it up for 4.6 here.

    http://docs.BlackBerry.com/en/developers/deliverables/3802/development.PDF

    This has a chapter entitled: "Creating connections" inside is a promising section called «... data recovery» "sounds just like what you want.

    To save the search, the sticky thread that RexDoug suggested is here:

    http://supportforums.BlackBerry.com/Rim/Board/message?board.ID=java_dev&thread.ID=29103

    You will also find a free sample around code that did something like what you want, including this one:

    http://developerlife.com/tutorials/?p=884

Maybe you are looking for

  • 1439

    How loser mand r. 1439 pa ipot classik

  • I need to delete old email addresses in the address cache

    I need to delete old addresses of e-mail addresses collected and personal address books. What does not work (final deletion; addresses not back when Thunderbird is opened later): 1) right-click and delete; (2.) to write a new email... address list co

  • Update of the unnecessary notes (crashes at opening) from El Capitan

    Since I upgraded to El Capitan my Notes app did not work. I have a MacBook Air (2012 version) running 10.11.4. I followed in other discussions for the same problem and have tried patches duplicate who worked for others, but mine is still unusable. I

  • How to uninstall Blinx Beat?

    Impossible to uninstall Blinx Beat. How can I uninstall it?

  • 4620 to windows wireless connection problem 8

    Unable to connect wirleless to 4620 with windows 8 - home network works with windows 7 and windows XP but my new computer has windows 8 and can not do work - message says that the printer is not 'online' - Please help if you can.