Skip to content

Instantly share code, notes, and snippets.

@Khanashima
Last active January 2, 2016 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Khanashima/5eb760b5c9241e1f931d to your computer and use it in GitHub Desktop.
Save Khanashima/5eb760b5c9241e1f931d to your computer and use it in GitHub Desktop.
Androidアプリ開発でDIのDagger2の使用方法 ref: http://qiita.com/kiimiiis/items/20c3fa79988ed3ccb3c9
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.google.dagger:dagger:2.0'
apt 'com.google.dagger:dagger-compiler:2.0'
provided 'org.glassfish:javax.annotation:10.0-b28'
}
@Component(modules = RecipientRepositoryModule.class)
public interface CRecipientRepository {
IRecipientRepository maker();
}
public interface IRecipientRepository {
public void insert(String name, String email);
public Recipient getRecipient(long id);
}
public class MockRecipientRepository implements IRecipientRepository {
public void insert(String name, String email) {
//Mock
}
/**
* 宛先オブジェクトを返すモック
*/
public Recipient getRecipient(long id) {
Recipient recipient = new Recipient();
recipient.id = 100L;
recipient.email = "mock@mock.jp";
recipient.name = "name";
recipient.is_delivery = 1;
return recipient;
}
}
public class NewRecipient extends AppCompatActivity {
@Inject IRecipientRepository recipientRepository;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_recipient);
this.recipientRepository = DaggerCRecipientRepository.create().maker();
this.recipientRepository.insert("テスト", "test01@android.com");
Recipient recipient = this.recipientRepository.getRecipient(1L);
Log.d("DB",recipient.email);
}
}
public class RecipientRepository implements IRecipientRepository{
/**
* Recipientテーブルにインサート
*
* @param String name 氏名
* @param String email メールアドレス
*/
public void insert(String name, String email) {
Recipient recipient = new Recipient();
recipient.name = name;
recipient.email = email;
recipient.is_delivery = 1;
recipient.save();
}
/**
* プライマリーキーで宛先テーブルを検索して取得
*
* @param Long _id ID
*
* @return Recipient recipient Recipientオブジェクト
*/
public Recipient getRecipient(long id) {
Recipient recipient = SQLite.select().from(Recipient.class)
.where(Recipient_Table.id.eq(id)).and(Recipient_Table.is_delivery.eq(1)).querySingle();
String query = SQLite.select().from(Recipient.class)
.where(Recipient_Table.id.eq(id)).and(Recipient_Table.is_delivery.eq(1)).getQuery();
Log.d("DbQuery", query);
return recipient;
}
}
@Module
public class RecipientRepositoryModule {
@Provides
public IRecipientRepository provideRecipientRepository() {
return new RecipientRepository(); //DB使用
//return new MockRecipientRepository(); //モック
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment