SlideShare a Scribd company logo
1 of 20
Download to read offline
Room with Testing
and Rxjava
報告⼈人:Vincent
• ⽤用過sqlite

• ⽤用過dao

• ⽤用過room
• ⽤用過sqlite

• ⽤用過dao

• ⽤用過room
Gradle
implementation “android.arch.persistence.room:runtime:$room_version”
// use kapt for Kotlin
annotationProcessor “android.arch.persistence.room:compiler:$room_version"
// optional - RxJava support for Room
implementation "android.arch.persistence.room:rxjava2:$room_version"
Room architecture
RoomDatabase
@Database(entities = {WordMain.class, WordInfo.class, WordExample.class,
SearchTime.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract WordMainDao wordMainDao();
public abstract WordInfoDao wordInfoDao();
public abstract WordExampleDao wordExampleDao();
public abstract SearchTimeDao searchTimeDao();
}
class AppDbHepler{
AppDatabase appDatabase = Room.databaseBuilder(context, AppDatabase.class,
dbName).build();
appDatabase.wordMainDao();
appDatabase.wordInfoDao();
appDatabase.wordExampleDao();
appDatabase.searchTimeDao();
}
Entity
@Entity(indices={@Index(value="word", unique=true)})
public class WordMain {
@PrimaryKey
@NonNull
private String wordid;
@NonNull
@ColumnInfo(name = “English_Word")
private String word;
private int times;
}
Wordid English_word Times
1 One 1
Data Access Object (DAO)
@Dao
public interface WordMainDao {
@Insert
void insert(WordMain wordMain);
@Delete
void delete(WordMain wordMain);
@Update
void update(WordMain wordMain);
@Query("SELECT * FROM WordMain WHERE word IN (:word)")
Single<List<WordMain>> loadByword(String word);
}
Insert,Update,Delete
@Insert(onConflict = OnConflictStrategy.IGNORE)
void insert(WordMain wordMain);
@Delete
void delete(WordMain... wordMain);
@Update
void update(List<WordMain> wordMain);
OnConflictStrategy
@Insert //ABORT
void insert(WordMain wordMain);
@Insert(onConflict = OnConflictStrategy.FAIL)
void insert(WordMain wordMain);
@Insert(onConflict = OnConflictStrategy.IGNORE)
void insert(WordMain wordMain);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(WordMain wordMain);
@Insert(onConflict = OnConflictStrategy.ROLLBACK)
void insert(WordMain wordMain);
Query
@Query("SELECT * FROM WordMain WHERE word IN (:word)")
List<WordMain> loadByword(String word);
@Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid
= s.wordid group by w.wordid order by s.searchtime desc")
List<WordMain> loadAll();
@Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid
= s.wordid WHERE s.searchtime BETWEEN :from AND :to group by
w.wordid order by s.searchtime desc")
List<WordMain> findWordMainBetweenDates(Date from, Date to);
RxJava
@Query("SELECT * FROM WordMain WHERE word IN (:word)")
Flowable<List<WordMain>> loadByword(String word);
@Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid
= s.wordid group by w.wordid order by s.searchtime desc")
Maybe<List<WordMain>> loadAll();
@Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid
= s.wordid WHERE s.searchtime BETWEEN :from AND :to group by
w.wordid order by s.searchtime desc")
Single<List<WordMain>> findWordMainBetweenDates(Date from, Date to);
TypeConverter
public class DateConverters {
@TypeConverter
public static Date fromTimestamp(Long value) {
return value == null ? null : new Date(value);
}
@TypeConverter
public static Long dateToTimestamp(Date date) {
return date == null ? null : date.getTime();
}
}
@Database(entities = {WordMain.class}, version = 1)
@TypeConverters({DateConverters.class})
public abstract class AppDatabase extends RoomDatabase {
……
}
Relation
單字 中英⽂文解釋 例例句句
Relation
@Entity(foreignKeys = @ForeignKey(entity = WordInfo.class,
parentColumns = "wordinfoid",
childColumns = "wordinfoid"),
indices={@Index(value="wordinfoid")})
public class WordExample {
…..
}
public class WordTotalInfo {
@Embedded
WordInfo wordInfo;
@Relation(parentColumn = "wordinfoid",
entityColumn = "wordinfoid", entity = WordExample.class)
List<WordExample> wordExamples;
…..
}
@Dao
public interface WordInfoDao {
@Query("SELECT * FROM WordInfo WHERE wordid IN (:wordid)")
Single<List<WordTotalInfo>> loadAllByIds(String wordid);
….
}
Testing
Testing
public class WordInfoDaoTest {
AppDatabase db;
@Before
public void setUp() throws Exception {
db = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext()
,AppDatabase.class).build();
}
@After
public void tearDown() throws Exception {
db.close();
}
}
@Test
public void OnConflictStrategy_ROLLBACK() {
try {
db.wordMainDao().insert(new WordMain("PrimaryKey3", "test", 123));
db.beginTransaction();
db.runInTransaction(new Runnable() {
@Override
public void run() {
List<WordMain> wordMains = new ArrayList<>();
wordMains.add(new WordMain("PrimaryKey2", "test1", 124));
wordMains.add(new WordMain("PrimaryKey3", "test7", 125));
db.wordMainDao().insert(wordMains);
db.setTransactionSuccessful();
}
});
} catch (Exception e) {
System.out.print(e.toString());
}
db.wordMainDao().all().subscribe(new SingleObserver<List<WordMain>>() {
@Override
public void onSubscribe(Disposable d) {}
@Override
public void onSuccess(List<WordMain> wordMains) {
Assert.assertThat(wordMains.size(), is(1));
Assert.assertThat(wordMains.get(0).getWordid(), is("PrimaryKey3"));
Assert.assertThat(wordMains.get(0).getWord(), is("test"));
Assert.assertThat(wordMains.get(0).getTimes(), is(123));
}
@Override
public void onError(Throwable e) {
System.out.print(e.toString());
}
});
}
@Test
public void wordTotalInfoQuery() {
wordMain = new WordMain("wordid3", "test", 123);
wordInfo = new WordInfo("wordinfoid2", "wordid3", "4", "5", "6");
wordExample = new WordExample("7", "wordinfoid2", "9", "10");
db.wordMainDao().insert(wordMain);
db.wordInfoDao().insert(wordInfo);
db.wordExampleDao().insert(wordExample);
Single<List<WordTotalInfo>> s = db.wordInfoDao().loadAllByIds("3");
s.subscribe(new Consumer<List<WordTotalInfo>>() {
@Override
public void accept(List<WordTotalInfo> wordTotalInfos) throws
Exception {
WordTotalInfo wordTotalInfo = wordTotalInfos.get(0);
WordInfo wordInfo = wordTotalInfo.getWordInfo();
WordExample wordExample = wordTotalInfo.getWordExamples().get(0);
Assert.assertThat(wordInfo.getWordinfoid(), is("wordinfoid2"));
Assert.assertThat(wordInfo.getWordid(), is("wordid3"));
Assert.assertThat(wordInfo.getChinesemean(), is("4"));
Assert.assertThat(wordInfo.getEnglishmean(), is("5"));
Assert.assertThat(wordInfo.getType(), is("6"));
Assert.assertThat(wordExample.getExampleid(), is("7"));
Assert.assertThat(wordExample.getWordinfoid(), is("wordinfoid2"));
Assert.assertThat(wordExample.getExample(), is("9"));
Assert.assertThat(wordExample.getExampletranslate(), is("10"));
}
});
}
Q&A

More Related Content

What's hot

Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24  tricky stuff in java grammar and javacJug trojmiasto 2014.04.24  tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javacAnna Brzezińska
 
Optimizing Tcl Bytecode
Optimizing Tcl BytecodeOptimizing Tcl Bytecode
Optimizing Tcl BytecodeDonal Fellows
 
TclOO: Past Present Future
TclOO: Past Present FutureTclOO: Past Present Future
TclOO: Past Present FutureDonal Fellows
 
Making an Object System with Tcl 8.5
Making an Object System with Tcl 8.5Making an Object System with Tcl 8.5
Making an Object System with Tcl 8.5Donal Fellows
 
Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkRefactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkCodeOps Technologies LLP
 
Cs267 hadoop programming
Cs267 hadoop programmingCs267 hadoop programming
Cs267 hadoop programmingKuldeep Dhole
 
Effective testing for spark programs scala bay preview (pre-strata ny 2015)
Effective testing for spark programs scala bay preview (pre-strata ny 2015)Effective testing for spark programs scala bay preview (pre-strata ny 2015)
Effective testing for spark programs scala bay preview (pre-strata ny 2015)Holden Karau
 
Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Holden Karau
 
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak?
Andrzej Ludwikowski -  Event Sourcing - co może pójść nie tak?Andrzej Ludwikowski -  Event Sourcing - co może pójść nie tak?
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak?SegFaultConf
 
RxJava from the trenches
RxJava from the trenchesRxJava from the trenches
RxJava from the trenchesPeter Hendriks
 
SH 1 - SES 7 - Change-Streams-Tel-Aviv.pptx
SH 1 - SES 7 - Change-Streams-Tel-Aviv.pptxSH 1 - SES 7 - Change-Streams-Tel-Aviv.pptx
SH 1 - SES 7 - Change-Streams-Tel-Aviv.pptxMongoDB
 
Scalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of codeScalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of codeKonrad Malawski
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 featuresindia_mani
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기Arawn Park
 

What's hot (20)

Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24  tricky stuff in java grammar and javacJug trojmiasto 2014.04.24  tricky stuff in java grammar and javac
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
 
Optimizing Tcl Bytecode
Optimizing Tcl BytecodeOptimizing Tcl Bytecode
Optimizing Tcl Bytecode
 
TclOO: Past Present Future
TclOO: Past Present FutureTclOO: Past Present Future
TclOO: Past Present Future
 
Making an Object System with Tcl 8.5
Making an Object System with Tcl 8.5Making an Object System with Tcl 8.5
Making an Object System with Tcl 8.5
 
Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkRefactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech Talk
 
Cs267 hadoop programming
Cs267 hadoop programmingCs267 hadoop programming
Cs267 hadoop programming
 
Effective testing for spark programs scala bay preview (pre-strata ny 2015)
Effective testing for spark programs scala bay preview (pre-strata ny 2015)Effective testing for spark programs scala bay preview (pre-strata ny 2015)
Effective testing for spark programs scala bay preview (pre-strata ny 2015)
 
Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016Beyond parallelize and collect - Spark Summit East 2016
Beyond parallelize and collect - Spark Summit East 2016
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak?
Andrzej Ludwikowski -  Event Sourcing - co może pójść nie tak?Andrzej Ludwikowski -  Event Sourcing - co może pójść nie tak?
Andrzej Ludwikowski - Event Sourcing - co może pójść nie tak?
 
Mongo db
Mongo dbMongo db
Mongo db
 
RxJava from the trenches
RxJava from the trenchesRxJava from the trenches
RxJava from the trenches
 
SH 1 - SES 7 - Change-Streams-Tel-Aviv.pptx
SH 1 - SES 7 - Change-Streams-Tel-Aviv.pptxSH 1 - SES 7 - Change-Streams-Tel-Aviv.pptx
SH 1 - SES 7 - Change-Streams-Tel-Aviv.pptx
 
Scalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of codeScalding - Hadoop Word Count in LESS than 70 lines of code
Scalding - Hadoop Word Count in LESS than 70 lines of code
 
Clojure: a LISP for the JVM
Clojure: a LISP for the JVMClojure: a LISP for the JVM
Clojure: a LISP for the JVM
 
Scalding for Hadoop
Scalding for HadoopScalding for Hadoop
Scalding for Hadoop
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 

Similar to Room with testing and rxjava

Annotation processing and code gen
Annotation processing and code genAnnotation processing and code gen
Annotation processing and code genkoji lin
 
Finding the right stuff, an intro to Elasticsearch (at Rug::B)
Finding the right stuff, an intro to Elasticsearch (at Rug::B) Finding the right stuff, an intro to Elasticsearch (at Rug::B)
Finding the right stuff, an intro to Elasticsearch (at Rug::B) Michael Reinsch
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
 
Data Types/Structures in DivConq
Data Types/Structures in DivConqData Types/Structures in DivConq
Data Types/Structures in DivConqeTimeline, LLC
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React NativeSoftware Guru
 
NET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxNET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxpetabridge
 
Применение паттерна Page Object для автоматизации веб сервисов - новый взгляд
Применение паттерна Page Object для автоматизации веб сервисов - новый взглядПрименение паттерна Page Object для автоматизации веб сервисов - новый взгляд
Применение паттерна Page Object для автоматизации веб сервисов - новый взглядCOMAQA.BY
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghStuart Roebuck
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaMartijn Blankestijn
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackGaryCoady
 
Android dev toolbox
Android dev toolboxAndroid dev toolbox
Android dev toolboxShem Magnezi
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012Timo Westkämper
 
Building a GraphQL API in PHP
Building a GraphQL API in PHPBuilding a GraphQL API in PHP
Building a GraphQL API in PHPAndrew Rota
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and MonoidsHugo Gävert
 
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Michel Schudel
 
Android Jetpack: Room persistence library
Android Jetpack: Room persistence libraryAndroid Jetpack: Room persistence library
Android Jetpack: Room persistence libraryThao Huynh Quang
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 

Similar to Room with testing and rxjava (20)

Annotation processing and code gen
Annotation processing and code genAnnotation processing and code gen
Annotation processing and code gen
 
Finding the right stuff, an intro to Elasticsearch (at Rug::B)
Finding the right stuff, an intro to Elasticsearch (at Rug::B) Finding the right stuff, an intro to Elasticsearch (at Rug::B)
Finding the right stuff, an intro to Elasticsearch (at Rug::B)
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Data Types/Structures in DivConq
Data Types/Structures in DivConqData Types/Structures in DivConq
Data Types/Structures in DivConq
 
Mobile Day - React Native
Mobile Day - React NativeMobile Day - React Native
Mobile Day - React Native
 
NET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptxNET Systems Programming Learned the Hard Way.pptx
NET Systems Programming Learned the Hard Way.pptx
 
Применение паттерна Page Object для автоматизации веб сервисов - новый взгляд
Применение паттерна Page Object для автоматизации веб сервисов - новый взглядПрименение паттерна Page Object для автоматизации веб сервисов - новый взгляд
Применение паттерна Page Object для автоматизации веб сервисов - новый взгляд
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by Ordina
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
Android dev toolbox
Android dev toolboxAndroid dev toolbox
Android dev toolbox
 
Querydsl fin jug - june 2012
Querydsl   fin jug - june 2012Querydsl   fin jug - june 2012
Querydsl fin jug - june 2012
 
Building a GraphQL API in PHP
Building a GraphQL API in PHPBuilding a GraphQL API in PHP
Building a GraphQL API in PHP
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
 
React native
React nativeReact native
React native
 
Android Sample Project By Wael Almadhoun
Android Sample Project By Wael AlmadhounAndroid Sample Project By Wael Almadhoun
Android Sample Project By Wael Almadhoun
 
Android Jetpack: Room persistence library
Android Jetpack: Room persistence libraryAndroid Jetpack: Room persistence library
Android Jetpack: Room persistence library
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 

Recently uploaded

Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and usesDevarapalliHaritha
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 

Recently uploaded (20)

young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
power system scada applications and uses
power system scada applications and usespower system scada applications and uses
power system scada applications and uses
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 

Room with testing and rxjava

  • 1. Room with Testing and Rxjava 報告⼈人:Vincent
  • 4. Gradle implementation “android.arch.persistence.room:runtime:$room_version” // use kapt for Kotlin annotationProcessor “android.arch.persistence.room:compiler:$room_version" // optional - RxJava support for Room implementation "android.arch.persistence.room:rxjava2:$room_version"
  • 6. RoomDatabase @Database(entities = {WordMain.class, WordInfo.class, WordExample.class, SearchTime.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { public abstract WordMainDao wordMainDao(); public abstract WordInfoDao wordInfoDao(); public abstract WordExampleDao wordExampleDao(); public abstract SearchTimeDao searchTimeDao(); } class AppDbHepler{ AppDatabase appDatabase = Room.databaseBuilder(context, AppDatabase.class, dbName).build(); appDatabase.wordMainDao(); appDatabase.wordInfoDao(); appDatabase.wordExampleDao(); appDatabase.searchTimeDao(); }
  • 7. Entity @Entity(indices={@Index(value="word", unique=true)}) public class WordMain { @PrimaryKey @NonNull private String wordid; @NonNull @ColumnInfo(name = “English_Word") private String word; private int times; } Wordid English_word Times 1 One 1
  • 8. Data Access Object (DAO) @Dao public interface WordMainDao { @Insert void insert(WordMain wordMain); @Delete void delete(WordMain wordMain); @Update void update(WordMain wordMain); @Query("SELECT * FROM WordMain WHERE word IN (:word)") Single<List<WordMain>> loadByword(String word); }
  • 9. Insert,Update,Delete @Insert(onConflict = OnConflictStrategy.IGNORE) void insert(WordMain wordMain); @Delete void delete(WordMain... wordMain); @Update void update(List<WordMain> wordMain);
  • 10. OnConflictStrategy @Insert //ABORT void insert(WordMain wordMain); @Insert(onConflict = OnConflictStrategy.FAIL) void insert(WordMain wordMain); @Insert(onConflict = OnConflictStrategy.IGNORE) void insert(WordMain wordMain); @Insert(onConflict = OnConflictStrategy.REPLACE) void insert(WordMain wordMain); @Insert(onConflict = OnConflictStrategy.ROLLBACK) void insert(WordMain wordMain);
  • 11. Query @Query("SELECT * FROM WordMain WHERE word IN (:word)") List<WordMain> loadByword(String word); @Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid = s.wordid group by w.wordid order by s.searchtime desc") List<WordMain> loadAll(); @Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid = s.wordid WHERE s.searchtime BETWEEN :from AND :to group by w.wordid order by s.searchtime desc") List<WordMain> findWordMainBetweenDates(Date from, Date to);
  • 12. RxJava @Query("SELECT * FROM WordMain WHERE word IN (:word)") Flowable<List<WordMain>> loadByword(String word); @Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid = s.wordid group by w.wordid order by s.searchtime desc") Maybe<List<WordMain>> loadAll(); @Query("SELECT * FROM WordMain w INNER JOIN SearchTime s ON w.wordid = s.wordid WHERE s.searchtime BETWEEN :from AND :to group by w.wordid order by s.searchtime desc") Single<List<WordMain>> findWordMainBetweenDates(Date from, Date to);
  • 13. TypeConverter public class DateConverters { @TypeConverter public static Date fromTimestamp(Long value) { return value == null ? null : new Date(value); } @TypeConverter public static Long dateToTimestamp(Date date) { return date == null ? null : date.getTime(); } } @Database(entities = {WordMain.class}, version = 1) @TypeConverters({DateConverters.class}) public abstract class AppDatabase extends RoomDatabase { …… }
  • 15. Relation @Entity(foreignKeys = @ForeignKey(entity = WordInfo.class, parentColumns = "wordinfoid", childColumns = "wordinfoid"), indices={@Index(value="wordinfoid")}) public class WordExample { ….. } public class WordTotalInfo { @Embedded WordInfo wordInfo; @Relation(parentColumn = "wordinfoid", entityColumn = "wordinfoid", entity = WordExample.class) List<WordExample> wordExamples; ….. } @Dao public interface WordInfoDao { @Query("SELECT * FROM WordInfo WHERE wordid IN (:wordid)") Single<List<WordTotalInfo>> loadAllByIds(String wordid); …. }
  • 17. Testing public class WordInfoDaoTest { AppDatabase db; @Before public void setUp() throws Exception { db = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext() ,AppDatabase.class).build(); } @After public void tearDown() throws Exception { db.close(); } }
  • 18. @Test public void OnConflictStrategy_ROLLBACK() { try { db.wordMainDao().insert(new WordMain("PrimaryKey3", "test", 123)); db.beginTransaction(); db.runInTransaction(new Runnable() { @Override public void run() { List<WordMain> wordMains = new ArrayList<>(); wordMains.add(new WordMain("PrimaryKey2", "test1", 124)); wordMains.add(new WordMain("PrimaryKey3", "test7", 125)); db.wordMainDao().insert(wordMains); db.setTransactionSuccessful(); } }); } catch (Exception e) { System.out.print(e.toString()); } db.wordMainDao().all().subscribe(new SingleObserver<List<WordMain>>() { @Override public void onSubscribe(Disposable d) {} @Override public void onSuccess(List<WordMain> wordMains) { Assert.assertThat(wordMains.size(), is(1)); Assert.assertThat(wordMains.get(0).getWordid(), is("PrimaryKey3")); Assert.assertThat(wordMains.get(0).getWord(), is("test")); Assert.assertThat(wordMains.get(0).getTimes(), is(123)); } @Override public void onError(Throwable e) { System.out.print(e.toString()); } }); }
  • 19. @Test public void wordTotalInfoQuery() { wordMain = new WordMain("wordid3", "test", 123); wordInfo = new WordInfo("wordinfoid2", "wordid3", "4", "5", "6"); wordExample = new WordExample("7", "wordinfoid2", "9", "10"); db.wordMainDao().insert(wordMain); db.wordInfoDao().insert(wordInfo); db.wordExampleDao().insert(wordExample); Single<List<WordTotalInfo>> s = db.wordInfoDao().loadAllByIds("3"); s.subscribe(new Consumer<List<WordTotalInfo>>() { @Override public void accept(List<WordTotalInfo> wordTotalInfos) throws Exception { WordTotalInfo wordTotalInfo = wordTotalInfos.get(0); WordInfo wordInfo = wordTotalInfo.getWordInfo(); WordExample wordExample = wordTotalInfo.getWordExamples().get(0); Assert.assertThat(wordInfo.getWordinfoid(), is("wordinfoid2")); Assert.assertThat(wordInfo.getWordid(), is("wordid3")); Assert.assertThat(wordInfo.getChinesemean(), is("4")); Assert.assertThat(wordInfo.getEnglishmean(), is("5")); Assert.assertThat(wordInfo.getType(), is("6")); Assert.assertThat(wordExample.getExampleid(), is("7")); Assert.assertThat(wordExample.getWordinfoid(), is("wordinfoid2")); Assert.assertThat(wordExample.getExample(), is("9")); Assert.assertThat(wordExample.getExampletranslate(), is("10")); } }); }
  • 20. Q&A