2011-03-29 16 views
0

我正在爲OS 5上的Blackberry開發應用程序。我試圖在調用成功時訪問一些以前初始化的變量。但是,這些變量不具有它們的價值,我無法找到原因。如何從PhoneListener事件訪問全局變量?

當應用程序啓動時,testVariable設置爲5,一切都按預期工作。但是,當我嘗試從callConnected事件訪問變量時,它返回0.即使我將該變量放在PhoneEvents類中,它仍然會返回0.它具有一個PhoneEvents值,另一個值用於屏幕。不應該這些變量只有一個值,因爲它不是一個實例變量?我究竟做錯了什麼?有沒有其他方法可以從PhoneEvents類和TestScreen類訪問變量,並保持其值?提前致謝。

public class TestApp extends UiApplication { 
     public TestApp() { 
      TestScreen screen = new TestScreen(); 
      UiApplication.getUiApplication().pushScreen(screen); 
     } 

     public static void main(String[] args) { 
      Phone.addPhoneListener(new PhoneEvents()); 
      TestApp app = new TestApp(); 
      app.enterEventDispatcher(); 
     } 
    } 

    // The main screen. 
    public class TestScreen extends MainScreen { 
     public TestScreen() { 
      this.setTitle("Test"); 
      GlobalClass.testVariable = 5; 
     } 
    } 

    // A public static holding a variable I want to have access to. 
    public class GlobalClass { 
     public static int testVariable; 
    } 

    // The method that gets called when a call is made. 
    public class PhoneEvents implements PhoneListener { 
     public void callConnected(int callId) { 
      int x = GlobalClass.testVariable; 
     } 
    } 

回答

0

PhoneListener回調在不同的進程中運行。例如,您可以通過調用UiEngine.getUiEngine()。getActiveScreen()來注意到這一點,當您在註冊PhoneListener之前調用PhoneListener回調和應用程序屏幕時,它會返回手機屏幕。靜態變量也不同。

一種解決方案是把你的應用程序數據的RuntimeStore:

class ApplicationData 
{ 
    public int testVariable; 
} 

ApplicationData appData = new ApplicationData(); 
appData.testVariable = 5; 

RuntimeStore.getRuntimeStore().put(MY_DATA_ID, appData); 

public class PhoneEvents implements PhoneListener { 
    public void callConnected(int callId) { 
     ApplicationData appData = (ApplicationData) RuntimeStore.getRuntimeStore().get(MY_DATA_ID); 
     int x = appData.testVariable; 
    } 
} 
+0

)謝謝!這正是我最終做的事情,但它不斷讓我知道是否還有別的東西我錯過了,很高興能得到確認。 – 2011-04-18 19:33:01

0

這只是一種替代方法。使GlobalClass成爲一個Singleton。這將保證你每次都能得到同一個類的實例。

這是一個顯示如何製作單身人士的鏈接。

Singleton with Arguments in Java

這維基百科的鏈接會給出一個深入解釋有關單身。希望這有助於

http://en.wikipedia.org/wiki/Singleton_pattern

+0

它仍然沒有保留價值。不錯的方法,但可能會用於其他項目。 – 2011-03-30 18:16:07

+0

單身人士不會工作,因爲他們在不同的過程。黑莓架構從根本上說是錯誤的...... :( – lithium 2011-09-02 15:24:20