2012-03-08 6 views
0

私はGuice(Guice v3と正確にはRoboguice v2)を使用しています。コンストラクタでGuiceシングルトンにアクセスする

私が持っているシングルトン..私はアカウントシングルトンへのアクセスを得ることができますどのように

@Singleton 
Accounts 
{ 
    public Account[] getAllAccounts() 
    { 
     // Stuff 
    } 
} 

そして、私はまた、そのコンストラクタで上記へのアクセスを必要とするクラスを持っている...

public class AccountListAdapter extends ArrayAdapter<Account> 
{ 
    public AccountListAdapter(Context c) 
    { 
     super(c, R.layout.account_list_row, R.id.accountName, accounts.getAllAccounts()); 
    } 

    ... 
} 

上記のsuper()コールの最後のパラメータとして使用されていますか?インスタンス変数が作成される前にコンストラクタが実行されるため。

ありがとうございます!

+0

アクティビティonCreate()中にAcountListAdapterを作成していますか? –

+0

はい私はそれをやっています。 –

答えて

2

これは2通りの方法で処理できます。

まず、あなたのアクティビティにアダプタを直接注入することができます。 )

public class AccountListAdapter extends ArrayAdapter<Account> 
{ 
    @Inject 
    public AccountListAdapter(Context c, Accounts acconts) 
    { 
     super(c, R.layout.account_list_row, R.id.accountName, accounts.getAllAccounts()); 
    } 

    ... 
} 

第二に、あなたはのonCreate(中にオブジェクトを自分で構築することができます:あなたは、以下の注釈を追加する必要が念頭に置いておく

public class ExampleActivity extends RoboActivity{ 

    @Inject 
    private AccountListAdapter accountListAdapter; 

    .... 
    //then register it with your listView in your onCreate() 
} 

:これは、現在のコンテキストだけでなく、singeltonが含まれます:

public class ExampleActivity extends RoboActivity{ 

    @Inject 
    private Account accounts; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     AccountListAdapter accountListAdapter = new AccountListAdapter(this, accounts); 

    //then register it with your listView 
} 

ListActivityを正常に使用するには、RoboActivityの代わりにRoboguice ListActivityを拡張する必要があります。これがあなたのために働くかどうか私に教えてください。

関連する問題