2011-11-21 14 views
3
public int getChildrenCount(int groupPosition) { 
    if(children == null){ 
     new SalesRequest().execute(); // runs in other thread which 
             // initialises children with some value. 
     while(children == null){ 
      // I'm doin this to avoid null pointer Exception. 
      // So it comes out of the loop only when childern 
      // gets initialised. 
     } 
    } 
    return children.length; 
} 

私はこれを処理している方法に満足していません。これを行うより良い方法はありますか?このビジー待機を回避するにはどうすればよいですか?

+2

下の有権者もコメントを追加することができます。私は明確ではない場合、私は質問を変更することができます。私はいくつかの助けを求めています.. – ngesh

+0

私はdownvoterではありませんが、上記のコードを達成する? – zengr

+0

@ zengr ..その実際のアンドロイドコード..私は、サーバーの応答に基づいてUIを更新する必要があります。私はその方法から、その背中の背中をコントロールしていません。だから私はいくつかの変数を初期化するためにオーバーライドしました。 – ngesh

答えて

3

この問題の可能な解決策の倍数があります。最もエレガントな方法は、上記のCountDownLatchと同じです。また、

// Populate and create children structure of the calling object 
// When done, signal to callee that we have finished creating children 
childrenReady.countDown(); // This will release the calling thread into the while loop 

あなたがそうでなければ、UIスレッドアプリケーションからgetChildrenCount()を呼び出していないことを確認してください:

SalesRequest.execute方法で
// Lock to signal Children are created 
CountDownLatch childrenReady = new CountDownLatch(1/*wait for one signal*/); 
public int getChildrenCount(int groupPosition) { 
    if(children == null){ 
     SalesRequest request = new SalesRequest(childrenReady /*pass on this lock to worker thread*/); 
     request().execute(); // runs in other thread which 
             // initialises children with some value. 
     childrenReady.await();  // Wait until salesRequest finishes 
     while(children == null){ 
      // I'm doin this to avoid null pointer Exception. 
      // So it comes out of the loop only when childern 
      // gets initialised. 
     } 
    } 
    return children.length; 
} 

、あなたは以下を持つことができます:ここで あなたが進む可能性がどのようですあなたがサーバーから答えを得るまで応答が失われます。

関連する問題