调用Web服务时为什么进度条会挂起?

时间:2014-02-13 05:31:19

标签: blackberry

我正在进行Web服务调用。我正在显示进度条,直到Web服务响应未来。但它挂起(停止递增值)或一段时间它会显示错误。 我们可以克服这个问题。

这是我的代码

    public class MyApp extends UiApplication
    {

        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.
            MyApp theApp = new MyApp();       
            theApp.enterEventDispatcher();
        }



        public MyApp()
        {

            MyScreen.progressBar=new ProgressBar("Loading data", 100, 90);
            MyScreen.progressBar.start();
            // Push a screen onto the UI stack for rendering.
            pushScreen(new MyScreen());
        }    
    }

====================================================================



        public final class MyScreen extends MainScreen
        {
            public static ProgressBar progressBar;

            /**
             * Creates a new MyScreen object
             */
            public MyScreen()
            {        
                // Set the displayed title of the screen       
                setTitle("MyTitle");
                add(new LabelField("Test"));

        for (int i = 0; i <10000; i++) {
            System.out.println("i");

        }



                // TODO Auto-generated method stub
                if ( ProgressBar.popup.isDisplayed()){
                     ProgressBar.popup.close();
                     ProgressBar.remove();

                }


        UiApplication.getUiApplication().invokeLater(new Runnable() {

            public void run() {
                // TODO Auto-generated method stub
            UiApplication.getUiApplication().pushScreen(new SecondScreen()) ;
            }
        });
            }
        }
    ===========================================================

        public class SecondScreen extends MainScreen {
            protected void onDisplay() {

                ConnectJsonWebService conjsonTocService = new ConnectJsonWebService();

                conjsonTocService.jsonResult("http://50.57.145.165:8080/FirstGroupRailApps/jservices/rest/"+"a/"+"destinationdashboard"+"?crsCode="+"PAD"+"&device_pin="+Integer.toHexString(DeviceInfo.getDeviceId()));
                System.out.println("**************Destination Response**********************"+conjsonTocService.response);
                // TODO Auto-generated method stub
                super.onDisplay();
            }

            public SecondScreen() {
                // TODO Auto-generated constructor stub
            }
        }


    =====================================================================
    package mypackage;
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
    //File Name                  :       ProgressBar.Java
    //Created On                 :       22 April 2010
    //Created By                 :       Ekansh Srivastava
    //Purpose                    :       This source file contains class which is a thread used for 
    //                                 showing cinnecting PopUpWindow after LOGIN 
    //Change History
    //Date                    Modified By                     Change
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
    import net.rim.device.api.system.Display;
    import net.rim.device.api.ui.Field;
    import net.rim.device.api.ui.UiApplication;
    import net.rim.device.api.ui.component.ButtonField;
    import net.rim.device.api.ui.component.Dialog;
    import net.rim.device.api.ui.component.GaugeField;
    import net.rim.device.api.ui.component.LabelField;
    import net.rim.device.api.ui.container.HorizontalFieldManager;
    import net.rim.device.api.ui.container.PopupScreen;
    import net.rim.device.api.ui.container.VerticalFieldManager;

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //Class Name      :       ProgressBar
    //Created On      :       22 April 2010
    //Created By      :       Ekansh Srivastava
    //Purpose         :       This class is a thrad which is used for Displaying Connecting PopUp after LogIn
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public class ProgressBar extends Thread {

    private int maximum, timeout;

    private static boolean useful;

    public static PopupScreen popup;

    public static GaugeField gaugeField;
    public static LabelField gaugetitleField;

    private  ButtonField stopBtn; 
    int iterations = 0;
    public static ProgressBar instance;

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //      Function Name           :       ProgressBar (Constructor)
    //      Created On              :       22 April 2010
    //      Created By              :       Ekansh Srivastava
    //      Input Parameters        :       String title, int maximum, int timeout
    //      Output                  :       void
    //      Purpose                 :       Executes the class, set the values and displays the Progress Bar
    //      Change History
    //      Date                Modified By                             Change
    //
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public ProgressBar(String title, int maximum, int timeout) 
    {
    try
    {
        this.maximum = maximum;
        this.timeout = timeout;

        VerticalFieldManager manager = new VerticalFieldManager(VerticalFieldManager.VERTICAL_SCROLL);
        HorizontalFieldManager buttonManager = new HorizontalFieldManager(); 
        popup = new PopupScreen(manager){
            public void sublayout(int width, int height){

                super.sublayout(width,height);
                setPosition(12,2*Display.getHeight()/3);
                }

        };
        gaugeField = new GaugeField(null, 1, maximum, 1, GaugeField.NO_TEXT);
        stopBtn = new ButtonField("CANCEL")
                    {
                        protected boolean navigationClick(int status,int time)
                        {
                            remove();
                            onClose();
                            return true;                         
                        }
                    };

      //  Font fon = Utility.getsFont(1);

       // buttonManager.add(new SeparatorFieldClass(65,0));        
       // stopBtn.setFont(fon);
                    gaugetitleField=new LabelField(title,Field.USE_ALL_WIDTH);
        manager.add(gaugetitleField);
        manager.add(gaugeField);
        manager.add(buttonManager);

        instance = this;

    }
    catch(Exception e)
    {
        System.out.println("Exception in ProgressBAr : ProgressBar()" + e.toString());
    }

    }

    public void run() 
    {
    try
    {
        useful = true;

            UiApplication.getUiApplication().invokeLater(new Runnable() {
                public void run() {
                        UiApplication.getUiApplication().pushScreen(popup);
                }
            });



        while (useful) {
                    try {
                        Thread.sleep(timeout);
                } catch (Exception e) {
                    }

                    if (++iterations > maximum)
                        iterations = 1;
                    UiApplication.getUiApplication().invokeLater(new Runnable() {

                        public void run() {
                            // TODO Auto-generated method stub
                              gaugeField.setValue(iterations);
                        }
                    });

            }

            if (popup.isDisplayed()) {
                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {
                                UiApplication.getUiApplication().popScreen(popup);
                            }
                    });
        }
    }
    catch(Exception e)
    {
        System.out.println("Exception in ProgressBAr : run()" + e.toString());
    }
    }


    /* To remove Progress Bar*/
    public static synchronized void remove() 
    {
    useful = false;
    }

    public static ProgressBar getInstance()
    {
    if(instance == null)
    {
        instance = new ProgressBar("Connecting..",100,50);
    }

    return instance;
    } 

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //      Function Name           :       onClose
        //      Created On              :       22 April 2010
        //      Created By              :       Ekansh Srivastava
        //      Input Parameters        :       None
        //      Output                  :       Void
        //      Purpose                 :       This method is remove Progress Bar and Close the Application
        //      Change History
        //      Date                Modified By                             Change
        //
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public boolean onClose() 
    {
    try
    {
       Dialog.inform("Application will exit");
    }
    catch(Exception e)
    {
        System.out.println("Exception in ProgressBar : onClose() "+e.toString());
    } 

    return true;
    }       

    }



================================================
package mypackage;


import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;


import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;

public class ConnectJsonWebService extends Thread {


     private String url;
     public String response;
     private String myinterface = ";deviceside=true";

      public void run() {
             HttpConnection conn = null;
             InputStream in = null;
             int code;

       try {


          conn = (HttpConnection) Connector.open(this.url + NetworkAvailabilityCheck.getUrl(), Connector.READ);
             conn.setRequestMethod(HttpConnection.GET);
             code = conn.getResponseCode();

             if (code == HttpConnection.HTTP_OK) {
                 in = conn.openInputStream();
                 byte[] buffer = IOUtilities.streamToBytes(in);
                 this.response = new String(buffer,"UTF-8");


                 if (in != null){
                     in.close();
                 }
                 if (conn != null){
                     conn.close();
                 }
             }

         } catch (Exception e) {
            Dialog.inform(e.toString());
         }
    }  

    public String jsonResult(String url){
      this.url = url;
    //  this.start();
     this.run();
      return response;
     }

}

1 个答案:

答案 0 :(得分:0)

此代码中还有其他一些奇怪之处,但最重要的是:

public String jsonResult(String url){
  this.url = url;
//  this.start();
 this.run();
  return response;
 }

this.run()会立即执行连接代码,这可能不是您想要的,因为您在事件线程上运行,因此实际上您阻止了事件线程,因此阻止了所有Ui更新。网络代码是阻塞的,因此不应在事件线程上执行。有关详细信息,请参阅此处:

What is the Event Thread

Blocking operation not permitted on Event Thread

因此,您应该启动它而不是运行您的线程。搜索有关使用Java线程的更多信息,例如,请参阅此处:

introduction-to-java-threads

如果你以非阻塞的方式运行它,那么你将异步地获得响应,所以你需要查看Observer模式之类的东西。

所有这些都已在本论坛和其他论坛上多次介绍过,因此我建议您查找人们专门为BlackBerry开发的其他代码示例,以下载和处理数据。

<强>更新

你问道: “你能让我演示一个演示,以便我理解它的基本原理”

我不确定如何制作比已经存在的许多样本更好的东西,包括BB网站本身的样本,如下所示:

Network API

您提供的链接

Implement Simplified Observer Pattern to Avoid BlackBerry UI Lockup

似乎是使用观察者模式的一个很好的例子,我看到你发现了我写的一些样本,它们涵盖了相同的基础。我认为适合您的操作是按原样实现其中一个示例,通过代码并尝试理解它。

事件线程并不容易,也不是网络,我认为任何人都不能挥动魔杖并让你理解它。我想你需要自己解决这个问题。

祝你好运。