Popular New Releases in Android Architecture
flexbox-layout
3.0.0
ReactiveLiveData
1.0.1
coin-collection-android-US
Release v3.4.0
Popular Libraries in Android Architecture
by google kotlin
16747 Apache-2.0
Flexbox for Android
by android kotlin
234 Apache-2.0
Multiple samples showing the best practices in permissions on Android.
by musichin kotlin
81 MIT
Transformation functions for LiveData
by Hariofspades java
76
For the blog, Dagger 2 for Android Beginners
by glung kotlin
59 MIT
An example of the ELM architecture on Android using Kotlin with Anko
by stfalcon-studio java
57
Sample project for the https://stfalcon.com/en/blog/post/faster-android-apps-with-databinding blogpost
by yigit java
49
repo for the android live code event, Feb 5, 2014
by Karumi kotlin
48
This repository is to show how to create an Play Framework project using Kotlin
by inutano javascript
41 MIT
ChIP-Atlas: Browse and analyze all public ChIP/DNase-seq data on your browser
Trending New libraries in Android Architecture
by KimReady kotlin
4
A collection of android-samples posted on a blog.
by gek169 c
2
Main code repository for small free software projects done by or used by the C Chads.
by personal-security java
0 GPL-3.0
Simple android vpn app
Top Authors in Android Architecture
1
1 Libraries
2
2
1 Libraries
2
3
1 Libraries
27
4
1 Libraries
4
5
1 Libraries
2
6
1 Libraries
48
7
1 Libraries
7
8
1 Libraries
3
9
1 Libraries
4
10
1 Libraries
4
1
1 Libraries
2
2
1 Libraries
2
3
1 Libraries
27
4
1 Libraries
4
5
1 Libraries
2
6
1 Libraries
48
7
1 Libraries
7
8
1 Libraries
3
9
1 Libraries
4
10
1 Libraries
4
Trending Kits in Android Architecture
No Trending Kits are available at this moment for Android Architecture
Trending Discussions on Android Architecture
How are Android activities handled with Jetpack Compose and Compose Navigation?
SetTheme to an activity with PreferencesDataStore
What is the best practice for starting a new thread when using Firebase Realtime Database?
Get second last value in each row of dataframe, R
Cannot create an instance of ViewModel Class
Android MVVM: how to avoid multiple livedata triggers when data from network did not change
Can I add Observer inside Observer? I actually tried but inner observers not working properly. Sometimes one of them work, sometimes no one work
Why I am facing threading issues despite using room database TransactionExecutor?
Where to Save ViewModel State in Android's MVVM?
Android (Kotlin): Type mismatch in Observer
QUESTION
How are Android activities handled with Jetpack Compose and Compose Navigation?
Asked 2021-Dec-15 at 03:26I'm currently studying Jetpack Compose in an attempt to build a feature-rich application using modern Android architecture components. Traditionally, each screen (or navigation unit) in my application would be either an activity or a fragment, each with its own lifecycle bindings, but with Jetpack Compose and the Compose Navigation library, I would do something like this:
MainActivity.kt
:
1class MainActivity : ComponentActivity() {
2 override fun onCreate(savedInstanceState: Bundle?) {
3 super.onCreate(savedInstanceState)
4 setContent {
5 val navController = rememberNavController()
6
7 NavHost(navController = navController, startDestination = "main") {
8 composable("main") { MainScreen(navController) }
9 // More composable calls
10 }
11 }
12 }
13}
14
15
Where MainScreen
is just a composable. My questions are:
- What is the equivalent here of a "lifecycle" for this composable? Say I want to perform some action when the screen is loaded, when it is destroyed etc. This is perhaps more relevant to the case where I have more screens and navigation between them
- Is there some way to integrate between Compose and standard activities? That is, define activities for screens as you would, with each activity being a
ComponentActivity
and defining its own composable layout? Is this discouraged for some reason?
ANSWER
Answered 2021-Aug-29 at 04:50The Compose application is designed to be used in a single-activity architecture with no fragments.
You can still have multiple activities or fragments and use setContent
in each of them, but in this case the transfer of data between activities falls on your shoulders. Use this approach if you're adding new Compose screens to an existing application built the old way.
But with Compose, it's much easier to do all the navigation within a single activity using Compose Navigation. Much less code, better performance due to no unnecessary code layers, easy to transfer data, etc.
To work with the view lifecycle, check out compose side-effects:
LaunchedEffect
can be used to execute an action when the view appears. It also runs on a coroutine context that is bound to the current composable: you can easily run suspend functions, and when the view disappears from view hierarchy - the coroutine will be canceled.DisposableEffect
can be used to subscribe to/unsubscribe from callbacks.
When you rotate the screen, all effects will restart no matter which key you passed.
1class MainActivity : ComponentActivity() {
2 override fun onCreate(savedInstanceState: Bundle?) {
3 super.onCreate(savedInstanceState)
4 setContent {
5 val navController = rememberNavController()
6
7 NavHost(navController = navController, startDestination = "main") {
8 composable("main") { MainScreen(navController) }
9 // More composable calls
10 }
11 }
12 }
13}
14
15@Composable
16fun MainScreen(navController: NavController) {
17 LaunchedEffect(Unit) {
18 println("LaunchedEffect: entered main")
19 var i = 0
20 // Just an example of coroutines usage
21 // don't use this way to track screen disappearance
22 // DisposableEffect is better for this
23 try {
24 while (true) {
25 delay(1000)
26 println("LaunchedEffect: ${i++} sec passed")
27 }
28 } catch (cancel: CancellationException) {
29 println("LaunchedEffect: job cancelled")
30 }
31 }
32 DisposableEffect(Unit) {
33 println("DisposableEffect: entered main")
34 onDispose {
35 println("DisposableEffect: exited main")
36 }
37 }
38}
39
Also note that in both cases, and in many other cases in compose, you pass key
to these functions. This helps compose understand when the value should be recomputed. In my example it is Unit
, which means that it won't change until the view is gone. But if you create a remember
value, use another dynamic value from the view model, or pass another argument to composable, you can pass it as a key
, this will cancel the current LaunchedEffect
job and call onDispose
for DisposableEffect
, and your job will be restarted with the updated key
value. You can pass as many keys as you want.
Read more about the state in Compose in documentation.
QUESTION
SetTheme to an activity with PreferencesDataStore
Asked 2021-Oct-12 at 10:27I have switched my app from using SharedPreferences
to PreferencesDataStore
. I have also implemented a dark mode and several themes inside my app. For theming, I basically rely in each activity on this code:
1 val themePreferences = getSharedPreferences("THEME_PREFERENCES", MODE_PRIVATE)
2 val settingsPreferences = getSharedPreferences("SETTINGS_PREFERENCES", MODE_PRIVATE)
3 darkMode = settingsPreferences.getBoolean("darkMode", false)
4
5 setTheme(when (darkMode) {
6 true -> themePreferences.getInt("themeDark", R.style.AppThemeDark)
7 false -> themePreferences.getInt("themeLight", R.style.AppThemeLight)
8 })
9
The selected theme gets stored as an Integer, each once for the light mode as well as the dark mode. Now, I also want to adopt this section of my code. I get my darkMode boolean from my dataStore repository like this:
1 val themePreferences = getSharedPreferences("THEME_PREFERENCES", MODE_PRIVATE)
2 val settingsPreferences = getSharedPreferences("SETTINGS_PREFERENCES", MODE_PRIVATE)
3 darkMode = settingsPreferences.getBoolean("darkMode", false)
4
5 setTheme(when (darkMode) {
6 true -> themePreferences.getInt("themeDark", R.style.AppThemeDark)
7 false -> themePreferences.getInt("themeLight", R.style.AppThemeLight)
8 })
9viewModel.storedDarkMode.observe(this) { darkMode = it }
10
If I work inside the observe(this) { ... } of the LiveData object it won't work.
Now, how can I change my code snippet shown above to PreferencesDataStore
? Or is it actually better e.g. to make a separate class in order to observe the values from there? If yes, how could something like that look like? Or do you know some good example code following Android Architecture including custom themes with a dark mode where I can look at?
I am still learning a lot, any help for better understanding this is much appreciated!
Best regards, Markus
Edit:
1 val themePreferences = getSharedPreferences("THEME_PREFERENCES", MODE_PRIVATE)
2 val settingsPreferences = getSharedPreferences("SETTINGS_PREFERENCES", MODE_PRIVATE)
3 darkMode = settingsPreferences.getBoolean("darkMode", false)
4
5 setTheme(when (darkMode) {
6 true -> themePreferences.getInt("themeDark", R.style.AppThemeDark)
7 false -> themePreferences.getInt("themeLight", R.style.AppThemeLight)
8 })
9viewModel.storedDarkMode.observe(this) { darkMode = it }
10runBlocking {
11 val darkMode = viewModel.darkModeFlow.first()
12 setTheme(when (darkMode) {
13 true -> viewModel.themeDarkFlow.first()
14 false -> viewModel.themeLightFlow.first()
15 })
16 }
17
ANSWER
Answered 2021-Sep-30 at 05:14I don't know if it is best practice or not, but I use runBlocking
to get theme data from dataStore
. It is always recommended that, we should never use runBlocking
in our production code.
1 val themePreferences = getSharedPreferences("THEME_PREFERENCES", MODE_PRIVATE)
2 val settingsPreferences = getSharedPreferences("SETTINGS_PREFERENCES", MODE_PRIVATE)
3 darkMode = settingsPreferences.getBoolean("darkMode", false)
4
5 setTheme(when (darkMode) {
6 true -> themePreferences.getInt("themeDark", R.style.AppThemeDark)
7 false -> themePreferences.getInt("themeLight", R.style.AppThemeLight)
8 })
9viewModel.storedDarkMode.observe(this) { darkMode = it }
10runBlocking {
11 val darkMode = viewModel.darkModeFlow.first()
12 setTheme(when (darkMode) {
13 true -> viewModel.themeDarkFlow.first()
14 false -> viewModel.themeLightFlow.first()
15 })
16 }
17val preferences = runBlocking {
18 mainActivityViewModel.preferencesFlow.first()
19}
20setAppTheme(preferences.currentTheme)
21binding = ActivityMainBinding.inflate(layoutInflater)
22
In setAppTheme
method
1 val themePreferences = getSharedPreferences("THEME_PREFERENCES", MODE_PRIVATE)
2 val settingsPreferences = getSharedPreferences("SETTINGS_PREFERENCES", MODE_PRIVATE)
3 darkMode = settingsPreferences.getBoolean("darkMode", false)
4
5 setTheme(when (darkMode) {
6 true -> themePreferences.getInt("themeDark", R.style.AppThemeDark)
7 false -> themePreferences.getInt("themeLight", R.style.AppThemeLight)
8 })
9viewModel.storedDarkMode.observe(this) { darkMode = it }
10runBlocking {
11 val darkMode = viewModel.darkModeFlow.first()
12 setTheme(when (darkMode) {
13 true -> viewModel.themeDarkFlow.first()
14 false -> viewModel.themeLightFlow.first()
15 })
16 }
17val preferences = runBlocking {
18 mainActivityViewModel.preferencesFlow.first()
19}
20setAppTheme(preferences.currentTheme)
21binding = ActivityMainBinding.inflate(layoutInflater)
22private fun setAppTheme(theme: Boolean) {
23 mainActivityViewModel.darkMode = theme
24 //set your theme here
25 }
26
Now observe preferencesFlow
for any change in theme value, and if the theme is changed then recreate()
1 val themePreferences = getSharedPreferences("THEME_PREFERENCES", MODE_PRIVATE)
2 val settingsPreferences = getSharedPreferences("SETTINGS_PREFERENCES", MODE_PRIVATE)
3 darkMode = settingsPreferences.getBoolean("darkMode", false)
4
5 setTheme(when (darkMode) {
6 true -> themePreferences.getInt("themeDark", R.style.AppThemeDark)
7 false -> themePreferences.getInt("themeLight", R.style.AppThemeLight)
8 })
9viewModel.storedDarkMode.observe(this) { darkMode = it }
10runBlocking {
11 val darkMode = viewModel.darkModeFlow.first()
12 setTheme(when (darkMode) {
13 true -> viewModel.themeDarkFlow.first()
14 false -> viewModel.themeLightFlow.first()
15 })
16 }
17val preferences = runBlocking {
18 mainActivityViewModel.preferencesFlow.first()
19}
20setAppTheme(preferences.currentTheme)
21binding = ActivityMainBinding.inflate(layoutInflater)
22private fun setAppTheme(theme: Boolean) {
23 mainActivityViewModel.darkMode = theme
24 //set your theme here
25 }
26mainActivityViewModel.preferencesLiveData.observe(this) {
27 if (it.currentTheme != mainActivityViewModel.selectedTheme) {
28 recreate()
29 }
30 }
31
As we can't load our UI, without getting the theme. It seemed right to use runBlocking
.
QUESTION
What is the best practice for starting a new thread when using Firebase Realtime Database?
Asked 2021-Sep-05 at 23:29I'm following along this blog for using Android Architecture Components with Firebase Realtime Database. Currently, I am at the part of the blog where I move the LiveData
callbacks to onChanged()
onto a different thread.
This is what I have (the Kotlin equivalent of the Java code from the blog):
1private val uid = Firebase.auth.currentUser!!.uid
2private val USERS_REF: DatabaseReference = FirebaseDatabase.getInstance().getReference("/users/$uid")
3private val liveData: FirebaseQueryLiveData = FirebaseQueryLiveData(USERS_REF)
4private val usersLiveData: MediatorLiveData<Users> = MediatorLiveData()
5
6fun UsersViewModel() {
7 usersLiveData.addSource(liveData, object : Observer<DataSnapshot> {
8 override fun onChanged(dataSnapshot: DataSnapshot?) {
9 if (dataSnapshot != null) {
10 Thread(Runnable() {
11 run() {
12 usersLiveData.postValue(dataSnapshot.getValue(Users::class.java))
13 }
14 }).start()
15 } else {
16 usersLiveData.value = null
17 }
18 }
19 })
20}
21
In the blog, it states that the way it has shown to start up a new thread is not considered the "best practice" for starting another thread in a production app. The suggestion is to use an Executor
with a pool of reusable threads for a job like this.
How do I modify the current Runnable Thread so that it uses an optimal practice for starting a new thread?
ANSWER
Answered 2021-Sep-05 at 23:28You don't need a new thread at all here. Just remove it.
postValue()
is asynchronous and doesn't block anything. You can call it safely on the main thread. Any LiveData observers will get the value immediately after the database callback completes.
QUESTION
Get second last value in each row of dataframe, R
Asked 2021-May-14 at 14:45I am trying to get the second last value in each row of a data frame, meaning the first job a person has had. (Job1_latest is the most recent job and people had a different number of jobs in the past and I want to get the first one). I managed to get the last value per row with the code below:
first_job <- function(x) tail(x[!is.na(x)], 1)
first_job <- apply(data, 1, first_job)
1structure(list(Index = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
213, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
329, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
445, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59),
5 FromJob = c("Senior Machine Learning Engineer", "Senior Machine Learning Engineer",
6 "Senior Machine Learning Engineer", "Senior Machine Learning Engineer",
7 "Senior Machine Learning Engineer", "Python Data Engineer (m/w/d)",
8 "Python Data Engineer (m/w/d)", "Python Data Engineer (m/w/d)",
9 "Lead Backend Developer (f/m/d)", "Lead Backend Developer (f/m/d)",
10 "Lead Backend Developer (f/m/d)", "Lead Backend Developer (f/m/d)",
11 "Python Data Engineer (m/w/d)", "Python Data Engineer (m/w/d)",
12 "Lead Developer", "Lead Developer", "Lead Developer", "Lead Developer",
13 "Lead Developer", "Lead Developer", "Team Lead Software Development",
14 "(Senior) Frontend Engineer", "(Senior) Frontend Engineer",
15 "(Senior) Frontend Engineer", "(Senior) Frontend Engineer",
16 "(Senior) Frontend Engineer", "(Senior) Frontend Engineer",
17 "Data Scientist", "Data Scientist", "Senior Backend (Java) Engineer",
18 "Senior Backend (Java) Engineer", "Senior Backend (Java) Engineer",
19 "Lead Developer", "Mobile Software Engineer", "Mobile Software Engineer",
20 "Mobile Software Engineer", "Mobile Software Engineer", "Mobile Software Engineer",
21 "Mobile Software Engineer", "Mobile Software Engineer", "Mobile Software Engineer",
22 "Mobile Software Engineer", "Mobile Software Engineer", "Mobile Software Engineer",
23 "Mobile Software Engineer", "Lead UI/UX Designer", "Lead UI/UX Designer",
24 "Lead UI/UX Designer", "Lead UI/UX Designer", "Head of Software Development",
25 "Head of Software Development", "Head of Software Development",
26 "Head of Software Development", "Head of Software Development",
27 "Head of Software Development", "Head of Software Development",
28 "Head of Software Development", "Jnuior Fullstack Developer",
29 NA), Highest_education_achieved = c("PhD", "MSc Computer Science",
30 "MSc", "MBA", "MSc", "MSc", "MSc", "MSc Communication and Media Engineering",
31 "High School", "BSc Informatics", "BSc Software engineering",
32 NA, "MSc in Electronic Engineering", "MSc in Communication and Media Engineering",
33 "BSc in Computer Engineering", "BSc in Technology", "MSc in Computer Science",
34 "BSc in Automatic Control System", "Dipl. Wirtschaftsinformatik",
35 "MCs Computer Science", "Dipl. Ing. in Software Development - Economics",
36 "MSc in Computer Science", "BSc. in Information Technology",
37 "MSc in Big Data and Business Analyst", "MSc. in Computer Science",
38 "Dipl.", "BSc.", "MSc. in Scientific Computing and Biomechanics",
39 "MSc. in Computational Engineering", "MSc. in Information Technology",
40 "MSc. in Computer Science", "MSc. in Informatics", "BSc.",
41 "BSc.", "BSc.", "BSc.", "BSc.", "BSc.", "BSc.", "BSc.", "Highschool",
42 "BSc.", "BSc.", "Highschool", "BSc.", "MCs.", "BSc.", "BSc.",
43 "BSc.", "MCs.", "BSc.", "Dipl.", "BSc.", "BSc.", "BSc.",
44 "BSc.", "MSc.", "BSc.", NA), Skills = c("Machine Learning, Mathematical Modeling, Scientific Computing, Linux, python, numpy, scipy, scikit-learn, keras, pandas, javascript, react.js, AWS, Lambda, EMR, EC2, S3, Glue, CloudFormation, git, Image recognition, deep learning, Natural language processing, Big data integration, cloud migration, Azure, Fortran, OpenFOAM, mercurial",
45 "Java, AngularJS, frontend, backend, Azure, data collection, modelbuilding, evaluation, deployment, serving and computing online metrics, Apache Spark, AWS Sagemaker, Airflow, MLflow, MLOps",
46 "Biometrics, Machine Learning, Pattern Recognition, AI, scrum, matlab, C++, Azure, logistics",
47 "Databricks, Spark, Airflow, AWS Sagemaker, Other AWS Services, Docker, Microstrategy, Presto, Python, PL/SQL, JavaScript, Shell Scripting, BigQuery (Google), Hadoop, Exasol, Kafka",
48 "Spark, Tensorflow &TFX, Kubeflow, BigQuery, Apache Beam (Dataflow), Google Cloud Platform",
49 "PythonC++, C, OpenCV, OpenCL, MatLab, TensorFlow/PyTorch, Caffe/Keras, Scikit-learn, Pandas/NumPy, Seaborn/Matplotlib, NLTK/spaCy, Computer Vision, Machine Learning, NLP, Linear/LogisticRegression, Naive Bayes/PCA, SVM/K Means, RandomForest, CNN/LSTM/GRU, Reinforcement Learning",
50 "Microsoft SQL Server, Hadoop,SQL Server Management Studio, VisualStudio(DataTools), PyCharm, Sublime text 3, SSIS, python, C#, \nC++, Html/Css, Java,T-SQL, git",
51 "Keras, TensorFlow, scikit-learn, NLTK, OpenCV, NumPy, pandas,Python, Java, PHP, HTML, CSS, JavaScript, Angular, React, jQuery, Bootstrap, Flask, SQL, MongoDB, Git, Docker",
52 "ElasticSearch, OOP, NoSQL, SQL, Docker, Kibana, Git, Unittest, Openshift",
53 "PHP, Java Script, CSS, (X)HTML, MySQL., NodeJS", "JavaScript (Vue.js, React, jQuery), Node.js (Express), PHP (Yii, Laravel, Symfony), JAVA (Spring Boot), .NET C#, SQL(postregsql, mysql), Elastic, MongoDB, HTML + CSS, Sketch, InVision Studio",
54 NA, "Python, C++, HTML/CSS, Java, C#, T-SQL, Microsoft SQL Server, Hadoop, Pycharm, Sublimetext 3, SISS, Git,Liquid Planner,",
55 "Keras, TensorFlow, scikit-Learn, NLTK, openCV, NumPy, pandas, Python, Java, PHP, HTML, JavaScript,CSS, Angular, React, jQuery, Bootstrap, Flask, SQL, MonoDB, Git, Android, PhoneGap, Docker",
56 "Java, PL/SQL, HTML, JavaScript, PHP, Bash, AngularJs, ReactJs, Python, Weblogic, Jboss, Tomcat, Jetty, Apache, IIS, Unix, Windows, Oracle 8i, 9i, 10g, MySql, MariaDB, PostgrwSql, MS Sql Server, GIT, Mercury, Jira",
57 "JavaScript, AngularJs, Angular Next, jQuery, RequireJS, React, WebPack, Typescript, Node, PWA, Socket Programming, Kong,",
58 "GIT, SME, API's, iOS, UI, Mobile application, SVN, Epic, Apple, SAML,",
59 "Kotlin, Java, JavaScript, Typescript, Pytion ML, AI, Spring, NoSQL, SQL, Microservices, AWS, Azure, Angular9, React, Kafka, Jenkins, Cloud, Rancher, K8s, Cloud foundry, MSSQL, Elas, Tensorflow, Boot, Teras, Hibernite, RabbitMQ, JUnit, AWS SQS, Docker, C++, STL, XML, Linux, Bash,",
60 "Scrum, Code Reviews, JIRA, Mantis, Kanban, Trello, Java, Kotlin, Typescript, Groovy, JavaScript, Delphi, Openshift, Kubernetes, Docker, Azure, Open Telekom Cloud, CosmosDB, Heroku, REST, SOAP, XMPP, NATS, JMS, ActiveMQ, Gatling, Mocktesting, Mockito, EasyMock, Cucumber, Angular 8, React, GWT, JSF, JSP, Struts, Spring Boot, JEE, Hibernate, JPA, MongoDB, Oracle, Postgres, CosmosDB, MySQL, DB2, SQL-Tuning, Maven, Ant, Gradle, GIT, SVN, CVS, BIRT, JasperReports, MicroStrategy, Maven,",
61 "Kotlin, Java 11, Docker, AWS, GCP, Kubernetes,Neo-4j, Solr, Spring-boot, Postgres, Hibernate, Flyway, sendGrit, Gradl, rxJava, Freemaker, Grafana, Prometheus,Oauth 2, Spring-gateway, Microservices, AWS, Amazon EMR, DynamoDB, S3, Hive, hdfs, storm, kafka, reactive programming, spring-cloud, groovy, elasticsearch, hystrix, ribbon, eureka, API, java 8, grunt, bamboo, jenkins, JavaScript, Junit, jbpm, jmx, C++, j2ee, servlet,",
62 "Scrum, SAP, NetWeaver 7.40", "CSS. Html, Bootstrap, Php, MySQL, JavaScript, Wordpress, Typo 3, Google Analytics, Google Adwords, React, GatsbyJS, Nextjs, Flutter, Postgres, AWS, Docker, Google Cloud Platform,",
63 "Node JS, JavaScript, ES6, CSS, PHP, XML, JQuery, Lambda, Appsync, React, JS, HTML5, CSS3, Bootstrap, REST web services, Microservices, JSON, Elasticsearch, Java, React JS, AWS Server, MAMP, Maven, Laravel, Codeigniter, MySQL, Dynamo DB, SQLite, Oracle, MS SQL, MAC, UNIX, Windows, Git, AWS-EC2, S3, Cloud Formation, Cloudwatch, SNS, PhpStorm, WebSorm, Visual Studio Code, Eclipse, Netbeans, Android Studio",
64 "C, C++, Java, J2EE, Dotnet, Angular, React, JS, JavaScript, Query, CSS, HTML, Microsoft SQL Server, GIT, React JS with Redux, Vue JS, CSS3, Bootstrap, Media query, AEM, Jest test, Python, Tabeleau, AWS, Miro",
65 "JavaScript, ReactJs, TypeScript, Python, C++, HTML, ASP, C#",
66 "SPA, TypeScript, React Hooks, Jest, Lerna, React Query, Azure DevOps, Storybook, RxJx, Socket.io, OpenAPI, SCSS,",
67 "JavaScript, React JS, Flow, Redux, React SSR, urql graphql client, Java 11, HTML5, CSSS3, JavaScript (ES6+), TypeScript, jQuery, AJAX, webpack, NodeJS, PHP, Express, MongoDB, SASS, Heroku, Linux, Hetzner, Git, AngularJS,",
68 "Linux, Windows, MS Office, Libre office, Python, SQL, Bash, C/C++, MATLAB, NumPy, SciPy, pandas, SciKit-Learn, statsmodels, Keras, TensorFlow, Flask, Matplotlib, Seaborn, Tableau, ParaView, Tecplot, Inkscape, GIMP, PyCharm, jupyter, Eclipse, Visual Studio, Git, Docker, Poetry, Pytest, Unittest, Pylint, Pre-commit",
69 "Python, C/C++, SQL, MySQL, Numpy, Pandas, Scipy, Scikit-Learn, Keras, Tensorflow, Theano, PyTorch, Visual Studio, Pycharm, Jupyter Notebook, Vscode, PowerBi, MS Office, Sourcetree, Jira, Git, Linux, Mac, Windows",
70 "NPM, Webpack, Bower, Gruntjs, Gulp, JavaScript, Angular, CSS, Animation, Angular-animation, TypeScript, ReactJS, Node.js, Lombok, Vue.js, Visual Studio, HTML, Maven, Redux, Chart.js, Kotlin,",
71 "Java. Web Services, Design Patterns, Agile Methodologies, Spring Hibernate, JSF, JUnit, Maven Eclipse, SQL, XML, Linux, Websphere, Tomcat, jQuery, Ant, JDBC, Subversion, JavaScript, CSS, JPA, Git, Jenkins, REST, services, AJAX, Glassfish, Java Enterprise Edition, Apache, Lucene, Artifactory,",
72 "Java, HTML, Perl, Programming, SQL, JavaScript, CSS, Oracle, C++, Linux, CSS, PHP, C#, Ruby, C",
73 NA, "Jira, Git, Scrum, Agile, Retrofit, Picasso, Volley, RESTful, HTTP, JSON, Asyns-task, Dagger2, MVVM Architecture, API, SQLite, Pandas, NumPy,",
74 "Kotlin, MVVM Archtiecture, Firebase, Google-Services, Git, Retrofit, JSON, Material Design UI, Constrains Layout Animations, Jira, Figma, Zeplin, Agile, Scrum",
75 "C++, Java, MVC Design, AdMob, Google Maps API Keys, Retrofit, Gson, SQLite, Picasso, Google Vision, Play Services, SQL, iOS Develpment, JSON, C#, XML, Android",
76 "Server-Side, Client-Side, NOSQL, Agile Development, Machine Learning, Elastic Search, AWS, C#, OOP, Object Oriented, Programming, SQL, DB, RDBMS, Relational Database, CSS, Angular, AngularJs, JavaScript, TypeScript, JQuery, HTML, PHP, .NET, MVC.NET, DOT.NET, HADOOP, Java, Apache Hive, XML, JSON, AJAX,MySQL, Visual Studio, Bootstrap, XCode, Android, IOS,",
77 "Kotlin, Java, Rx, Dagger, Retrofit, Data Binding, Glide, Picasso, Leak Canary,Git, Flow, MVP, MVVM, Junit, Mockito, Espresso, Repository, Pattern, Singleton Pattern, CI/CD, Python, C/C++, C#, HTML, CSS, JavaScript, React, Spring Boot, Slack, XML, Android Arch Components, Material Design, Timber, ML, Kit,",
78 "Android SDK, Java, Kotlin, XML, Firebase, Android Studio, GIMP, Illustrator, PHP, API,",
79 "Android Development, Java, Firebase, Kotlin, SQLite, Android Studio, SDK Implementation, Mobile Application, Version Control, JSON, IMA SDK, Google AdSense, Jira, C#, Swift",
80 "Java, Android SDK, Java SE, GWT, AWT, SWT, JSP, JSTL, JSF, Hibernate, Struts, Kotlin, Swift, JavaScript, jQuery, Oracle, MySQL, SQLite, PHP, HTML, CSS, C#,GWT, Angular, Bootstrap, Junit, Selenium, Appium, JavaServer Faces, Zend, Eclipse, XCode, Unity, iOS, Firebase, Open Source, Atlassian, Apache, Microsoft, Adobe,",
81 "Android, Kotlin, Java, Dart, MVVM, UAT, CI/CD, UI/UX,",
82 "GoF Design Patterns, SOLID, MVVM, MVP, MVC, Android Development, AppoloGraphQL, Dagger2, RxJava, Jetpack Components, Kotlin, iOS, Swift, Autolayout, Python, JavaScript",
83 "Git, Youtrack, Trello, Jira, CI/CD, Gitlab, Teamcity, Kotlin, Java, Retrofit, Ktor, Android Architechture Compor Room, SQLDelight, RxJava2, Coroutines/Flow, MVP, MVVM, MVI, Python, Scrum, Waterfall",
84 "Java, Kotlin, XML, Android SDK, Retrofit, Okhttp, Dagger 2, Eventbus, Multithreating, Design Patterns, RX, Coroutines, Picasso, Glide, MVM, MVVM, MVP, Clean Architecture, Android Jetpack, Android Architecture Component, Espresso, Junit, Mockito, Cucumber, SQLite, Realm, Room, Firebase, Git",
85 "invison, Uxpin, Sketch, Figma, Slack Abstract, Adobe XD, Adobe InDesign, Illustrator, Adobe Photoshop, Adobe Muse, Rhinoceros, Animation Studio, MacOS, Microsoft Office, Material Design, Fluent Design, Swift, React, Angular, HTML, CSS, JS, GitHub",
86 "PHP, HTML, CSS, JavaScript, React, Python, CRO, Adobe XD, Sketch, InVision, Lingo App, TripleTex,",
87 "Figma, Sketch, Invision, Adobe XD, Adobe Creative Cloud, Craft Marvel,",
88 "Figma, Sketch, Photoshop, Illustrator, Adobe After Effects, Maya, Cinema 4D, JavaScript, HTML, CSS, React, Node, Next.js, TailwindCSS, Firebase, MongoDB,",
89 "Java, C#.NET, PHP, Python, JavaScript, HTML, CSS, XML, Datenbanken, SQL, Geodaten, CMS Systeme, Jira, Confluence, Linux, Webserver-Betrieb, Catching, Load Balancing, Monitoring CI Systeme, automatisiertes Testen, Deployment,",
90 "Software Engineering, DevOps, System Architecture, Agile Transformation, IT Security, Python, Java, CI, CD, Docker, iOS, C++, C#, Golang, Ruby, Node JS, PostgrSQL, MySQL, RethinkDB, Cassandra, Consul",
91 "Cobol, Delta, ISAM, Java, JavaScript, CSS, Eclipse RCP, ANTLR, JPA, Maven, JPA/Hibernate, Lucene, HSQL, Oracle, Tomcat, Jetty, Axis, JBoss, JAX-WS, SOAP, WSDL, HBase, Jenkins, SNS, S3, SASS, Jira, Github, SEO/SM, Gitlab, Kotlin, Kafka,",
92 "AWS, Azure, Angular, MongoDB, Node.js, iOS,", "Java, RIM, COM Interfaces, Edifact, MT940, XSLT, XML, Tomcat, JMS, Arvo Workflowsystem, XSL-FO, Xalan, JSP, Servlets, JavaScript, Struts, EJB, JPA, Trinidad, Drools, XFire, Eclipse, Springframework, Dozer Framework,",
93 "Android, Java, Python, Rails, Ruby, SQL, Kotlin, Git, Redmine, MariaDB, Gitlab, Jira, Bitbucket, Mattermost, Docker, Jenkins CI,",
94 "Trello, Asana, Microsoft Office, Photoshop, Unity 3D,",
95 "Java, CMS, Scrum, C++, SOA, EDA, Cloud,", "SQL, Adobe, Python, SQL, ABAP, React + TypeScript, Node.js, CMS, REST API, Tensorflow + Pytorch, Flutter, AWS Deployment, SAP, Jira, AutoCAD",
96 NA), Job1_latest = c("Senior Engineer - Machine learning",
97 "Senior Machine Learning Engineer", "Application Developer Associate Manager",
98 "Senior Data & ML Engineer", "Senior Machine Learning Engineer",
99 "Software Developer", "Machine Learning Engineer", "Akademischer Mitarbeiter, Machine Learning and Analytics",
100 "Senior Backend Developer", "Senior Web Developer", "Software Architect / Development lead",
101 NA, "Data Analysing (Researcher)", "Software Engineer", "Sofware Developer",
102 "Senior Associate Experience Technology", "Senior Software Architect",
103 "Senior Software Developer / Tech Lead", "Fullstack Developer/ ProductOwner",
104 "Freelancing Software Developer", "Senior Software Developer / Teamlead",
105 "Fullstack JavaScript Developer", "Blowoutandgo Application Developer",
106 "Software Developer", "Software Engineer", "Senior Frontend Engineer and Lead Developer",
107 "Javascript Developer", "Data Scientist/ Python Developer",
108 "Research Assistant", "Fullstack Engineer", "Backend Developer",
109 "App-Backend Developer", "Senior Software Developer", "Android Developer",
110 "Android Software Engineer", "Senior Android Developer",
111 "Senior C# Developer", "Software Developer", "Applications Developer",
112 "Senior Android Developer", "Android Developer", "Senior Android Engineer",
113 "Mobile Engineer", "Senior Android Developer", "Software Engineer",
114 "Senior UX/UI Designer", "User Experience Designer", "Design Consultant",
115 "Frontend Product Designer", "Team Lead Payment Page and Processing",
116 "Head of Engineering", "Senior Software Engineering Manager",
117 "Head of Technology", "Head of Development", "Senior Software Developer",
118 "Producer", "Vice President", "Software Developer", NA),
119 Years1 = c(3, 1, 2, 1, 2, 2, 2, 1, 5, 5, 5, NA, NA, 1, 4,
120 1, 6, 1, 2, 4, 2, 3, 3, 3, 1, 1, 2, 2, 1, 2, 4, 1, 1, 1,
121 2, NA, 1, 1, 4, 1, 1, 3, 2, 1, 1, 1, 1, 1, 1, 2, 3, 3, 4,
122 2, 2, 6, 1, 2, NA), Job2 = c("Data Scientist", "Machine Learning Engineer",
123 "Machine Learning Developer - Associate Manager", "Senior DWH&BI Engineer",
124 "Co-Founder & CTO", "Software Developer", "Data Engineer",
125 "Application Software Engineer", "Backend Develope", "Lead PHP Developer",
126 "Lead PHP developer", NA, "Machine Learning Engineer", "Software Engineer",
127 "Expert Application Development Specialist", "SDE 3", "Developer Trainer & Mentor",
128 "Senior Software Developer", "Senior Software Developer",
129 "AI Developer", "Software Developer & Consulatance", "Web & Communication Consultance",
130 "Mobile Application Development", "Frontend Developer", "Web Developer",
131 "Fullstack Engineer", "Javascript Developer", "Junior Research Scientist",
132 "Junior Data Analyst", "Frontend Engineer", "Senior Software Developer",
133 "Fullstack Developer", "Senior Software Developer", "Android Developer",
134 "Android Software Engineer", "Mobile Application Developer",
135 "Senior Java Developer", "Android Developer", "Android Developer",
136 "Mobile Application Developer", "Mobile Developer", "Senior Android Engineer",
137 "Senior Android Developer", "Senior Android Developer", "Software Engineer",
138 "UI/UX Designer", "Senior Information Technology Consultant",
139 "Global Head of Design", "Lead Product Desiger", "Product Manager / Product Analyst",
140 "Lead DevOps Engineer", "Vice President Tech", "Head of Product",
141 "IT Lead", "Android Consultant", "Social Game Designer",
142 "Head of Enterprise Architecture", "Team Supervisor", NA),
143 Years2 = c(1, 2, 2, 3, 5, 2, 1, 3, 1, 8, 2, NA, 2, 2, 1,
144 2, 8, 1, 1, 1, 6, 4, 2, NA, 1, 1, 1, 1, 1, 2, 6, 1, 1, 2,
145 2, 2, 2, 2, 4, 1, 2, 1, 1, 1, 1, 1, 8, 3, 6, 3, 1, 1, 1,
146 2, 2, 2, 5, 1, NA), Job3 = c("Senior Research Scientist",
147 "Senior Analytics Analyst", "Senior Developer", NA, "Graduate Research Assistant",
148 "Software Developer", NA, NA, "Software Developer", "Senior Web Developer",
149 "Lead PHP/SugarCRM developer", NA, "Data Engineer", "Software Engineer",
150 "Senior Application Development Specialist", "Manager L1 (UI/ Frontend)",
151 "Application Infrastructor Lead", "Software Developer", "Software Developer & Consultance",
152 "Software Developer", "Student Assistant", NA, "HEB Retail Application",
153 NA, NA, "Senior Software Engineer", "Frontend Web Developer",
154 "Computational Scientist/ Backend Developer", NA, "Fullstack Engineer",
155 "IT Specialist - Application Developer", "Insurance Software Programmer",
156 "Software Developer", "Android Developer", NA, "Software Developer",
157 "Senior C# Developer", "Embedded Software Intern", "Android Developer",
158 "Android Developer", "Java Developer", "Senior Android Engineer",
159 NA, "Techlead of Mobile Development Group", "Software Engineer",
160 "Product Designer", "User Experience Designer", "Chief UX and Product Architect",
161 "Product Designer UI/UX & Motion", "Senior Web Developer",
162 "Lead Developer", "Senior Manager Digital Platform Development",
163 "Head of Engineering", "IT Manager", "Head of Software Development",
164 "QA Tester", "Head of Enterprise Archticture, Lead of EA & Innovation",
165 "Videography Consultant", NA), Years3 = c(1, 1, 5, NA, 2,
166 1, NA, NA, 2, 3, 2, NA, 1, 1, NA, 1, 7, 2, 2, 5, 1, NA, 2,
167 NA, NA, 1, 1, 4, NA, 1, 1, 4, 2, 2, NA, 1, 1, 1, 1, 1, 4,
168 2, NA, 1, 1, 1, 1, 1, 1, 3, 2, 2, 1, 1, 2, 1, 4, 1, NA),
169 Job4 = c("Research Scientist", "Analytics Analyst", "Optical Engineer",
170 NA, "Graduate Teaching Assistant", NA, NA, NA, NA, NA, "PHP/ZEND Developer",
171 NA, "Software Engineer", NA, "Senior Application Development Specialist Consultance",
172 "Senior Engineer- Technology", "Fullstack IOS Developer",
173 "Software Engineering Manager/ Solution Architect", "Senior Software Developer",
174 "Software Developer", NA, NA, NA, NA, NA, "Frontend Engineer and Teamlead Frontend",
175 "Forensic Principal Expert at Special Technical Department",
176 NA, NA, "Fullstack Engineer", "Java Web Developer", "Perl & Oracle Programmer",
177 "Software Engineering Manager", NA, NA, NA, "Senior Web Developer",
178 NA, NA, "Software Developer", "Android Developer", "Senior Android Engineer/Team Lead",
179 NA, "Android/iOS App Developer", "Software Engineer", "Art Director, Lead UX/UI Designer",
180 "Founder & CEO", "Director, User Experience", "Senior Product Designer UI/UX & Motion",
181 "Senior Consultant/ Senior Software Engineer", "CTO & Partner",
182 "Senior Consutant/ Architect", NA, "Managing Director IT",
183 "Android Developer", NA, "Enterprise Architect", "Software Modification Consultant",
184 NA), Years4 = c(5, 2, 3, NA, 5, NA, NA, NA, NA, NA, 3, NA,
185 2, NA, 6, 1, 9, 2, 8, 1, NA, NA, NA, NA, NA, 2, 1, NA, NA,
186 1, 1, 3, 2, NA, NA, NA, 3, NA, NA, 1, 1, 4, NA, 1, 2, 2,
187 2, 1, 5, 3, 2, 2, NA, 2, 4, NA, 1, 2, NA), Job5 = c("PhD fellow",
188 "Java developer Intern", NA, NA, "Senior Software Engineer",
189 NA, NA, NA, NA, NA, "PHP System Analytic / Software specialist",
190 NA, NA, NA, "Application Developer Consultance", "Frontend Engineer",
191 NA, "Technical Delivery Manager", "Application Developer",
192 "Software Developer", NA, NA, NA, NA, NA, NA, "Web Designer/ Developer",
193 NA, NA, NA, "Java Software Developer", "Java Junior Programmer",
194 "Technical Delivery Manager", NA, NA, NA, "Senior Mobile Developer",
195 NA, NA, "Software Developer Intern", "Technical Consultant",
196 "Software Engineer", NA, "Fullstack Android Developer", "Software Engineer",
197 "Senior Designer", "CEO, PR & Marketing", "Managing Partner/ User Experience",
198 "Art Director", "Software Entwickler", "Developer & Consultant",
199 "Extern Senior Java Developer", NA, "Vice President Solution Delivery",
200 "Development & Sales", NA, "Senior Architect E-Commerce",
201 "IT & Custom Computer Service", NA), Years5 = c(3, 1, NA,
202 NA, 2, NA, NA, NA, NA, NA, 1, NA, NA, NA, 1, 1, NA, 2, 2,
203 2, NA, NA, NA, NA, NA, NA, 7, NA, NA, NA, 1, 1, 5, NA, NA,
204 NA, 1, NA, NA, 1, 2, 1, NA, 1, 1, 1, 2, 3, 3, 2, 2, 1, NA,
205 4, 2, NA, 1, 3, NA), Job6 = c(NA, NA, NA, NA, NA, NA, NA,
206 NA, NA, NA, "Web Developer", NA, NA, NA, "Software Instrocture",
207 "Associate Software Engineer", NA, "Software Engineer", "Software Architect",
208 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Software Engineer",
209 NA, NA, NA, "Senior Web Developer", NA, NA, NA, "Software Engineer",
210 NA, NA, NA, NA, NA, NA, "Regional Head of Experience", NA,
211 NA, "Junior IT Security Analyst", "Feelance Consulant", NA,
212 "Senior Software Engineer", NA, NA, "Team Lead E-Commerce",
213 NA, NA), Years6 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
214 2, NA, NA, NA, 1, 2, NA, 3, 3, NA, NA, NA, NA, NA, NA, NA,
215 NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, 2, NA, NA, NA, 2,
216 NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, 2, NA, 1, NA, NA, 4,
217 NA, NA), Job7 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
218 NA, NA, NA, NA, "Assistant Network Administrator", NA, NA,
219 "Technical Delivery Manager/ Project Manager", NA, NA, NA,
220 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
221 "Senior Mobile Developer", NA, NA, NA, "Web Developer", NA,
222 NA, NA, NA, NA, NA, NA, NA, NA, NA, "Developement Lead",
223 NA, "Chief Software Architect", NA, NA, "Senior Software Developer",
224 NA, NA), Years7 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
225 NA, NA, NA, NA, 1, NA, NA, 3, NA, NA, NA, NA, NA, NA, NA,
226 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
227 3, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 10, NA, 1, NA,
228 NA, 3, NA, NA), Job8 = c(NA, NA, NA, NA, NA, NA, NA, NA,
229 NA, NA, NA, NA, NA, NA, "Trainee ES Computer", NA, NA, NA,
230 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
231 NA, NA, NA, "Big-Data Developer", NA, NA, NA, "Supervisor Support",
232 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Product Development",
233 NA, NA, NA, NA, NA), Years8 = c(NA, NA, NA, NA, NA, NA, NA,
234 NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA,
235 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1,
236 NA, NA, NA, 3, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
237 NA, 1, NA, NA, NA, NA, NA), Job9 = c(NA, NA, NA, NA, NA,
238 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
239 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
240 NA, "Fullstack Developer", NA, NA, NA, NA, NA, NA, NA, NA,
241 NA, NA, NA, NA, NA, NA, NA, NA, "Software Architecture",
242 NA, NA, NA, NA, NA), Years9 = c(NA, NA, NA, NA, NA, NA, NA,
243 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
244 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 3,
245 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
246 NA, 6, NA, NA, NA, NA, NA), Job10 = c(NA, NA, NA, NA, NA,
247 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
248 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
249 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
250 NA, NA, NA, "Senior Software Developer", NA, NA, NA, NA,
251 NA), Years10 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
252 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
253 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
254 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 3, NA,
255 NA, NA, NA, NA), Job11 = c(NA, NA, NA, NA, NA, NA, NA, NA,
256 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
257 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
258 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
259 "Software Developer", NA, NA, NA, NA, NA), Years11 = c(NA,
260 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
261 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
262 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
263 NA, NA, NA, NA, NA, NA, NA, 4, NA, NA, NA, NA, NA), Job12 = c(NA,
264 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
265 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
266 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
267 NA, NA, NA, NA, NA, NA, NA, "IT/ Organisation", NA, NA, NA,
268 NA, NA), Years12 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA,
269 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
270 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
271 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 8,
272 NA, NA, NA, NA, NA)), problems = structure(list(row = c(13L,
27324L, 36L), col = c("Years1", "Years2", "Years1"), expected = c("no trailing characters",
274"no trailing characters", "no trailing characters"), actual = c("0,2",
275"0,6", "0,4"), file = c("'Recruitee Tech CVs - Tabellenblatt1 (1).csv'",
276"'Recruitee Tech CVs - Tabellenblatt1 (1).csv'", "'Recruitee Tech CVs - Tabellenblatt1 (1).csv'"
277)), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"
278)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA,
279-59L), spec = structure(list(cols = list(Index = structure(list(), class = c("collector_double",
280"collector")), FromJob = structure(list(), class = c("collector_character",
281"collector")), Highest_education_achieved = structure(list(), class = c("collector_character",
282"collector")), Skills = structure(list(), class = c("collector_character",
283"collector")), Job1_latest = structure(list(), class = c("collector_character",
284"collector")), Years1 = structure(list(), class = c("collector_double",
285"collector")), Job2 = structure(list(), class = c("collector_character",
286"collector")), Years2 = structure(list(), class = c("collector_double",
287"collector")), Job3 = structure(list(), class = c("collector_character",
288"collector")), Years3 = structure(list(), class = c("collector_double",
289"collector")), Job4 = structure(list(), class = c("collector_character",
290"collector")), Years4 = structure(list(), class = c("collector_double",
291"collector")), Job5 = structure(list(), class = c("collector_character",
292"collector")), Years5 = structure(list(), class = c("collector_double",
293"collector")), Job6 = structure(list(), class = c("collector_character",
294"collector")), Years6 = structure(list(), class = c("collector_double",
295"collector")), Job7 = structure(list(), class = c("collector_character",
296"collector")), Years7 = structure(list(), class = c("collector_double",
297"collector")), Job8 = structure(list(), class = c("collector_character",
298"collector")), Years8 = structure(list(), class = c("collector_double",
299"collector")), Job9 = structure(list(), class = c("collector_character",
300"collector")), Years9 = structure(list(), class = c("collector_double",
301"collector")), Job10 = structure(list(), class = c("collector_character",
302"collector")), Years10 = structure(list(), class = c("collector_double",
303"collector")), Job11 = structure(list(), class = c("collector_character",
304"collector")), Years11 = structure(list(), class = c("collector_double",
305"collector")), Job12 = structure(list(), class = c("collector_character",
306"collector")), Years12 = structure(list(), class = c("collector_double",
307"collector"))), default = structure(list(), class = c("collector_guess",
308"collector")), skip = 1L), class = "col_spec"))
309
ANSWER
Answered 2021-May-11 at 13:56You can get the value which is next to last non-NA value.
1structure(list(Index = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
213, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
329, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
445, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59),
5 FromJob = c("Senior Machine Learning Engineer", "Senior Machine Learning Engineer",
6 "Senior Machine Learning Engineer", "Senior Machine Learning Engineer",
7 "Senior Machine Learning Engineer", "Python Data Engineer (m/w/d)",
8 "Python Data Engineer (m/w/d)", "Python Data Engineer (m/w/d)",
9 "Lead Backend Developer (f/m/d)", "Lead Backend Developer (f/m/d)",
10 "Lead Backend Developer (f/m/d)", "Lead Backend Developer (f/m/d)",
11 "Python Data Engineer (m/w/d)", "Python Data Engineer (m/w/d)",
12 "Lead Developer", "Lead Developer", "Lead Developer", "Lead Developer",
13 "Lead Developer", "Lead Developer", "Team Lead Software Development",
14 "(Senior) Frontend Engineer", "(Senior) Frontend Engineer",
15 "(Senior) Frontend Engineer", "(Senior) Frontend Engineer",
16 "(Senior) Frontend Engineer", "(Senior) Frontend Engineer",
17 "Data Scientist", "Data Scientist", "Senior Backend (Java) Engineer",
18 "Senior Backend (Java) Engineer", "Senior Backend (Java) Engineer",
19 "Lead Developer", "Mobile Software Engineer", "Mobile Software Engineer",
20 "Mobile Software Engineer", "Mobile Software Engineer", "Mobile Software Engineer",
21 "Mobile Software Engineer", "Mobile Software Engineer", "Mobile Software Engineer",
22 "Mobile Software Engineer", "Mobile Software Engineer", "Mobile Software Engineer",
23 "Mobile Software Engineer", "Lead UI/UX Designer", "Lead UI/UX Designer",
24 "Lead UI/UX Designer", "Lead UI/UX Designer", "Head of Software Development",
25 "Head of Software Development", "Head of Software Development",
26 "Head of Software Development", "Head of Software Development",
27 "Head of Software Development", "Head of Software Development",
28 "Head of Software Development", "Jnuior Fullstack Developer",
29 NA), Highest_education_achieved = c("PhD", "MSc Computer Science",
30 "MSc", "MBA", "MSc", "MSc", "MSc", "MSc Communication and Media Engineering",
31 "High School", "BSc Informatics", "BSc Software engineering",
32 NA, "MSc in Electronic Engineering", "MSc in Communication and Media Engineering",
33 "BSc in Computer Engineering", "BSc in Technology", "MSc in Computer Science",
34 "BSc in Automatic Control System", "Dipl. Wirtschaftsinformatik",
35 "MCs Computer Science", "Dipl. Ing. in Software Development - Economics",
36 "MSc in Computer Science", "BSc. in Information Technology",
37 "MSc in Big Data and Business Analyst", "MSc. in Computer Science",
38 "Dipl.", "BSc.", "MSc. in Scientific Computing and Biomechanics",
39 "MSc. in Computational Engineering", "MSc. in Information Technology",
40 "MSc. in Computer Science", "MSc. in Informatics", "BSc.",
41 "BSc.", "BSc.", "BSc.", "BSc.", "BSc.", "BSc.", "BSc.", "Highschool",
42 "BSc.", "BSc.", "Highschool", "BSc.", "MCs.", "BSc.", "BSc.",
43 "BSc.", "MCs.", "BSc.", "Dipl.", "BSc.", "BSc.", "BSc.",
44 "BSc.", "MSc.", "BSc.", NA), Skills = c("Machine Learning, Mathematical Modeling, Scientific Computing, Linux, python, numpy, scipy, scikit-learn, keras, pandas, javascript, react.js, AWS, Lambda, EMR, EC2, S3, Glue, CloudFormation, git, Image recognition, deep learning, Natural language processing, Big data integration, cloud migration, Azure, Fortran, OpenFOAM, mercurial",
45 "Java, AngularJS, frontend, backend, Azure, data collection, modelbuilding, evaluation, deployment, serving and computing online metrics, Apache Spark, AWS Sagemaker, Airflow, MLflow, MLOps",
46 "Biometrics, Machine Learning, Pattern Recognition, AI, scrum, matlab, C++, Azure, logistics",
47 "Databricks, Spark, Airflow, AWS Sagemaker, Other AWS Services, Docker, Microstrategy, Presto, Python, PL/SQL, JavaScript, Shell Scripting, BigQuery (Google), Hadoop, Exasol, Kafka",
48 "Spark, Tensorflow &TFX, Kubeflow, BigQuery, Apache Beam (Dataflow), Google Cloud Platform",
49 "PythonC++, C, OpenCV, OpenCL, MatLab, TensorFlow/PyTorch, Caffe/Keras, Scikit-learn, Pandas/NumPy, Seaborn/Matplotlib, NLTK/spaCy, Computer Vision, Machine Learning, NLP, Linear/LogisticRegression, Naive Bayes/PCA, SVM/K Means, RandomForest, CNN/LSTM/GRU, Reinforcement Learning",
50 "Microsoft SQL Server, Hadoop,SQL Server Management Studio, VisualStudio(DataTools), PyCharm, Sublime text 3, SSIS, python, C#, \nC++, Html/Css, Java,T-SQL, git",
51 "Keras, TensorFlow, scikit-learn, NLTK, OpenCV, NumPy, pandas,Python, Java, PHP, HTML, CSS, JavaScript, Angular, React, jQuery, Bootstrap, Flask, SQL, MongoDB, Git, Docker",
52 "ElasticSearch, OOP, NoSQL, SQL, Docker, Kibana, Git, Unittest, Openshift",
53 "PHP, Java Script, CSS, (X)HTML, MySQL., NodeJS", "JavaScript (Vue.js, React, jQuery), Node.js (Express), PHP (Yii, Laravel, Symfony), JAVA (Spring Boot), .NET C#, SQL(postregsql, mysql), Elastic, MongoDB, HTML + CSS, Sketch, InVision Studio",
54 NA, "Python, C++, HTML/CSS, Java, C#, T-SQL, Microsoft SQL Server, Hadoop, Pycharm, Sublimetext 3, SISS, Git,Liquid Planner,",
55 "Keras, TensorFlow, scikit-Learn, NLTK, openCV, NumPy, pandas, Python, Java, PHP, HTML, JavaScript,CSS, Angular, React, jQuery, Bootstrap, Flask, SQL, MonoDB, Git, Android, PhoneGap, Docker",
56 "Java, PL/SQL, HTML, JavaScript, PHP, Bash, AngularJs, ReactJs, Python, Weblogic, Jboss, Tomcat, Jetty, Apache, IIS, Unix, Windows, Oracle 8i, 9i, 10g, MySql, MariaDB, PostgrwSql, MS Sql Server, GIT, Mercury, Jira",
57 "JavaScript, AngularJs, Angular Next, jQuery, RequireJS, React, WebPack, Typescript, Node, PWA, Socket Programming, Kong,",
58 "GIT, SME, API's, iOS, UI, Mobile application, SVN, Epic, Apple, SAML,",
59 "Kotlin, Java, JavaScript, Typescript, Pytion ML, AI, Spring, NoSQL, SQL, Microservices, AWS, Azure, Angular9, React, Kafka, Jenkins, Cloud, Rancher, K8s, Cloud foundry, MSSQL, Elas, Tensorflow, Boot, Teras, Hibernite, RabbitMQ, JUnit, AWS SQS, Docker, C++, STL, XML, Linux, Bash,",
60 "Scrum, Code Reviews, JIRA, Mantis, Kanban, Trello, Java, Kotlin, Typescript, Groovy, JavaScript, Delphi, Openshift, Kubernetes, Docker, Azure, Open Telekom Cloud, CosmosDB, Heroku, REST, SOAP, XMPP, NATS, JMS, ActiveMQ, Gatling, Mocktesting, Mockito, EasyMock, Cucumber, Angular 8, React, GWT, JSF, JSP, Struts, Spring Boot, JEE, Hibernate, JPA, MongoDB, Oracle, Postgres, CosmosDB, MySQL, DB2, SQL-Tuning, Maven, Ant, Gradle, GIT, SVN, CVS, BIRT, JasperReports, MicroStrategy, Maven,",
61 "Kotlin, Java 11, Docker, AWS, GCP, Kubernetes,Neo-4j, Solr, Spring-boot, Postgres, Hibernate, Flyway, sendGrit, Gradl, rxJava, Freemaker, Grafana, Prometheus,Oauth 2, Spring-gateway, Microservices, AWS, Amazon EMR, DynamoDB, S3, Hive, hdfs, storm, kafka, reactive programming, spring-cloud, groovy, elasticsearch, hystrix, ribbon, eureka, API, java 8, grunt, bamboo, jenkins, JavaScript, Junit, jbpm, jmx, C++, j2ee, servlet,",
62 "Scrum, SAP, NetWeaver 7.40", "CSS. Html, Bootstrap, Php, MySQL, JavaScript, Wordpress, Typo 3, Google Analytics, Google Adwords, React, GatsbyJS, Nextjs, Flutter, Postgres, AWS, Docker, Google Cloud Platform,",
63 "Node JS, JavaScript, ES6, CSS, PHP, XML, JQuery, Lambda, Appsync, React, JS, HTML5, CSS3, Bootstrap, REST web services, Microservices, JSON, Elasticsearch, Java, React JS, AWS Server, MAMP, Maven, Laravel, Codeigniter, MySQL, Dynamo DB, SQLite, Oracle, MS SQL, MAC, UNIX, Windows, Git, AWS-EC2, S3, Cloud Formation, Cloudwatch, SNS, PhpStorm, WebSorm, Visual Studio Code, Eclipse, Netbeans, Android Studio",
64 "C, C++, Java, J2EE, Dotnet, Angular, React, JS, JavaScript, Query, CSS, HTML, Microsoft SQL Server, GIT, React JS with Redux, Vue JS, CSS3, Bootstrap, Media query, AEM, Jest test, Python, Tabeleau, AWS, Miro",
65 "JavaScript, ReactJs, TypeScript, Python, C++, HTML, ASP, C#",
66 "SPA, TypeScript, React Hooks, Jest, Lerna, React Query, Azure DevOps, Storybook, RxJx, Socket.io, OpenAPI, SCSS,",
67 "JavaScript, React JS, Flow, Redux, React SSR, urql graphql client, Java 11, HTML5, CSSS3, JavaScript (ES6+), TypeScript, jQuery, AJAX, webpack, NodeJS, PHP, Express, MongoDB, SASS, Heroku, Linux, Hetzner, Git, AngularJS,",
68 "Linux, Windows, MS Office, Libre office, Python, SQL, Bash, C/C++, MATLAB, NumPy, SciPy, pandas, SciKit-Learn, statsmodels, Keras, TensorFlow, Flask, Matplotlib, Seaborn, Tableau, ParaView, Tecplot, Inkscape, GIMP, PyCharm, jupyter, Eclipse, Visual Studio, Git, Docker, Poetry, Pytest, Unittest, Pylint, Pre-commit",
69 "Python, C/C++, SQL, MySQL, Numpy, Pandas, Scipy, Scikit-Learn, Keras, Tensorflow, Theano, PyTorch, Visual Studio, Pycharm, Jupyter Notebook, Vscode, PowerBi, MS Office, Sourcetree, Jira, Git, Linux, Mac, Windows",
70 "NPM, Webpack, Bower, Gruntjs, Gulp, JavaScript, Angular, CSS, Animation, Angular-animation, TypeScript, ReactJS, Node.js, Lombok, Vue.js, Visual Studio, HTML, Maven, Redux, Chart.js, Kotlin,",
71 "Java. Web Services, Design Patterns, Agile Methodologies, Spring Hibernate, JSF, JUnit, Maven Eclipse, SQL, XML, Linux, Websphere, Tomcat, jQuery, Ant, JDBC, Subversion, JavaScript, CSS, JPA, Git, Jenkins, REST, services, AJAX, Glassfish, Java Enterprise Edition, Apache, Lucene, Artifactory,",
72 "Java, HTML, Perl, Programming, SQL, JavaScript, CSS, Oracle, C++, Linux, CSS, PHP, C#, Ruby, C",
73 NA, "Jira, Git, Scrum, Agile, Retrofit, Picasso, Volley, RESTful, HTTP, JSON, Asyns-task, Dagger2, MVVM Architecture, API, SQLite, Pandas, NumPy,",
74 "Kotlin, MVVM Archtiecture, Firebase, Google-Services, Git, Retrofit, JSON, Material Design UI, Constrains Layout Animations, Jira, Figma, Zeplin, Agile, Scrum",
75 "C++, Java, MVC Design, AdMob, Google Maps API Keys, Retrofit, Gson, SQLite, Picasso, Google Vision, Play Services, SQL, iOS Develpment, JSON, C#, XML, Android",
76 "Server-Side, Client-Side, NOSQL, Agile Development, Machine Learning, Elastic Search, AWS, C#, OOP, Object Oriented, Programming, SQL, DB, RDBMS, Relational Database, CSS, Angular, AngularJs, JavaScript, TypeScript, JQuery, HTML, PHP, .NET, MVC.NET, DOT.NET, HADOOP, Java, Apache Hive, XML, JSON, AJAX,MySQL, Visual Studio, Bootstrap, XCode, Android, IOS,",
77 "Kotlin, Java, Rx, Dagger, Retrofit, Data Binding, Glide, Picasso, Leak Canary,Git, Flow, MVP, MVVM, Junit, Mockito, Espresso, Repository, Pattern, Singleton Pattern, CI/CD, Python, C/C++, C#, HTML, CSS, JavaScript, React, Spring Boot, Slack, XML, Android Arch Components, Material Design, Timber, ML, Kit,",
78 "Android SDK, Java, Kotlin, XML, Firebase, Android Studio, GIMP, Illustrator, PHP, API,",
79 "Android Development, Java, Firebase, Kotlin, SQLite, Android Studio, SDK Implementation, Mobile Application, Version Control, JSON, IMA SDK, Google AdSense, Jira, C#, Swift",
80 "Java, Android SDK, Java SE, GWT, AWT, SWT, JSP, JSTL, JSF, Hibernate, Struts, Kotlin, Swift, JavaScript, jQuery, Oracle, MySQL, SQLite, PHP, HTML, CSS, C#,GWT, Angular, Bootstrap, Junit, Selenium, Appium, JavaServer Faces, Zend, Eclipse, XCode, Unity, iOS, Firebase, Open Source, Atlassian, Apache, Microsoft, Adobe,",
81 "Android, Kotlin, Java, Dart, MVVM, UAT, CI/CD, UI/UX,",
82 "GoF Design Patterns, SOLID, MVVM, MVP, MVC, Android Development, AppoloGraphQL, Dagger2, RxJava, Jetpack Components, Kotlin, iOS, Swift, Autolayout, Python, JavaScript",
83 "Git, Youtrack, Trello, Jira, CI/CD, Gitlab, Teamcity, Kotlin, Java, Retrofit, Ktor, Android Architechture Compor Room, SQLDelight, RxJava2, Coroutines/Flow, MVP, MVVM, MVI, Python, Scrum, Waterfall",
84 "Java, Kotlin, XML, Android SDK, Retrofit, Okhttp, Dagger 2, Eventbus, Multithreating, Design Patterns, RX, Coroutines, Picasso, Glide, MVM, MVVM, MVP, Clean Architecture, Android Jetpack, Android Architecture Component, Espresso, Junit, Mockito, Cucumber, SQLite, Realm, Room, Firebase, Git",
85 "invison, Uxpin, Sketch, Figma, Slack Abstract, Adobe XD, Adobe InDesign, Illustrator, Adobe Photoshop, Adobe Muse, Rhinoceros, Animation Studio, MacOS, Microsoft Office, Material Design, Fluent Design, Swift, React, Angular, HTML, CSS, JS, GitHub",
86 "PHP, HTML, CSS, JavaScript, React, Python, CRO, Adobe XD, Sketch, InVision, Lingo App, TripleTex,",
87 "Figma, Sketch, Invision, Adobe XD, Adobe Creative Cloud, Craft Marvel,",
88 "Figma, Sketch, Photoshop, Illustrator, Adobe After Effects, Maya, Cinema 4D, JavaScript, HTML, CSS, React, Node, Next.js, TailwindCSS, Firebase, MongoDB,",
89 "Java, C#.NET, PHP, Python, JavaScript, HTML, CSS, XML, Datenbanken, SQL, Geodaten, CMS Systeme, Jira, Confluence, Linux, Webserver-Betrieb, Catching, Load Balancing, Monitoring CI Systeme, automatisiertes Testen, Deployment,",
90 "Software Engineering, DevOps, System Architecture, Agile Transformation, IT Security, Python, Java, CI, CD, Docker, iOS, C++, C#, Golang, Ruby, Node JS, PostgrSQL, MySQL, RethinkDB, Cassandra, Consul",
91 "Cobol, Delta, ISAM, Java, JavaScript, CSS, Eclipse RCP, ANTLR, JPA, Maven, JPA/Hibernate, Lucene, HSQL, Oracle, Tomcat, Jetty, Axis, JBoss, JAX-WS, SOAP, WSDL, HBase, Jenkins, SNS, S3, SASS, Jira, Github, SEO/SM, Gitlab, Kotlin, Kafka,",
92 "AWS, Azure, Angular, MongoDB, Node.js, iOS,", "Java, RIM, COM Interfaces, Edifact, MT940, XSLT, XML, Tomcat, JMS, Arvo Workflowsystem, XSL-FO, Xalan, JSP, Servlets, JavaScript, Struts, EJB, JPA, Trinidad, Drools, XFire, Eclipse, Springframework, Dozer Framework,",
93 "Android, Java, Python, Rails, Ruby, SQL, Kotlin, Git, Redmine, MariaDB, Gitlab, Jira, Bitbucket, Mattermost, Docker, Jenkins CI,",
94 "Trello, Asana, Microsoft Office, Photoshop, Unity 3D,",
95 "Java, CMS, Scrum, C++, SOA, EDA, Cloud,", "SQL, Adobe, Python, SQL, ABAP, React + TypeScript, Node.js, CMS, REST API, Tensorflow + Pytorch, Flutter, AWS Deployment, SAP, Jira, AutoCAD",
96 NA), Job1_latest = c("Senior Engineer - Machine learning",
97 "Senior Machine Learning Engineer", "Application Developer Associate Manager",
98 "Senior Data & ML Engineer", "Senior Machine Learning Engineer",
99 "Software Developer", "Machine Learning Engineer", "Akademischer Mitarbeiter, Machine Learning and Analytics",
100 "Senior Backend Developer", "Senior Web Developer", "Software Architect / Development lead",
101 NA, "Data Analysing (Researcher)", "Software Engineer", "Sofware Developer",
102 "Senior Associate Experience Technology", "Senior Software Architect",
103 "Senior Software Developer / Tech Lead", "Fullstack Developer/ ProductOwner",
104 "Freelancing Software Developer", "Senior Software Developer / Teamlead",
105 "Fullstack JavaScript Developer", "Blowoutandgo Application Developer",
106 "Software Developer", "Software Engineer", "Senior Frontend Engineer and Lead Developer",
107 "Javascript Developer", "Data Scientist/ Python Developer",
108 "Research Assistant", "Fullstack Engineer", "Backend Developer",
109 "App-Backend Developer", "Senior Software Developer", "Android Developer",
110 "Android Software Engineer", "Senior Android Developer",
111 "Senior C# Developer", "Software Developer", "Applications Developer",
112 "Senior Android Developer", "Android Developer", "Senior Android Engineer",
113 "Mobile Engineer", "Senior Android Developer", "Software Engineer",
114 "Senior UX/UI Designer", "User Experience Designer", "Design Consultant",
115 "Frontend Product Designer", "Team Lead Payment Page and Processing",
116 "Head of Engineering", "Senior Software Engineering Manager",
117 "Head of Technology", "Head of Development", "Senior Software Developer",
118 "Producer", "Vice President", "Software Developer", NA),
119 Years1 = c(3, 1, 2, 1, 2, 2, 2, 1, 5, 5, 5, NA, NA, 1, 4,
120 1, 6, 1, 2, 4, 2, 3, 3, 3, 1, 1, 2, 2, 1, 2, 4, 1, 1, 1,
121 2, NA, 1, 1, 4, 1, 1, 3, 2, 1, 1, 1, 1, 1, 1, 2, 3, 3, 4,
122 2, 2, 6, 1, 2, NA), Job2 = c("Data Scientist", "Machine Learning Engineer",
123 "Machine Learning Developer - Associate Manager", "Senior DWH&BI Engineer",
124 "Co-Founder & CTO", "Software Developer", "Data Engineer",
125 "Application Software Engineer", "Backend Develope", "Lead PHP Developer",
126 "Lead PHP developer", NA, "Machine Learning Engineer", "Software Engineer",
127 "Expert Application Development Specialist", "SDE 3", "Developer Trainer & Mentor",
128 "Senior Software Developer", "Senior Software Developer",
129 "AI Developer", "Software Developer & Consulatance", "Web & Communication Consultance",
130 "Mobile Application Development", "Frontend Developer", "Web Developer",
131 "Fullstack Engineer", "Javascript Developer", "Junior Research Scientist",
132 "Junior Data Analyst", "Frontend Engineer", "Senior Software Developer",
133 "Fullstack Developer", "Senior Software Developer", "Android Developer",
134 "Android Software Engineer", "Mobile Application Developer",
135 "Senior Java Developer", "Android Developer", "Android Developer",
136 "Mobile Application Developer", "Mobile Developer", "Senior Android Engineer",
137 "Senior Android Developer", "Senior Android Developer", "Software Engineer",
138 "UI/UX Designer", "Senior Information Technology Consultant",
139 "Global Head of Design", "Lead Product Desiger", "Product Manager / Product Analyst",
140 "Lead DevOps Engineer", "Vice President Tech", "Head of Product",
141 "IT Lead", "Android Consultant", "Social Game Designer",
142 "Head of Enterprise Architecture", "Team Supervisor", NA),
143 Years2 = c(1, 2, 2, 3, 5, 2, 1, 3, 1, 8, 2, NA, 2, 2, 1,
144 2, 8, 1, 1, 1, 6, 4, 2, NA, 1, 1, 1, 1, 1, 2, 6, 1, 1, 2,
145 2, 2, 2, 2, 4, 1, 2, 1, 1, 1, 1, 1, 8, 3, 6, 3, 1, 1, 1,
146 2, 2, 2, 5, 1, NA), Job3 = c("Senior Research Scientist",
147 "Senior Analytics Analyst", "Senior Developer", NA, "Graduate Research Assistant",
148 "Software Developer", NA, NA, "Software Developer", "Senior Web Developer",
149 "Lead PHP/SugarCRM developer", NA, "Data Engineer", "Software Engineer",
150 "Senior Application Development Specialist", "Manager L1 (UI/ Frontend)",
151 "Application Infrastructor Lead", "Software Developer", "Software Developer & Consultance",
152 "Software Developer", "Student Assistant", NA, "HEB Retail Application",
153 NA, NA, "Senior Software Engineer", "Frontend Web Developer",
154 "Computational Scientist/ Backend Developer", NA, "Fullstack Engineer",
155 "IT Specialist - Application Developer", "Insurance Software Programmer",
156 "Software Developer", "Android Developer", NA, "Software Developer",
157 "Senior C# Developer", "Embedded Software Intern", "Android Developer",
158 "Android Developer", "Java Developer", "Senior Android Engineer",
159 NA, "Techlead of Mobile Development Group", "Software Engineer",
160 "Product Designer", "User Experience Designer", "Chief UX and Product Architect",
161 "Product Designer UI/UX & Motion", "Senior Web Developer",
162 "Lead Developer", "Senior Manager Digital Platform Development",
163 "Head of Engineering", "IT Manager", "Head of Software Development",
164 "QA Tester", "Head of Enterprise Archticture, Lead of EA & Innovation",
165 "Videography Consultant", NA), Years3 = c(1, 1, 5, NA, 2,
166 1, NA, NA, 2, 3, 2, NA, 1, 1, NA, 1, 7, 2, 2, 5, 1, NA, 2,
167 NA, NA, 1, 1, 4, NA, 1, 1, 4, 2, 2, NA, 1, 1, 1, 1, 1, 4,
168 2, NA, 1, 1, 1, 1, 1, 1, 3, 2, 2, 1, 1, 2, 1, 4, 1, NA),
169 Job4 = c("Research Scientist", "Analytics Analyst", "Optical Engineer",
170 NA, "Graduate Teaching Assistant", NA, NA, NA, NA, NA, "PHP/ZEND Developer",
171 NA, "Software Engineer", NA, "Senior Application Development Specialist Consultance",
172 "Senior Engineer- Technology", "Fullstack IOS Developer",
173 "Software Engineering Manager/ Solution Architect", "Senior Software Developer",
174 "Software Developer", NA, NA, NA, NA, NA, "Frontend Engineer and Teamlead Frontend",
175 "Forensic Principal Expert at Special Technical Department",
176 NA, NA, "Fullstack Engineer", "Java Web Developer", "Perl & Oracle Programmer",
177 "Software Engineering Manager", NA, NA, NA, "Senior Web Developer",
178 NA, NA, "Software Developer", "Android Developer", "Senior Android Engineer/Team Lead",
179 NA, "Android/iOS App Developer", "Software Engineer", "Art Director, Lead UX/UI Designer",
180 "Founder & CEO", "Director, User Experience", "Senior Product Designer UI/UX & Motion",
181 "Senior Consultant/ Senior Software Engineer", "CTO & Partner",
182 "Senior Consutant/ Architect", NA, "Managing Director IT",
183 "Android Developer", NA, "Enterprise Architect", "Software Modification Consultant",
184 NA), Years4 = c(5, 2, 3, NA, 5, NA, NA, NA, NA, NA, 3, NA,
185 2, NA, 6, 1, 9, 2, 8, 1, NA, NA, NA, NA, NA, 2, 1, NA, NA,
186 1, 1, 3, 2, NA, NA, NA, 3, NA, NA, 1, 1, 4, NA, 1, 2, 2,
187 2, 1, 5, 3, 2, 2, NA, 2, 4, NA, 1, 2, NA), Job5 = c("PhD fellow",
188 "Java developer Intern", NA, NA, "Senior Software Engineer",
189 NA, NA, NA, NA, NA, "PHP System Analytic / Software specialist",
190 NA, NA, NA, "Application Developer Consultance", "Frontend Engineer",
191 NA, "Technical Delivery Manager", "Application Developer",
192 "Software Developer", NA, NA, NA, NA, NA, NA, "Web Designer/ Developer",
193 NA, NA, NA, "Java Software Developer", "Java Junior Programmer",
194 "Technical Delivery Manager", NA, NA, NA, "Senior Mobile Developer",
195 NA, NA, "Software Developer Intern", "Technical Consultant",
196 "Software Engineer", NA, "Fullstack Android Developer", "Software Engineer",
197 "Senior Designer", "CEO, PR & Marketing", "Managing Partner/ User Experience",
198 "Art Director", "Software Entwickler", "Developer & Consultant",
199 "Extern Senior Java Developer", NA, "Vice President Solution Delivery",
200 "Development & Sales", NA, "Senior Architect E-Commerce",
201 "IT & Custom Computer Service", NA), Years5 = c(3, 1, NA,
202 NA, 2, NA, NA, NA, NA, NA, 1, NA, NA, NA, 1, 1, NA, 2, 2,
203 2, NA, NA, NA, NA, NA, NA, 7, NA, NA, NA, 1, 1, 5, NA, NA,
204 NA, 1, NA, NA, 1, 2, 1, NA, 1, 1, 1, 2, 3, 3, 2, 2, 1, NA,
205 4, 2, NA, 1, 3, NA), Job6 = c(NA, NA, NA, NA, NA, NA, NA,
206 NA, NA, NA, "Web Developer", NA, NA, NA, "Software Instrocture",
207 "Associate Software Engineer", NA, "Software Engineer", "Software Architect",
208 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Software Engineer",
209 NA, NA, NA, "Senior Web Developer", NA, NA, NA, "Software Engineer",
210 NA, NA, NA, NA, NA, NA, "Regional Head of Experience", NA,
211 NA, "Junior IT Security Analyst", "Feelance Consulant", NA,
212 "Senior Software Engineer", NA, NA, "Team Lead E-Commerce",
213 NA, NA), Years6 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
214 2, NA, NA, NA, 1, 2, NA, 3, 3, NA, NA, NA, NA, NA, NA, NA,
215 NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, 2, NA, NA, NA, 2,
216 NA, NA, NA, NA, NA, NA, 1, NA, NA, 1, 2, NA, 1, NA, NA, 4,
217 NA, NA), Job7 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
218 NA, NA, NA, NA, "Assistant Network Administrator", NA, NA,
219 "Technical Delivery Manager/ Project Manager", NA, NA, NA,
220 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
221 "Senior Mobile Developer", NA, NA, NA, "Web Developer", NA,
222 NA, NA, NA, NA, NA, NA, NA, NA, NA, "Developement Lead",
223 NA, "Chief Software Architect", NA, NA, "Senior Software Developer",
224 NA, NA), Years7 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
225 NA, NA, NA, NA, 1, NA, NA, 3, NA, NA, NA, NA, NA, NA, NA,
226 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA,
227 3, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 10, NA, 1, NA,
228 NA, 3, NA, NA), Job8 = c(NA, NA, NA, NA, NA, NA, NA, NA,
229 NA, NA, NA, NA, NA, NA, "Trainee ES Computer", NA, NA, NA,
230 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
231 NA, NA, NA, "Big-Data Developer", NA, NA, NA, "Supervisor Support",
232 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "Product Development",
233 NA, NA, NA, NA, NA), Years8 = c(NA, NA, NA, NA, NA, NA, NA,
234 NA, NA, NA, NA, NA, NA, NA, 1, NA, NA, NA, NA, NA, NA, NA,
235 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 1,
236 NA, NA, NA, 3, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
237 NA, 1, NA, NA, NA, NA, NA), Job9 = c(NA, NA, NA, NA, NA,
238 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
239 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
240 NA, "Fullstack Developer", NA, NA, NA, NA, NA, NA, NA, NA,
241 NA, NA, NA, NA, NA, NA, NA, NA, "Software Architecture",
242 NA, NA, NA, NA, NA), Years9 = c(NA, NA, NA, NA, NA, NA, NA,
243 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
244 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 3,
245 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
246 NA, 6, NA, NA, NA, NA, NA), Job10 = c(NA, NA, NA, NA, NA,
247 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
248 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
249 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
250 NA, NA, NA, "Senior Software Developer", NA, NA, NA, NA,
251 NA), Years10 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
252 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
253 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
254 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 3, NA,
255 NA, NA, NA, NA), Job11 = c(NA, NA, NA, NA, NA, NA, NA, NA,
256 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
257 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
258 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
259 "Software Developer", NA, NA, NA, NA, NA), Years11 = c(NA,
260 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
261 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
262 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
263 NA, NA, NA, NA, NA, NA, NA, 4, NA, NA, NA, NA, NA), Job12 = c(NA,
264 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
265 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
266 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
267 NA, NA, NA, NA, NA, NA, NA, "IT/ Organisation", NA, NA, NA,
268 NA, NA), Years12 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA,
269 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
270 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
271 NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 8,
272 NA, NA, NA, NA, NA)), problems = structure(list(row = c(13L,
27324L, 36L), col = c("Years1", "Years2", "Years1"), expected = c("no trailing characters",
274"no trailing characters", "no trailing characters"), actual = c("0,2",
275"0,6", "0,4"), file = c("'Recruitee Tech CVs - Tabellenblatt1 (1).csv'",
276"'Recruitee Tech CVs - Tabellenblatt1 (1).csv'", "'Recruitee Tech CVs - Tabellenblatt1 (1).csv'"
277)), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"
278)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA,
279-59L), spec = structure(list(cols = list(Index = structure(list(), class = c("collector_double",
280"collector")), FromJob = structure(list(), class = c("collector_character",
281"collector")), Highest_education_achieved = structure(list(), class = c("collector_character",
282"collector")), Skills = structure(list(), class = c("collector_character",
283"collector")), Job1_latest = structure(list(), class = c("collector_character",
284"collector")), Years1 = structure(list(), class = c("collector_double",
285"collector")), Job2 = structure(list(), class = c("collector_character",
286"collector")), Years2 = structure(list(), class = c("collector_double",
287"collector")), Job3 = structure(list(), class = c("collector_character",
288"collector")), Years3 = structure(list(), class = c("collector_double",
289"collector")), Job4 = structure(list(), class = c("collector_character",
290"collector")), Years4 = structure(list(), class = c("collector_double",
291"collector")), Job5 = structure(list(), class = c("collector_character",
292"collector")), Years5 = structure(list(), class = c("collector_double",
293"collector")), Job6 = structure(list(), class = c("collector_character",
294"collector")), Years6 = structure(list(), class = c("collector_double",
295"collector")), Job7 = structure(list(), class = c("collector_character",
296"collector")), Years7 = structure(list(), class = c("collector_double",
297"collector")), Job8 = structure(list(), class = c("collector_character",
298"collector")), Years8 = structure(list(), class = c("collector_double",
299"collector")), Job9 = structure(list(), class = c("collector_character",
300"collector")), Years9 = structure(list(), class = c("collector_double",
301"collector")), Job10 = structure(list(), class = c("collector_character",
302"collector")), Years10 = structure(list(), class = c("collector_double",
303"collector")), Job11 = structure(list(), class = c("collector_character",
304"collector")), Years11 = structure(list(), class = c("collector_double",
305"collector")), Job12 = structure(list(), class = c("collector_character",
306"collector")), Years12 = structure(list(), class = c("collector_double",
307"collector"))), default = structure(list(), class = c("collector_guess",
308"collector")), skip = 1L), class = "col_spec"))
309first_job <- function(x) {x1 <- x[!is.na(x)];x1[length(x1) - 1][1]}
310apply(data[-(1:4)], 1, first_job)
311
312#[1] "PhD fellow" "Java developer Intern" "Optical Engineer"
313#[4] "Senior DWH&BI Engineer" "Senior Software Engineer" "Software Developer"
314
QUESTION
Cannot create an instance of ViewModel Class
Asked 2021-May-09 at 07:58When I try to run my app, it crashes with this logcat error. This problem is very similar to this and this post but all mentioned solutions didn't work for me.
When I searched for this error, I found out that it's usually because of the viewmodelproviders being outdated and people recommending to use the new ViewModelProvider with Factory class but even that didn't work out for me.
java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
I don't see where there could be an issue, if I have a tiny syntax error somewhere or something else. It is driving me crazy as I'm a beginner and trying to learn Android Architecture Components. I was following a youtube playlist linked here and his code worked flawlessly when he ran it. Please take a look at it before flagging it as a duplicate. I'm really out of my depth here. Thanks in advance.
logcat error
1 Process: com.emirhalici.notetakingappnvvmexample, PID: 17577
2java.lang.RuntimeException: Unable to start activity ComponentInfo{com.emirhalici.notetakingappnvvmexample/com.emirhalici.notetakingappnvvmexample.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
3 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
4 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
5 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
6 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
7 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
8 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
9 at android.os.Handler.dispatchMessage(Handler.java:106)
10 at android.os.Looper.loop(Looper.java:223)
11 at android.app.ActivityThread.main(ActivityThread.java:7656)
12 at java.lang.reflect.Method.invoke(Native Method)
13 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
14 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
15 Caused by: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
16 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:275)
17 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
18 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
19 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
20 at android.app.Activity.performCreate(Activity.java:8000)
21 at android.app.Activity.performCreate(Activity.java:7984)
22 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
23 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
24 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
25 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
26 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
27 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
28 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
29 at android.os.Handler.dispatchMessage(Handler.java:106)
30 at android.os.Looper.loop(Looper.java:223)
31 at android.app.ActivityThread.main(ActivityThread.java:7656)
32 at java.lang.reflect.Method.invoke(Native Method)
33 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
34 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
35 Caused by: java.lang.reflect.InvocationTargetException
36 at java.lang.reflect.Constructor.newInstance0(Native Method)
37 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
38 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
39 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
40 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
41 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
42 at android.app.Activity.performCreate(Activity.java:8000)
43 at android.app.Activity.performCreate(Activity.java:7984)
44 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
45 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
46 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
47 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
48 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
49 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
50 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
51 at android.os.Handler.dispatchMessage(Handler.java:106)
52 at android.os.Looper.loop(Looper.java:223)
53 at android.app.ActivityThread.main(ActivityThread.java:7656)
54 at java.lang.reflect.Method.invoke(Native Method)
55 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
56 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
57 Caused by: java.lang.RuntimeException: cannot find implementation for com.emirhalici.notetakingappnvvmexample.NoteDatabase. NoteDatabase_Impl does not exist
58 at androidx.room.Room.getGeneratedImplementation(Room.java:97)
59 at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1358)
60 at com.emirhalici.notetakingappnvvmexample.NoteDatabase.getInstance(NoteDatabase.java:25)
61 at com.emirhalici.notetakingappnvvmexample.NoteRepository.<init>(NoteRepository.java:15)
62 at com.emirhalici.notetakingappnvvmexample.NoteViewModel.<init>(NoteViewModel.java:19)
63 at java.lang.reflect.Constructor.newInstance0(Native Method)
64 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
65 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
66 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
67 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
68 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
69 at android.app.Activity.performCreate(Activity.java:8000)
70 at android.app.Activity.performCreate(Activity.java:7984)
71 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
72 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
73 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
74 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
75 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
76 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
77 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
78 at android.os.Handler.dispatchMessage(Handler.java:106)
79 at android.os.Looper.loop(Looper.java:223)
80 at android.app.ActivityThread.main(ActivityThread.java:7656)
81 at java.lang.reflect.Method.invoke(Native Method)
82 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
83 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
84
MainActivity.java
1 Process: com.emirhalici.notetakingappnvvmexample, PID: 17577
2java.lang.RuntimeException: Unable to start activity ComponentInfo{com.emirhalici.notetakingappnvvmexample/com.emirhalici.notetakingappnvvmexample.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
3 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
4 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
5 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
6 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
7 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
8 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
9 at android.os.Handler.dispatchMessage(Handler.java:106)
10 at android.os.Looper.loop(Looper.java:223)
11 at android.app.ActivityThread.main(ActivityThread.java:7656)
12 at java.lang.reflect.Method.invoke(Native Method)
13 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
14 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
15 Caused by: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
16 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:275)
17 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
18 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
19 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
20 at android.app.Activity.performCreate(Activity.java:8000)
21 at android.app.Activity.performCreate(Activity.java:7984)
22 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
23 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
24 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
25 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
26 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
27 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
28 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
29 at android.os.Handler.dispatchMessage(Handler.java:106)
30 at android.os.Looper.loop(Looper.java:223)
31 at android.app.ActivityThread.main(ActivityThread.java:7656)
32 at java.lang.reflect.Method.invoke(Native Method)
33 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
34 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
35 Caused by: java.lang.reflect.InvocationTargetException
36 at java.lang.reflect.Constructor.newInstance0(Native Method)
37 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
38 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
39 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
40 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
41 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
42 at android.app.Activity.performCreate(Activity.java:8000)
43 at android.app.Activity.performCreate(Activity.java:7984)
44 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
45 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
46 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
47 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
48 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
49 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
50 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
51 at android.os.Handler.dispatchMessage(Handler.java:106)
52 at android.os.Looper.loop(Looper.java:223)
53 at android.app.ActivityThread.main(ActivityThread.java:7656)
54 at java.lang.reflect.Method.invoke(Native Method)
55 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
56 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
57 Caused by: java.lang.RuntimeException: cannot find implementation for com.emirhalici.notetakingappnvvmexample.NoteDatabase. NoteDatabase_Impl does not exist
58 at androidx.room.Room.getGeneratedImplementation(Room.java:97)
59 at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1358)
60 at com.emirhalici.notetakingappnvvmexample.NoteDatabase.getInstance(NoteDatabase.java:25)
61 at com.emirhalici.notetakingappnvvmexample.NoteRepository.<init>(NoteRepository.java:15)
62 at com.emirhalici.notetakingappnvvmexample.NoteViewModel.<init>(NoteViewModel.java:19)
63 at java.lang.reflect.Constructor.newInstance0(Native Method)
64 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
65 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
66 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
67 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
68 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
69 at android.app.Activity.performCreate(Activity.java:8000)
70 at android.app.Activity.performCreate(Activity.java:7984)
71 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
72 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
73 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
74 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
75 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
76 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
77 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
78 at android.os.Handler.dispatchMessage(Handler.java:106)
79 at android.os.Looper.loop(Looper.java:223)
80 at android.app.ActivityThread.main(ActivityThread.java:7656)
81 at java.lang.reflect.Method.invoke(Native Method)
82 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
83 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
84public class MainActivity extends AppCompatActivity {
85private NoteViewModel noteViewModel;
86
87@Override
88protected void onCreate(Bundle savedInstanceState) {
89 super.onCreate(savedInstanceState);
90 setContentView(R.layout.activity_main);
91
92 // these didn't work
93 //noteViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
94 //noteViewModel = new ViewModelProvider(this).get(NoteViewModel.class);
95 //noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
96 // i tried this but this don't work either
97 noteViewModel = new ViewModelProvider(this,
98 ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
99 noteViewModel.getAllNotes().observe(this, new Observer<List<Note>>() {
100 @Override
101 public void onChanged(List<Note> notes) {
102 // update RecyclerView
103 Toast.makeText(MainActivity.this, "onChanged", Toast.LENGTH_SHORT).show();
104 }
105 });
106} }
107
Note.java (entity class)
1 Process: com.emirhalici.notetakingappnvvmexample, PID: 17577
2java.lang.RuntimeException: Unable to start activity ComponentInfo{com.emirhalici.notetakingappnvvmexample/com.emirhalici.notetakingappnvvmexample.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
3 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
4 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
5 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
6 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
7 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
8 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
9 at android.os.Handler.dispatchMessage(Handler.java:106)
10 at android.os.Looper.loop(Looper.java:223)
11 at android.app.ActivityThread.main(ActivityThread.java:7656)
12 at java.lang.reflect.Method.invoke(Native Method)
13 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
14 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
15 Caused by: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
16 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:275)
17 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
18 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
19 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
20 at android.app.Activity.performCreate(Activity.java:8000)
21 at android.app.Activity.performCreate(Activity.java:7984)
22 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
23 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
24 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
25 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
26 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
27 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
28 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
29 at android.os.Handler.dispatchMessage(Handler.java:106)
30 at android.os.Looper.loop(Looper.java:223)
31 at android.app.ActivityThread.main(ActivityThread.java:7656)
32 at java.lang.reflect.Method.invoke(Native Method)
33 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
34 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
35 Caused by: java.lang.reflect.InvocationTargetException
36 at java.lang.reflect.Constructor.newInstance0(Native Method)
37 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
38 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
39 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
40 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
41 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
42 at android.app.Activity.performCreate(Activity.java:8000)
43 at android.app.Activity.performCreate(Activity.java:7984)
44 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
45 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
46 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
47 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
48 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
49 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
50 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
51 at android.os.Handler.dispatchMessage(Handler.java:106)
52 at android.os.Looper.loop(Looper.java:223)
53 at android.app.ActivityThread.main(ActivityThread.java:7656)
54 at java.lang.reflect.Method.invoke(Native Method)
55 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
56 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
57 Caused by: java.lang.RuntimeException: cannot find implementation for com.emirhalici.notetakingappnvvmexample.NoteDatabase. NoteDatabase_Impl does not exist
58 at androidx.room.Room.getGeneratedImplementation(Room.java:97)
59 at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1358)
60 at com.emirhalici.notetakingappnvvmexample.NoteDatabase.getInstance(NoteDatabase.java:25)
61 at com.emirhalici.notetakingappnvvmexample.NoteRepository.<init>(NoteRepository.java:15)
62 at com.emirhalici.notetakingappnvvmexample.NoteViewModel.<init>(NoteViewModel.java:19)
63 at java.lang.reflect.Constructor.newInstance0(Native Method)
64 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
65 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
66 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
67 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
68 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
69 at android.app.Activity.performCreate(Activity.java:8000)
70 at android.app.Activity.performCreate(Activity.java:7984)
71 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
72 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
73 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
74 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
75 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
76 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
77 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
78 at android.os.Handler.dispatchMessage(Handler.java:106)
79 at android.os.Looper.loop(Looper.java:223)
80 at android.app.ActivityThread.main(ActivityThread.java:7656)
81 at java.lang.reflect.Method.invoke(Native Method)
82 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
83 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
84public class MainActivity extends AppCompatActivity {
85private NoteViewModel noteViewModel;
86
87@Override
88protected void onCreate(Bundle savedInstanceState) {
89 super.onCreate(savedInstanceState);
90 setContentView(R.layout.activity_main);
91
92 // these didn't work
93 //noteViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
94 //noteViewModel = new ViewModelProvider(this).get(NoteViewModel.class);
95 //noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
96 // i tried this but this don't work either
97 noteViewModel = new ViewModelProvider(this,
98 ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
99 noteViewModel.getAllNotes().observe(this, new Observer<List<Note>>() {
100 @Override
101 public void onChanged(List<Note> notes) {
102 // update RecyclerView
103 Toast.makeText(MainActivity.this, "onChanged", Toast.LENGTH_SHORT).show();
104 }
105 });
106} }
107@Entity(tableName = "note_table")
108public class Note {
109
110@PrimaryKey(autoGenerate = true)
111private int id;
112
113private String title;
114private String description;
115private int priority;
116
117// getters
118public int getId() {
119 return id;
120}
121
122public String getTitle() {
123 return title;
124}
125
126public String getDescription() {
127 return description;
128}
129
130public int getPriority() {
131 return priority;
132}
133
134// id setter
135public void setId(int id) {
136 this.id = id;
137}
138
139// constructor
140public Note(String title, String description, int priority) {
141 this.title = title;
142 this.description = description;
143 this.priority = priority;
144}
145
146}
147
NoteDao.java
1 Process: com.emirhalici.notetakingappnvvmexample, PID: 17577
2java.lang.RuntimeException: Unable to start activity ComponentInfo{com.emirhalici.notetakingappnvvmexample/com.emirhalici.notetakingappnvvmexample.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
3 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
4 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
5 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
6 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
7 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
8 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
9 at android.os.Handler.dispatchMessage(Handler.java:106)
10 at android.os.Looper.loop(Looper.java:223)
11 at android.app.ActivityThread.main(ActivityThread.java:7656)
12 at java.lang.reflect.Method.invoke(Native Method)
13 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
14 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
15 Caused by: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
16 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:275)
17 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
18 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
19 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
20 at android.app.Activity.performCreate(Activity.java:8000)
21 at android.app.Activity.performCreate(Activity.java:7984)
22 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
23 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
24 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
25 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
26 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
27 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
28 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
29 at android.os.Handler.dispatchMessage(Handler.java:106)
30 at android.os.Looper.loop(Looper.java:223)
31 at android.app.ActivityThread.main(ActivityThread.java:7656)
32 at java.lang.reflect.Method.invoke(Native Method)
33 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
34 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
35 Caused by: java.lang.reflect.InvocationTargetException
36 at java.lang.reflect.Constructor.newInstance0(Native Method)
37 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
38 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
39 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
40 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
41 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
42 at android.app.Activity.performCreate(Activity.java:8000)
43 at android.app.Activity.performCreate(Activity.java:7984)
44 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
45 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
46 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
47 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
48 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
49 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
50 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
51 at android.os.Handler.dispatchMessage(Handler.java:106)
52 at android.os.Looper.loop(Looper.java:223)
53 at android.app.ActivityThread.main(ActivityThread.java:7656)
54 at java.lang.reflect.Method.invoke(Native Method)
55 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
56 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
57 Caused by: java.lang.RuntimeException: cannot find implementation for com.emirhalici.notetakingappnvvmexample.NoteDatabase. NoteDatabase_Impl does not exist
58 at androidx.room.Room.getGeneratedImplementation(Room.java:97)
59 at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1358)
60 at com.emirhalici.notetakingappnvvmexample.NoteDatabase.getInstance(NoteDatabase.java:25)
61 at com.emirhalici.notetakingappnvvmexample.NoteRepository.<init>(NoteRepository.java:15)
62 at com.emirhalici.notetakingappnvvmexample.NoteViewModel.<init>(NoteViewModel.java:19)
63 at java.lang.reflect.Constructor.newInstance0(Native Method)
64 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
65 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
66 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
67 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
68 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
69 at android.app.Activity.performCreate(Activity.java:8000)
70 at android.app.Activity.performCreate(Activity.java:7984)
71 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
72 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
73 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
74 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
75 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
76 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
77 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
78 at android.os.Handler.dispatchMessage(Handler.java:106)
79 at android.os.Looper.loop(Looper.java:223)
80 at android.app.ActivityThread.main(ActivityThread.java:7656)
81 at java.lang.reflect.Method.invoke(Native Method)
82 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
83 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
84public class MainActivity extends AppCompatActivity {
85private NoteViewModel noteViewModel;
86
87@Override
88protected void onCreate(Bundle savedInstanceState) {
89 super.onCreate(savedInstanceState);
90 setContentView(R.layout.activity_main);
91
92 // these didn't work
93 //noteViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
94 //noteViewModel = new ViewModelProvider(this).get(NoteViewModel.class);
95 //noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
96 // i tried this but this don't work either
97 noteViewModel = new ViewModelProvider(this,
98 ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
99 noteViewModel.getAllNotes().observe(this, new Observer<List<Note>>() {
100 @Override
101 public void onChanged(List<Note> notes) {
102 // update RecyclerView
103 Toast.makeText(MainActivity.this, "onChanged", Toast.LENGTH_SHORT).show();
104 }
105 });
106} }
107@Entity(tableName = "note_table")
108public class Note {
109
110@PrimaryKey(autoGenerate = true)
111private int id;
112
113private String title;
114private String description;
115private int priority;
116
117// getters
118public int getId() {
119 return id;
120}
121
122public String getTitle() {
123 return title;
124}
125
126public String getDescription() {
127 return description;
128}
129
130public int getPriority() {
131 return priority;
132}
133
134// id setter
135public void setId(int id) {
136 this.id = id;
137}
138
139// constructor
140public Note(String title, String description, int priority) {
141 this.title = title;
142 this.description = description;
143 this.priority = priority;
144}
145
146}
147@Dao
148public interface NoteDao {
149
150@Insert
151void insert(Note note);
152
153@Update
154void update(Note note);
155
156@Delete
157void delete(Note note);
158
159@Query("DELETE FROM note_table")
160void deleteAll();
161
162@Query("SELECT * FROM note_table ORDER BY priority DESC")
163LiveData<List<Note>> getAllNotes();
164
165}
166
NoteDatabase.java
1 Process: com.emirhalici.notetakingappnvvmexample, PID: 17577
2java.lang.RuntimeException: Unable to start activity ComponentInfo{com.emirhalici.notetakingappnvvmexample/com.emirhalici.notetakingappnvvmexample.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
3 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
4 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
5 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
6 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
7 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
8 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
9 at android.os.Handler.dispatchMessage(Handler.java:106)
10 at android.os.Looper.loop(Looper.java:223)
11 at android.app.ActivityThread.main(ActivityThread.java:7656)
12 at java.lang.reflect.Method.invoke(Native Method)
13 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
14 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
15 Caused by: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
16 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:275)
17 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
18 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
19 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
20 at android.app.Activity.performCreate(Activity.java:8000)
21 at android.app.Activity.performCreate(Activity.java:7984)
22 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
23 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
24 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
25 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
26 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
27 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
28 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
29 at android.os.Handler.dispatchMessage(Handler.java:106)
30 at android.os.Looper.loop(Looper.java:223)
31 at android.app.ActivityThread.main(ActivityThread.java:7656)
32 at java.lang.reflect.Method.invoke(Native Method)
33 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
34 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
35 Caused by: java.lang.reflect.InvocationTargetException
36 at java.lang.reflect.Constructor.newInstance0(Native Method)
37 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
38 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
39 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
40 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
41 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
42 at android.app.Activity.performCreate(Activity.java:8000)
43 at android.app.Activity.performCreate(Activity.java:7984)
44 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
45 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
46 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
47 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
48 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
49 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
50 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
51 at android.os.Handler.dispatchMessage(Handler.java:106)
52 at android.os.Looper.loop(Looper.java:223)
53 at android.app.ActivityThread.main(ActivityThread.java:7656)
54 at java.lang.reflect.Method.invoke(Native Method)
55 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
56 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
57 Caused by: java.lang.RuntimeException: cannot find implementation for com.emirhalici.notetakingappnvvmexample.NoteDatabase. NoteDatabase_Impl does not exist
58 at androidx.room.Room.getGeneratedImplementation(Room.java:97)
59 at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1358)
60 at com.emirhalici.notetakingappnvvmexample.NoteDatabase.getInstance(NoteDatabase.java:25)
61 at com.emirhalici.notetakingappnvvmexample.NoteRepository.<init>(NoteRepository.java:15)
62 at com.emirhalici.notetakingappnvvmexample.NoteViewModel.<init>(NoteViewModel.java:19)
63 at java.lang.reflect.Constructor.newInstance0(Native Method)
64 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
65 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
66 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
67 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
68 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
69 at android.app.Activity.performCreate(Activity.java:8000)
70 at android.app.Activity.performCreate(Activity.java:7984)
71 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
72 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
73 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
74 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
75 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
76 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
77 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
78 at android.os.Handler.dispatchMessage(Handler.java:106)
79 at android.os.Looper.loop(Looper.java:223)
80 at android.app.ActivityThread.main(ActivityThread.java:7656)
81 at java.lang.reflect.Method.invoke(Native Method)
82 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
83 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
84public class MainActivity extends AppCompatActivity {
85private NoteViewModel noteViewModel;
86
87@Override
88protected void onCreate(Bundle savedInstanceState) {
89 super.onCreate(savedInstanceState);
90 setContentView(R.layout.activity_main);
91
92 // these didn't work
93 //noteViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
94 //noteViewModel = new ViewModelProvider(this).get(NoteViewModel.class);
95 //noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
96 // i tried this but this don't work either
97 noteViewModel = new ViewModelProvider(this,
98 ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
99 noteViewModel.getAllNotes().observe(this, new Observer<List<Note>>() {
100 @Override
101 public void onChanged(List<Note> notes) {
102 // update RecyclerView
103 Toast.makeText(MainActivity.this, "onChanged", Toast.LENGTH_SHORT).show();
104 }
105 });
106} }
107@Entity(tableName = "note_table")
108public class Note {
109
110@PrimaryKey(autoGenerate = true)
111private int id;
112
113private String title;
114private String description;
115private int priority;
116
117// getters
118public int getId() {
119 return id;
120}
121
122public String getTitle() {
123 return title;
124}
125
126public String getDescription() {
127 return description;
128}
129
130public int getPriority() {
131 return priority;
132}
133
134// id setter
135public void setId(int id) {
136 this.id = id;
137}
138
139// constructor
140public Note(String title, String description, int priority) {
141 this.title = title;
142 this.description = description;
143 this.priority = priority;
144}
145
146}
147@Dao
148public interface NoteDao {
149
150@Insert
151void insert(Note note);
152
153@Update
154void update(Note note);
155
156@Delete
157void delete(Note note);
158
159@Query("DELETE FROM note_table")
160void deleteAll();
161
162@Query("SELECT * FROM note_table ORDER BY priority DESC")
163LiveData<List<Note>> getAllNotes();
164
165}
166@Database(entities = Note.class, version = 1)
167public abstract class NoteDatabase extends RoomDatabase {
168
169private static NoteDatabase instance;
170
171public abstract NoteDao noteDao();
172
173public static synchronized NoteDatabase getInstance(Context context) {
174 if (instance == null) {
175 instance = Room.databaseBuilder(context.getApplicationContext(),
176 NoteDatabase.class, "note_database")
177 .fallbackToDestructiveMigration()
178 .addCallback(roomCallback)
179 .build();
180 }
181 return instance;
182}
183
184private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback() {
185 @Override
186 public void onCreate(@NonNull SupportSQLiteDatabase db) {
187 super.onCreate(db);
188 new PopulateDbAsyncTask(instance).execute();
189 }
190};
191
192private static class PopulateDbAsyncTask extends AsyncTask<Void, Void, Void> {
193 private NoteDao noteDao;
194 private PopulateDbAsyncTask(NoteDatabase db) {
195 noteDao = db.noteDao();
196 }
197
198 @Override
199 protected Void doInBackground(Void... voids) {
200 noteDao.insert(new Note("Title 1","Description 1", 1));
201 noteDao.insert(new Note("Title 2","Description 2", 2));
202 noteDao.insert(new Note("Title 3","Description 3", 3));
203 noteDao.insert(new Note("Title 4","Description 4", 1));
204 noteDao.insert(new Note("Title 5","Description 5", 2));
205 noteDao.insert(new Note("Title 6","Description 6", 4));
206 return null;
207 }
208}
209}
210
NoteRepository.java
1 Process: com.emirhalici.notetakingappnvvmexample, PID: 17577
2java.lang.RuntimeException: Unable to start activity ComponentInfo{com.emirhalici.notetakingappnvvmexample/com.emirhalici.notetakingappnvvmexample.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
3 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
4 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
5 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
6 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
7 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
8 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
9 at android.os.Handler.dispatchMessage(Handler.java:106)
10 at android.os.Looper.loop(Looper.java:223)
11 at android.app.ActivityThread.main(ActivityThread.java:7656)
12 at java.lang.reflect.Method.invoke(Native Method)
13 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
14 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
15 Caused by: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
16 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:275)
17 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
18 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
19 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
20 at android.app.Activity.performCreate(Activity.java:8000)
21 at android.app.Activity.performCreate(Activity.java:7984)
22 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
23 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
24 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
25 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
26 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
27 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
28 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
29 at android.os.Handler.dispatchMessage(Handler.java:106)
30 at android.os.Looper.loop(Looper.java:223)
31 at android.app.ActivityThread.main(ActivityThread.java:7656)
32 at java.lang.reflect.Method.invoke(Native Method)
33 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
34 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
35 Caused by: java.lang.reflect.InvocationTargetException
36 at java.lang.reflect.Constructor.newInstance0(Native Method)
37 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
38 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
39 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
40 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
41 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
42 at android.app.Activity.performCreate(Activity.java:8000)
43 at android.app.Activity.performCreate(Activity.java:7984)
44 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
45 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
46 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
47 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
48 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
49 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
50 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
51 at android.os.Handler.dispatchMessage(Handler.java:106)
52 at android.os.Looper.loop(Looper.java:223)
53 at android.app.ActivityThread.main(ActivityThread.java:7656)
54 at java.lang.reflect.Method.invoke(Native Method)
55 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
56 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
57 Caused by: java.lang.RuntimeException: cannot find implementation for com.emirhalici.notetakingappnvvmexample.NoteDatabase. NoteDatabase_Impl does not exist
58 at androidx.room.Room.getGeneratedImplementation(Room.java:97)
59 at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1358)
60 at com.emirhalici.notetakingappnvvmexample.NoteDatabase.getInstance(NoteDatabase.java:25)
61 at com.emirhalici.notetakingappnvvmexample.NoteRepository.<init>(NoteRepository.java:15)
62 at com.emirhalici.notetakingappnvvmexample.NoteViewModel.<init>(NoteViewModel.java:19)
63 at java.lang.reflect.Constructor.newInstance0(Native Method)
64 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
65 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
66 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
67 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
68 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
69 at android.app.Activity.performCreate(Activity.java:8000)
70 at android.app.Activity.performCreate(Activity.java:7984)
71 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
72 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
73 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
74 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
75 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
76 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
77 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
78 at android.os.Handler.dispatchMessage(Handler.java:106)
79 at android.os.Looper.loop(Looper.java:223)
80 at android.app.ActivityThread.main(ActivityThread.java:7656)
81 at java.lang.reflect.Method.invoke(Native Method)
82 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
83 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
84public class MainActivity extends AppCompatActivity {
85private NoteViewModel noteViewModel;
86
87@Override
88protected void onCreate(Bundle savedInstanceState) {
89 super.onCreate(savedInstanceState);
90 setContentView(R.layout.activity_main);
91
92 // these didn't work
93 //noteViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
94 //noteViewModel = new ViewModelProvider(this).get(NoteViewModel.class);
95 //noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
96 // i tried this but this don't work either
97 noteViewModel = new ViewModelProvider(this,
98 ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
99 noteViewModel.getAllNotes().observe(this, new Observer<List<Note>>() {
100 @Override
101 public void onChanged(List<Note> notes) {
102 // update RecyclerView
103 Toast.makeText(MainActivity.this, "onChanged", Toast.LENGTH_SHORT).show();
104 }
105 });
106} }
107@Entity(tableName = "note_table")
108public class Note {
109
110@PrimaryKey(autoGenerate = true)
111private int id;
112
113private String title;
114private String description;
115private int priority;
116
117// getters
118public int getId() {
119 return id;
120}
121
122public String getTitle() {
123 return title;
124}
125
126public String getDescription() {
127 return description;
128}
129
130public int getPriority() {
131 return priority;
132}
133
134// id setter
135public void setId(int id) {
136 this.id = id;
137}
138
139// constructor
140public Note(String title, String description, int priority) {
141 this.title = title;
142 this.description = description;
143 this.priority = priority;
144}
145
146}
147@Dao
148public interface NoteDao {
149
150@Insert
151void insert(Note note);
152
153@Update
154void update(Note note);
155
156@Delete
157void delete(Note note);
158
159@Query("DELETE FROM note_table")
160void deleteAll();
161
162@Query("SELECT * FROM note_table ORDER BY priority DESC")
163LiveData<List<Note>> getAllNotes();
164
165}
166@Database(entities = Note.class, version = 1)
167public abstract class NoteDatabase extends RoomDatabase {
168
169private static NoteDatabase instance;
170
171public abstract NoteDao noteDao();
172
173public static synchronized NoteDatabase getInstance(Context context) {
174 if (instance == null) {
175 instance = Room.databaseBuilder(context.getApplicationContext(),
176 NoteDatabase.class, "note_database")
177 .fallbackToDestructiveMigration()
178 .addCallback(roomCallback)
179 .build();
180 }
181 return instance;
182}
183
184private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback() {
185 @Override
186 public void onCreate(@NonNull SupportSQLiteDatabase db) {
187 super.onCreate(db);
188 new PopulateDbAsyncTask(instance).execute();
189 }
190};
191
192private static class PopulateDbAsyncTask extends AsyncTask<Void, Void, Void> {
193 private NoteDao noteDao;
194 private PopulateDbAsyncTask(NoteDatabase db) {
195 noteDao = db.noteDao();
196 }
197
198 @Override
199 protected Void doInBackground(Void... voids) {
200 noteDao.insert(new Note("Title 1","Description 1", 1));
201 noteDao.insert(new Note("Title 2","Description 2", 2));
202 noteDao.insert(new Note("Title 3","Description 3", 3));
203 noteDao.insert(new Note("Title 4","Description 4", 1));
204 noteDao.insert(new Note("Title 5","Description 5", 2));
205 noteDao.insert(new Note("Title 6","Description 6", 4));
206 return null;
207 }
208}
209}
210public class NoteRepository {
211private NoteDao noteDao;
212private LiveData<List<Note>> allNotes;
213
214public NoteRepository(Application application) {
215 NoteDatabase database = NoteDatabase.getInstance(application);
216 noteDao = database.noteDao();
217 allNotes = noteDao.getAllNotes();
218}
219
220public void insert(Note note) {
221 new InsertNoteAsyncTask(noteDao).execute(note);
222}
223
224public void update(Note note) {
225 new UpdateNoteAsyncTask(noteDao).execute(note);
226}
227
228public void delete(Note note) {
229 new DeleteNoteAsyncTask(noteDao).execute(note);
230}
231
232public void deleteAll() {
233 new DeleteAllNotesAsyncTask(noteDao).execute();
234}
235
236public LiveData<List<Note>> getAllNotes() {
237 return allNotes;
238}
239
240private static class InsertNoteAsyncTask extends AsyncTask<Note, Void, Void> {
241 private NoteDao noteDao;
242
243 private InsertNoteAsyncTask(NoteDao noteDao) {
244 this.noteDao = noteDao;
245 }
246
247 @Override
248 protected Void doInBackground(Note... notes) {
249 noteDao.insert(notes[0]);
250 return null;
251 }
252}
253
254private static class UpdateNoteAsyncTask extends AsyncTask<Note, Void, Void> {
255 private NoteDao noteDao;
256
257 private UpdateNoteAsyncTask(NoteDao noteDao) {
258 this.noteDao = noteDao;
259 }
260
261 @Override
262 protected Void doInBackground(Note... notes) {
263 noteDao.update(notes[0]);
264 return null;
265 }
266}
267
268private static class DeleteNoteAsyncTask extends AsyncTask<Note, Void, Void> {
269 private NoteDao noteDao;
270
271 private DeleteNoteAsyncTask(NoteDao noteDao) {
272 this.noteDao = noteDao;
273 }
274
275 @Override
276 protected Void doInBackground(Note... notes) {
277 noteDao.delete(notes[0]);
278 return null;
279 }
280}
281
282private static class DeleteAllNotesAsyncTask extends AsyncTask<Note, Void, Void> {
283 private NoteDao noteDao;
284
285 private DeleteAllNotesAsyncTask(NoteDao noteDao) {
286 this.noteDao = noteDao;
287 }
288
289 @Override
290 protected Void doInBackground(Note... voids) {
291 noteDao.deleteAll();
292 return null;
293 }
294}
295}
296
NoteViewModel.java
1 Process: com.emirhalici.notetakingappnvvmexample, PID: 17577
2java.lang.RuntimeException: Unable to start activity ComponentInfo{com.emirhalici.notetakingappnvvmexample/com.emirhalici.notetakingappnvvmexample.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
3 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
4 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
5 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
6 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
7 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
8 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
9 at android.os.Handler.dispatchMessage(Handler.java:106)
10 at android.os.Looper.loop(Looper.java:223)
11 at android.app.ActivityThread.main(ActivityThread.java:7656)
12 at java.lang.reflect.Method.invoke(Native Method)
13 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
14 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
15 Caused by: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
16 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:275)
17 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
18 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
19 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
20 at android.app.Activity.performCreate(Activity.java:8000)
21 at android.app.Activity.performCreate(Activity.java:7984)
22 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
23 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
24 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
25 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
26 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
27 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
28 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
29 at android.os.Handler.dispatchMessage(Handler.java:106)
30 at android.os.Looper.loop(Looper.java:223)
31 at android.app.ActivityThread.main(ActivityThread.java:7656)
32 at java.lang.reflect.Method.invoke(Native Method)
33 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
34 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
35 Caused by: java.lang.reflect.InvocationTargetException
36 at java.lang.reflect.Constructor.newInstance0(Native Method)
37 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
38 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
39 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
40 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
41 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
42 at android.app.Activity.performCreate(Activity.java:8000)
43 at android.app.Activity.performCreate(Activity.java:7984)
44 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
45 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
46 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
47 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
48 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
49 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
50 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
51 at android.os.Handler.dispatchMessage(Handler.java:106)
52 at android.os.Looper.loop(Looper.java:223)
53 at android.app.ActivityThread.main(ActivityThread.java:7656)
54 at java.lang.reflect.Method.invoke(Native Method)
55 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
56 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
57 Caused by: java.lang.RuntimeException: cannot find implementation for com.emirhalici.notetakingappnvvmexample.NoteDatabase. NoteDatabase_Impl does not exist
58 at androidx.room.Room.getGeneratedImplementation(Room.java:97)
59 at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1358)
60 at com.emirhalici.notetakingappnvvmexample.NoteDatabase.getInstance(NoteDatabase.java:25)
61 at com.emirhalici.notetakingappnvvmexample.NoteRepository.<init>(NoteRepository.java:15)
62 at com.emirhalici.notetakingappnvvmexample.NoteViewModel.<init>(NoteViewModel.java:19)
63 at java.lang.reflect.Constructor.newInstance0(Native Method)
64 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
65 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
66 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
67 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
68 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
69 at android.app.Activity.performCreate(Activity.java:8000)
70 at android.app.Activity.performCreate(Activity.java:7984)
71 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
72 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
73 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
74 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
75 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
76 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
77 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
78 at android.os.Handler.dispatchMessage(Handler.java:106)
79 at android.os.Looper.loop(Looper.java:223)
80 at android.app.ActivityThread.main(ActivityThread.java:7656)
81 at java.lang.reflect.Method.invoke(Native Method)
82 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
83 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
84public class MainActivity extends AppCompatActivity {
85private NoteViewModel noteViewModel;
86
87@Override
88protected void onCreate(Bundle savedInstanceState) {
89 super.onCreate(savedInstanceState);
90 setContentView(R.layout.activity_main);
91
92 // these didn't work
93 //noteViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
94 //noteViewModel = new ViewModelProvider(this).get(NoteViewModel.class);
95 //noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
96 // i tried this but this don't work either
97 noteViewModel = new ViewModelProvider(this,
98 ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
99 noteViewModel.getAllNotes().observe(this, new Observer<List<Note>>() {
100 @Override
101 public void onChanged(List<Note> notes) {
102 // update RecyclerView
103 Toast.makeText(MainActivity.this, "onChanged", Toast.LENGTH_SHORT).show();
104 }
105 });
106} }
107@Entity(tableName = "note_table")
108public class Note {
109
110@PrimaryKey(autoGenerate = true)
111private int id;
112
113private String title;
114private String description;
115private int priority;
116
117// getters
118public int getId() {
119 return id;
120}
121
122public String getTitle() {
123 return title;
124}
125
126public String getDescription() {
127 return description;
128}
129
130public int getPriority() {
131 return priority;
132}
133
134// id setter
135public void setId(int id) {
136 this.id = id;
137}
138
139// constructor
140public Note(String title, String description, int priority) {
141 this.title = title;
142 this.description = description;
143 this.priority = priority;
144}
145
146}
147@Dao
148public interface NoteDao {
149
150@Insert
151void insert(Note note);
152
153@Update
154void update(Note note);
155
156@Delete
157void delete(Note note);
158
159@Query("DELETE FROM note_table")
160void deleteAll();
161
162@Query("SELECT * FROM note_table ORDER BY priority DESC")
163LiveData<List<Note>> getAllNotes();
164
165}
166@Database(entities = Note.class, version = 1)
167public abstract class NoteDatabase extends RoomDatabase {
168
169private static NoteDatabase instance;
170
171public abstract NoteDao noteDao();
172
173public static synchronized NoteDatabase getInstance(Context context) {
174 if (instance == null) {
175 instance = Room.databaseBuilder(context.getApplicationContext(),
176 NoteDatabase.class, "note_database")
177 .fallbackToDestructiveMigration()
178 .addCallback(roomCallback)
179 .build();
180 }
181 return instance;
182}
183
184private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback() {
185 @Override
186 public void onCreate(@NonNull SupportSQLiteDatabase db) {
187 super.onCreate(db);
188 new PopulateDbAsyncTask(instance).execute();
189 }
190};
191
192private static class PopulateDbAsyncTask extends AsyncTask<Void, Void, Void> {
193 private NoteDao noteDao;
194 private PopulateDbAsyncTask(NoteDatabase db) {
195 noteDao = db.noteDao();
196 }
197
198 @Override
199 protected Void doInBackground(Void... voids) {
200 noteDao.insert(new Note("Title 1","Description 1", 1));
201 noteDao.insert(new Note("Title 2","Description 2", 2));
202 noteDao.insert(new Note("Title 3","Description 3", 3));
203 noteDao.insert(new Note("Title 4","Description 4", 1));
204 noteDao.insert(new Note("Title 5","Description 5", 2));
205 noteDao.insert(new Note("Title 6","Description 6", 4));
206 return null;
207 }
208}
209}
210public class NoteRepository {
211private NoteDao noteDao;
212private LiveData<List<Note>> allNotes;
213
214public NoteRepository(Application application) {
215 NoteDatabase database = NoteDatabase.getInstance(application);
216 noteDao = database.noteDao();
217 allNotes = noteDao.getAllNotes();
218}
219
220public void insert(Note note) {
221 new InsertNoteAsyncTask(noteDao).execute(note);
222}
223
224public void update(Note note) {
225 new UpdateNoteAsyncTask(noteDao).execute(note);
226}
227
228public void delete(Note note) {
229 new DeleteNoteAsyncTask(noteDao).execute(note);
230}
231
232public void deleteAll() {
233 new DeleteAllNotesAsyncTask(noteDao).execute();
234}
235
236public LiveData<List<Note>> getAllNotes() {
237 return allNotes;
238}
239
240private static class InsertNoteAsyncTask extends AsyncTask<Note, Void, Void> {
241 private NoteDao noteDao;
242
243 private InsertNoteAsyncTask(NoteDao noteDao) {
244 this.noteDao = noteDao;
245 }
246
247 @Override
248 protected Void doInBackground(Note... notes) {
249 noteDao.insert(notes[0]);
250 return null;
251 }
252}
253
254private static class UpdateNoteAsyncTask extends AsyncTask<Note, Void, Void> {
255 private NoteDao noteDao;
256
257 private UpdateNoteAsyncTask(NoteDao noteDao) {
258 this.noteDao = noteDao;
259 }
260
261 @Override
262 protected Void doInBackground(Note... notes) {
263 noteDao.update(notes[0]);
264 return null;
265 }
266}
267
268private static class DeleteNoteAsyncTask extends AsyncTask<Note, Void, Void> {
269 private NoteDao noteDao;
270
271 private DeleteNoteAsyncTask(NoteDao noteDao) {
272 this.noteDao = noteDao;
273 }
274
275 @Override
276 protected Void doInBackground(Note... notes) {
277 noteDao.delete(notes[0]);
278 return null;
279 }
280}
281
282private static class DeleteAllNotesAsyncTask extends AsyncTask<Note, Void, Void> {
283 private NoteDao noteDao;
284
285 private DeleteAllNotesAsyncTask(NoteDao noteDao) {
286 this.noteDao = noteDao;
287 }
288
289 @Override
290 protected Void doInBackground(Note... voids) {
291 noteDao.deleteAll();
292 return null;
293 }
294}
295}
296public class NoteViewModel extends AndroidViewModel {
297private NoteRepository repository;
298private LiveData<List<Note>> allNotes;
299
300public NoteViewModel(@NonNull Application application) {
301 super(application);
302 repository = new NoteRepository(application);
303 allNotes = repository.getAllNotes();
304}
305
306public void insert(Note note) {
307 repository.insert(note);
308}
309
310public void update(Note note) {
311 repository.update(note);
312}
313
314public void delete(Note note) {
315 repository.delete(note);
316}
317
318public void deleteAllNotes() {
319 repository.deleteAll();
320}
321
322public LiveData<List<Note>> getAllNotes() {
323 return allNotes;
324}
325
326}
327
ANSWER
Answered 2021-May-09 at 07:58Let me start off by saying CodeInFlow
is a great source to learn from I've used him lots to help build my knowledge, Codelabs are also great and frequently updated by the Android dev team. If you are starting out I would recommend learning Kotlin over java, Kotlin is the future of android and recommend language by the Android Dev Team.
This is how you get a new or existing ViewModel.
1 Process: com.emirhalici.notetakingappnvvmexample, PID: 17577
2java.lang.RuntimeException: Unable to start activity ComponentInfo{com.emirhalici.notetakingappnvvmexample/com.emirhalici.notetakingappnvvmexample.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
3 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
4 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
5 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
6 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
7 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
8 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
9 at android.os.Handler.dispatchMessage(Handler.java:106)
10 at android.os.Looper.loop(Looper.java:223)
11 at android.app.ActivityThread.main(ActivityThread.java:7656)
12 at java.lang.reflect.Method.invoke(Native Method)
13 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
14 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
15 Caused by: java.lang.RuntimeException: Cannot create an instance of class com.emirhalici.notetakingappnvvmexample.NoteViewModel
16 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:275)
17 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
18 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
19 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
20 at android.app.Activity.performCreate(Activity.java:8000)
21 at android.app.Activity.performCreate(Activity.java:7984)
22 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
23 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
24 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
25 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
26 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
27 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
28 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
29 at android.os.Handler.dispatchMessage(Handler.java:106)
30 at android.os.Looper.loop(Looper.java:223)
31 at android.app.ActivityThread.main(ActivityThread.java:7656)
32 at java.lang.reflect.Method.invoke(Native Method)
33 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
34 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
35 Caused by: java.lang.reflect.InvocationTargetException
36 at java.lang.reflect.Constructor.newInstance0(Native Method)
37 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
38 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
39 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
40 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
41 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
42 at android.app.Activity.performCreate(Activity.java:8000)
43 at android.app.Activity.performCreate(Activity.java:7984)
44 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
45 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
46 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
47 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
48 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
49 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
50 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
51 at android.os.Handler.dispatchMessage(Handler.java:106)
52 at android.os.Looper.loop(Looper.java:223)
53 at android.app.ActivityThread.main(ActivityThread.java:7656)
54 at java.lang.reflect.Method.invoke(Native Method)
55 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
56 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
57 Caused by: java.lang.RuntimeException: cannot find implementation for com.emirhalici.notetakingappnvvmexample.NoteDatabase. NoteDatabase_Impl does not exist
58 at androidx.room.Room.getGeneratedImplementation(Room.java:97)
59 at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1358)
60 at com.emirhalici.notetakingappnvvmexample.NoteDatabase.getInstance(NoteDatabase.java:25)
61 at com.emirhalici.notetakingappnvvmexample.NoteRepository.<init>(NoteRepository.java:15)
62 at com.emirhalici.notetakingappnvvmexample.NoteViewModel.<init>(NoteViewModel.java:19)
63 at java.lang.reflect.Constructor.newInstance0(Native Method)
64 at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
65 at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
66 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
67 at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
68 at com.emirhalici.notetakingappnvvmexample.MainActivity.onCreate(MainActivity.java:26)
69 at android.app.Activity.performCreate(Activity.java:8000)
70 at android.app.Activity.performCreate(Activity.java:7984)
71 at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
72 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
73 at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
74 at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
75 at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
76 at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
77 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
78 at android.os.Handler.dispatchMessage(Handler.java:106)
79 at android.os.Looper.loop(Looper.java:223)
80 at android.app.ActivityThread.main(ActivityThread.java:7656)
81 at java.lang.reflect.Method.invoke(Native Method)
82 at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
83 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
84public class MainActivity extends AppCompatActivity {
85private NoteViewModel noteViewModel;
86
87@Override
88protected void onCreate(Bundle savedInstanceState) {
89 super.onCreate(savedInstanceState);
90 setContentView(R.layout.activity_main);
91
92 // these didn't work
93 //noteViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
94 //noteViewModel = new ViewModelProvider(this).get(NoteViewModel.class);
95 //noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
96 // i tried this but this don't work either
97 noteViewModel = new ViewModelProvider(this,
98 ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
99 noteViewModel.getAllNotes().observe(this, new Observer<List<Note>>() {
100 @Override
101 public void onChanged(List<Note> notes) {
102 // update RecyclerView
103 Toast.makeText(MainActivity.this, "onChanged", Toast.LENGTH_SHORT).show();
104 }
105 });
106} }
107@Entity(tableName = "note_table")
108public class Note {
109
110@PrimaryKey(autoGenerate = true)
111private int id;
112
113private String title;
114private String description;
115private int priority;
116
117// getters
118public int getId() {
119 return id;
120}
121
122public String getTitle() {
123 return title;
124}
125
126public String getDescription() {
127 return description;
128}
129
130public int getPriority() {
131 return priority;
132}
133
134// id setter
135public void setId(int id) {
136 this.id = id;
137}
138
139// constructor
140public Note(String title, String description, int priority) {
141 this.title = title;
142 this.description = description;
143 this.priority = priority;
144}
145
146}
147@Dao
148public interface NoteDao {
149
150@Insert
151void insert(Note note);
152
153@Update
154void update(Note note);
155
156@Delete
157void delete(Note note);
158
159@Query("DELETE FROM note_table")
160void deleteAll();
161
162@Query("SELECT * FROM note_table ORDER BY priority DESC")
163LiveData<List<Note>> getAllNotes();
164
165}
166@Database(entities = Note.class, version = 1)
167public abstract class NoteDatabase extends RoomDatabase {
168
169private static NoteDatabase instance;
170
171public abstract NoteDao noteDao();
172
173public static synchronized NoteDatabase getInstance(Context context) {
174 if (instance == null) {
175 instance = Room.databaseBuilder(context.getApplicationContext(),
176 NoteDatabase.class, "note_database")
177 .fallbackToDestructiveMigration()
178 .addCallback(roomCallback)
179 .build();
180 }
181 return instance;
182}
183
184private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback() {
185 @Override
186 public void onCreate(@NonNull SupportSQLiteDatabase db) {
187 super.onCreate(db);
188 new PopulateDbAsyncTask(instance).execute();
189 }
190};
191
192private static class PopulateDbAsyncTask extends AsyncTask<Void, Void, Void> {
193 private NoteDao noteDao;
194 private PopulateDbAsyncTask(NoteDatabase db) {
195 noteDao = db.noteDao();
196 }
197
198 @Override
199 protected Void doInBackground(Void... voids) {
200 noteDao.insert(new Note("Title 1","Description 1", 1));
201 noteDao.insert(new Note("Title 2","Description 2", 2));
202 noteDao.insert(new Note("Title 3","Description 3", 3));
203 noteDao.insert(new Note("Title 4","Description 4", 1));
204 noteDao.insert(new Note("Title 5","Description 5", 2));
205 noteDao.insert(new Note("Title 6","Description 6", 4));
206 return null;
207 }
208}
209}
210public class NoteRepository {
211private NoteDao noteDao;
212private LiveData<List<Note>> allNotes;
213
214public NoteRepository(Application application) {
215 NoteDatabase database = NoteDatabase.getInstance(application);
216 noteDao = database.noteDao();
217 allNotes = noteDao.getAllNotes();
218}
219
220public void insert(Note note) {
221 new InsertNoteAsyncTask(noteDao).execute(note);
222}
223
224public void update(Note note) {
225 new UpdateNoteAsyncTask(noteDao).execute(note);
226}
227
228public void delete(Note note) {
229 new DeleteNoteAsyncTask(noteDao).execute(note);
230}
231
232public void deleteAll() {
233 new DeleteAllNotesAsyncTask(noteDao).execute();
234}
235
236public LiveData<List<Note>> getAllNotes() {
237 return allNotes;
238}
239
240private static class InsertNoteAsyncTask extends AsyncTask<Note, Void, Void> {
241 private NoteDao noteDao;
242
243 private InsertNoteAsyncTask(NoteDao noteDao) {
244 this.noteDao = noteDao;
245 }
246
247 @Override
248 protected Void doInBackground(Note... notes) {
249 noteDao.insert(notes[0]);
250 return null;
251 }
252}
253
254private static class UpdateNoteAsyncTask extends AsyncTask<Note, Void, Void> {
255 private NoteDao noteDao;
256
257 private UpdateNoteAsyncTask(NoteDao noteDao) {
258 this.noteDao = noteDao;
259 }
260
261 @Override
262 protected Void doInBackground(Note... notes) {
263 noteDao.update(notes[0]);
264 return null;
265 }
266}
267
268private static class DeleteNoteAsyncTask extends AsyncTask<Note, Void, Void> {
269 private NoteDao noteDao;
270
271 private DeleteNoteAsyncTask(NoteDao noteDao) {
272 this.noteDao = noteDao;
273 }
274
275 @Override
276 protected Void doInBackground(Note... notes) {
277 noteDao.delete(notes[0]);
278 return null;
279 }
280}
281
282private static class DeleteAllNotesAsyncTask extends AsyncTask<Note, Void, Void> {
283 private NoteDao noteDao;
284
285 private DeleteAllNotesAsyncTask(NoteDao noteDao) {
286 this.noteDao = noteDao;
287 }
288
289 @Override
290 protected Void doInBackground(Note... voids) {
291 noteDao.deleteAll();
292 return null;
293 }
294}
295}
296public class NoteViewModel extends AndroidViewModel {
297private NoteRepository repository;
298private LiveData<List<Note>> allNotes;
299
300public NoteViewModel(@NonNull Application application) {
301 super(application);
302 repository = new NoteRepository(application);
303 allNotes = repository.getAllNotes();
304}
305
306public void insert(Note note) {
307 repository.insert(note);
308}
309
310public void update(Note note) {
311 repository.update(note);
312}
313
314public void delete(Note note) {
315 repository.delete(note);
316}
317
318public void deleteAllNotes() {
319 repository.deleteAll();
320}
321
322public LiveData<List<Note>> getAllNotes() {
323 return allNotes;
324}
325
326}
327NoteViewModel viewModel = new ViewModelProvider(this).get(NoteViewModel.class);
328
Using a custom ViewModel Factory is not necessary for this project. You would only want to use custom ViewModel Factory if you are passing an argument into the ViewModel constructor.
QUESTION
Android MVVM: how to avoid multiple livedata triggers when data from network did not change
Asked 2021-May-03 at 14:33I have this basic Android Architecture Component use-case where I observe a live-data and update UI.
1 myLiveData.observe(viewLifecycleOwner, Observer {
2 // update UI
3 })
4
5 // will trigger a network call and update the repository (Room DB)
6 myViewModel.refreshDataFromRepository()
7
With the observe call, I get the trigger and I update the UI, which is fine. However, I also need to update the DB if the backend data has changed, so I trigger a network refresh and that updates the DB and triggers the observer once again. So, I am getting data twice.
I can change conflict strategy to ignore to avoid but I need to set it to "replace" as the data may change:
1 myLiveData.observe(viewLifecycleOwner, Observer {
2 // update UI
3 })
4
5 // will trigger a network call and update the repository (Room DB)
6 myViewModel.refreshDataFromRepository()
7@Query("SELECT * FROM my_table ORDER BY timestamp DESC")
8fun getMyEntities(): LiveData<List<MyEntity>>
9
10@Insert(onConflict = OnConflictStrategy.REPLACE)
11suspend fun add(myEntity: MyEntity)
12
Other option is to compare the network response with DB contents and avoid re-writing identical data but would be expensive.
Is there any way, database access can be made intelligent to avoid trigger if data has not changed?
ANSWER
Answered 2021-May-03 at 14:33You could use distinctUntilChanged, it has been added to Transformations:
1 myLiveData.observe(viewLifecycleOwner, Observer {
2 // update UI
3 })
4
5 // will trigger a network call and update the repository (Room DB)
6 myViewModel.refreshDataFromRepository()
7@Query("SELECT * FROM my_table ORDER BY timestamp DESC")
8fun getMyEntities(): LiveData<List<MyEntity>>
9
10@Insert(onConflict = OnConflictStrategy.REPLACE)
11suspend fun add(myEntity: MyEntity)
12myLiveData.distinctUntilChanged().observe(viewLifecycleOwner) {
13 // update UI
14 }
15
QUESTION
Can I add Observer inside Observer? I actually tried but inner observers not working properly. Sometimes one of them work, sometimes no one work
Asked 2021-Apr-09 at 10:27I used Android Architecture Components (ViewModel, LiveData) and used Room to fetch data from Local Sqlite Database using Repository. Outermost observer just fine, problem is only with inner observers.
See the Code:
1 @Override
2 public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
3 super.onViewCreated(view, savedInstanceState);
4 BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);
5
6 Observer<Bank> bankObserver = new Observer<Bank>() {
7 @Override
8 public void onChanged(Bank bank) {
9 if(bank!= null)
10 binding.tvBank.setText(bank.getBank());
11 }
12 };
13
14
15 branchDetailsViewModel.getBranchById(branchIid).observe(this, new Observer<Branch>() {
16 @Override
17 public void onChanged(Branch branch) {
18
19 branchDetailsViewModel.getBankById(branch.getBankId()).observe(getViewLifecycleOwner(), bankObserver);
20
21 branchDetailsViewModel.getCityById(branch.getCityId()).observe(requireActivity(), new Observer<City>() {
22 @Override
23 public void onChanged(City city) {
24 if(city != null)
25 binding.tvCity.setText(city.getCity() + " cty");
26 }
27 });
28
29 branchDetailsViewModel.getDistrictById(branch.getDistrictId()).observe(requireActivity(), new Observer<District>() {
30 @Override
31 public void onChanged(District district) {
32 if(district != null)
33 binding.tvDistrict.setText(district.getDistrict());
34 }
35 });
36
37 branchDetailsViewModel.getStateById(branch.getStateId()).observe(requireActivity(), new Observer<State>() {
38 @Override
39 public void onChanged(State state) {
40 if(state!= null)
41 binding.tvState.setText(state.getState());
42 }
43 });
44 }
45 });
46 }
47
I tried it both using named and anonymous Observers. I can't understand what is the problem here.
Sometimes it thorow NullPointerExceptions. Sometimes Failed to change locale.
1 @Override
2 public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
3 super.onViewCreated(view, savedInstanceState);
4 BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);
5
6 Observer<Bank> bankObserver = new Observer<Bank>() {
7 @Override
8 public void onChanged(Bank bank) {
9 if(bank!= null)
10 binding.tvBank.setText(bank.getBank());
11 }
12 };
13
14
15 branchDetailsViewModel.getBranchById(branchIid).observe(this, new Observer<Branch>() {
16 @Override
17 public void onChanged(Branch branch) {
18
19 branchDetailsViewModel.getBankById(branch.getBankId()).observe(getViewLifecycleOwner(), bankObserver);
20
21 branchDetailsViewModel.getCityById(branch.getCityId()).observe(requireActivity(), new Observer<City>() {
22 @Override
23 public void onChanged(City city) {
24 if(city != null)
25 binding.tvCity.setText(city.getCity() + " cty");
26 }
27 });
28
29 branchDetailsViewModel.getDistrictById(branch.getDistrictId()).observe(requireActivity(), new Observer<District>() {
30 @Override
31 public void onChanged(District district) {
32 if(district != null)
33 binding.tvDistrict.setText(district.getDistrict());
34 }
35 });
36
37 branchDetailsViewModel.getStateById(branch.getStateId()).observe(requireActivity(), new Observer<State>() {
38 @Override
39 public void onChanged(State state) {
40 if(state!= null)
41 binding.tvState.setText(state.getState());
42 }
43 });
44 }
45 });
46 }
4704-09 15:48:45.182 2096-2113/com.appsbharti.bharatbankdetails E/SQLiteDatabase: Failed to open database '/data/data/com.appsbharti.bharatbankdetails/databases/bank_details.db'.
48 android.database.sqlite.SQLiteException: Failed to change locale for db '/data/data/com.appsbharti.bharatbankdetails/databases/bank_details.db' to 'en_IN'.
49 at android.database.sqlite.SQLiteConnection.setLocaleFromConfiguration(SQLiteConnection.java:386)
50 at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:218)
51 at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
52 at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
53 at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
54 at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
55 at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
56 at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
57 at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
58 at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:804)
59 at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:221)
60 at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
61 at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
62 at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:92)
63 at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:53)
64 at androidx.room.SQLiteCopyOpenHelper.getWritableDatabase(SQLiteCopyOpenHelper.java:90)
65 at androidx.room.RoomDatabase.inTransaction(RoomDatabase.java:476)
66 at androidx.room.RoomDatabase.assertNotSuspendingTransaction(RoomDatabase.java:281)
67 at com.appsbharti.bharatbankdetails.Daos.HistoryDao_Impl.insert(HistoryDao_Impl.java:45)
68 at com.appsbharti.bharatbankdetails.Repositories.HistoryRepository$1.run(HistoryRepository.java:37)
69 at androidx.room.TransactionExecutor$1.run(TransactionExecutor.java:45)
70 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
71 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
72 at java.lang.Thread.run(Thread.java:856)
73 Caused by: android.database.sqlite.SQLiteDiskIOException: disk I/O error (code 1802)
74 at android.database.sqlite.SQLiteConnection.nativeExecute(Native Method)
75 at android.database.sqlite.SQLiteConnection.execute(SQLiteConnection.java:548)
76 at android.database.sqlite.SQLiteConnection.setLocaleFromConfiguration(SQLiteConnection.java:364)
77 at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:218)
78 at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
79 at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
80 at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
81 at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
82 at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
83 at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
84 at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
85 at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:804)
86 at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:221)
87 at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:224)
88 at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
89 at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:92)
90 at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:53)
91 at androidx.room.SQLiteCopyOpenHelper.getWritableDatabase(SQLiteCopyOpenHelper.java:90)
92 at androidx.room.RoomDatabase.inTransaction(RoomDatabase.java:476)
93 at androidx.room.RoomDatabase.assertNotSuspendingTransaction(RoomDatabase.java:281)
94 at com.appsbharti.bharatbankdetails.Daos.HistoryDao_Impl.insert(HistoryDao_Impl.java:45)
95 at com.appsbharti.bharatbankdetails.Repositories.HistoryRepository$1.run(HistoryRepository.java:37)
96 at androidx.room.TransactionExecutor$1.run(TransactionExecutor.java:45)
97 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
98 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
99 at java.lang.Thread.run(Thread.java:856)
100
One more issue is that I am unsure which one I should use in Fragment as Observer's owner, requireActivity()
or getActivity()
(I get warning that this could return null, so I haven't used it) or getViewLifecycleOwner()
(to get fragment's life cycle owner object).
ANSWER
Answered 2021-Apr-01 at 08:57If you are inside a Fragment, you cannot pass this
to observe, you should be passing viewlifecycleOwner
. In your case you are setting an observe to get the value of branch from room, and then depending on the branch, your other observers are getting called.
This means that your inside observers will observe after your branch
observer has been invoked.
When you bind your observers to the lifecycle of the fragment, the observers work in accordance with the lifecycle of the fragment itself.
Binding it with lifecycleowner should work, mainly because this
does not work in case of fragment.
QUESTION
Why I am facing threading issues despite using room database TransactionExecutor?
Asked 2021-Apr-07 at 13:14I have 2 fragments. One is showing Branch Details, other is showing showing branches viewed in history. I want to add entry whenver user see branch details.
I am following Android Architecture principles and using Room+LiveData+Repository+Viewmodel.
Here is BranchDetailsFragment:
1public class BranchDetailsFragment extends Fragment implements View.OnClickListener {
2
3 private final Application application;
4 private final int branchIid;
5
6 private FragBranchDetailsBinding binding;//view-binding
7
8 public BranchDetailsFragment(Application application, int branchIid) {
9 //saving branchId
10 }
11
12 @Nullable
13 @Override
14 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
15 //normal stuff
16 }
17
18 @Override
19 public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
20 super.onViewCreated(view, savedInstanceState);
21 BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);
22
23 //inserting entry in history table
24 HistoryViewModel historyViewModel = new HistoryViewModel(application);
25 History history = new History();
26 history.setBranchId(branchIid);
27 historyViewModel.insert(history);
28
29 //fetching data from branches table
30 branchDetailsViewModel.getBranchCustomizedById(branchIid).observe(getViewLifecycleOwner(), new Observer<BranchCustomized>() {
31 @Override
32 public void onChanged(BranchCustomized branchCustomized) {
33 //get branch details and show them
34 }
35 });
36 }
37}
38
Here is the Branch POJO Room Entity:
1public class BranchDetailsFragment extends Fragment implements View.OnClickListener {
2
3 private final Application application;
4 private final int branchIid;
5
6 private FragBranchDetailsBinding binding;//view-binding
7
8 public BranchDetailsFragment(Application application, int branchIid) {
9 //saving branchId
10 }
11
12 @Nullable
13 @Override
14 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
15 //normal stuff
16 }
17
18 @Override
19 public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
20 super.onViewCreated(view, savedInstanceState);
21 BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);
22
23 //inserting entry in history table
24 HistoryViewModel historyViewModel = new HistoryViewModel(application);
25 History history = new History();
26 history.setBranchId(branchIid);
27 historyViewModel.insert(history);
28
29 //fetching data from branches table
30 branchDetailsViewModel.getBranchCustomizedById(branchIid).observe(getViewLifecycleOwner(), new Observer<BranchCustomized>() {
31 @Override
32 public void onChanged(BranchCustomized branchCustomized) {
33 //get branch details and show them
34 }
35 });
36 }
37}
38@Entity(tableName = "branches")
39public class Branch {
40 @PrimaryKey(autoGenerate = true)
41 @ColumnInfo(name = "_id")
42 private int id;
43
44 @ColumnInfo(name = "bank_id")
45 private int bankId;
46
47 public int getId() {
48 return id;
49 }
50
51 public void setId(int id) {
52 this.id = id;
53 }
54
55 public int getBankId() {
56 return bankId;
57 }
58
59 public void setBankId(int bankId) {
60 this.bankId = bankId;
61 }
62
63}
64
Here is History POJO Room Entity:
1public class BranchDetailsFragment extends Fragment implements View.OnClickListener {
2
3 private final Application application;
4 private final int branchIid;
5
6 private FragBranchDetailsBinding binding;//view-binding
7
8 public BranchDetailsFragment(Application application, int branchIid) {
9 //saving branchId
10 }
11
12 @Nullable
13 @Override
14 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
15 //normal stuff
16 }
17
18 @Override
19 public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
20 super.onViewCreated(view, savedInstanceState);
21 BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);
22
23 //inserting entry in history table
24 HistoryViewModel historyViewModel = new HistoryViewModel(application);
25 History history = new History();
26 history.setBranchId(branchIid);
27 historyViewModel.insert(history);
28
29 //fetching data from branches table
30 branchDetailsViewModel.getBranchCustomizedById(branchIid).observe(getViewLifecycleOwner(), new Observer<BranchCustomized>() {
31 @Override
32 public void onChanged(BranchCustomized branchCustomized) {
33 //get branch details and show them
34 }
35 });
36 }
37}
38@Entity(tableName = "branches")
39public class Branch {
40 @PrimaryKey(autoGenerate = true)
41 @ColumnInfo(name = "_id")
42 private int id;
43
44 @ColumnInfo(name = "bank_id")
45 private int bankId;
46
47 public int getId() {
48 return id;
49 }
50
51 public void setId(int id) {
52 this.id = id;
53 }
54
55 public int getBankId() {
56 return bankId;
57 }
58
59 public void setBankId(int bankId) {
60 this.bankId = bankId;
61 }
62
63}
64@Entity(tableName = "history", foreignKeys = @ForeignKey(entity = Branch.class, parentColumns = "_id", childColumns = "branch_id"))
65public class History {
66 @PrimaryKey(autoGenerate = true)
67 @ColumnInfo(name = "_id")
68 private int id;
69
70 @ColumnInfo(name = "branch_id")
71 private int branchId;
72
73 public int getId() {
74 return id;
75 }
76
77 public void setId(int id) {
78 this.id = id;
79 }
80
81 public int getBranchId() {
82 return branchId;
83 }
84
85 public void setBranchId(int branchId) {
86 this.branchId = branchId;
87 }
88}
89
Here is historyViewModel
1public class BranchDetailsFragment extends Fragment implements View.OnClickListener {
2
3 private final Application application;
4 private final int branchIid;
5
6 private FragBranchDetailsBinding binding;//view-binding
7
8 public BranchDetailsFragment(Application application, int branchIid) {
9 //saving branchId
10 }
11
12 @Nullable
13 @Override
14 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
15 //normal stuff
16 }
17
18 @Override
19 public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
20 super.onViewCreated(view, savedInstanceState);
21 BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);
22
23 //inserting entry in history table
24 HistoryViewModel historyViewModel = new HistoryViewModel(application);
25 History history = new History();
26 history.setBranchId(branchIid);
27 historyViewModel.insert(history);
28
29 //fetching data from branches table
30 branchDetailsViewModel.getBranchCustomizedById(branchIid).observe(getViewLifecycleOwner(), new Observer<BranchCustomized>() {
31 @Override
32 public void onChanged(BranchCustomized branchCustomized) {
33 //get branch details and show them
34 }
35 });
36 }
37}
38@Entity(tableName = "branches")
39public class Branch {
40 @PrimaryKey(autoGenerate = true)
41 @ColumnInfo(name = "_id")
42 private int id;
43
44 @ColumnInfo(name = "bank_id")
45 private int bankId;
46
47 public int getId() {
48 return id;
49 }
50
51 public void setId(int id) {
52 this.id = id;
53 }
54
55 public int getBankId() {
56 return bankId;
57 }
58
59 public void setBankId(int bankId) {
60 this.bankId = bankId;
61 }
62
63}
64@Entity(tableName = "history", foreignKeys = @ForeignKey(entity = Branch.class, parentColumns = "_id", childColumns = "branch_id"))
65public class History {
66 @PrimaryKey(autoGenerate = true)
67 @ColumnInfo(name = "_id")
68 private int id;
69
70 @ColumnInfo(name = "branch_id")
71 private int branchId;
72
73 public int getId() {
74 return id;
75 }
76
77 public void setId(int id) {
78 this.id = id;
79 }
80
81 public int getBranchId() {
82 return branchId;
83 }
84
85 public void setBranchId(int branchId) {
86 this.branchId = branchId;
87 }
88}
89public class HistoryViewModel extends AndroidViewModel {
90 final HistoryRepository repository;
91
92 public HistoryViewModel(Application application) {
93 super(application);
94 repository = new HistoryRepository(application);
95 }
96
97 public LiveData<List<HistoryCustomized>> getAll(){
98 return repository.getAll();
99 }
100
101 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token){
102 return repository.searchHistoryByBankOrBranch(token);
103 }
104
105 public void insert(History history){
106 repository.insert(history);
107 }
108}
109
Here is HistoryRepository
1public class BranchDetailsFragment extends Fragment implements View.OnClickListener {
2
3 private final Application application;
4 private final int branchIid;
5
6 private FragBranchDetailsBinding binding;//view-binding
7
8 public BranchDetailsFragment(Application application, int branchIid) {
9 //saving branchId
10 }
11
12 @Nullable
13 @Override
14 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
15 //normal stuff
16 }
17
18 @Override
19 public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
20 super.onViewCreated(view, savedInstanceState);
21 BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);
22
23 //inserting entry in history table
24 HistoryViewModel historyViewModel = new HistoryViewModel(application);
25 History history = new History();
26 history.setBranchId(branchIid);
27 historyViewModel.insert(history);
28
29 //fetching data from branches table
30 branchDetailsViewModel.getBranchCustomizedById(branchIid).observe(getViewLifecycleOwner(), new Observer<BranchCustomized>() {
31 @Override
32 public void onChanged(BranchCustomized branchCustomized) {
33 //get branch details and show them
34 }
35 });
36 }
37}
38@Entity(tableName = "branches")
39public class Branch {
40 @PrimaryKey(autoGenerate = true)
41 @ColumnInfo(name = "_id")
42 private int id;
43
44 @ColumnInfo(name = "bank_id")
45 private int bankId;
46
47 public int getId() {
48 return id;
49 }
50
51 public void setId(int id) {
52 this.id = id;
53 }
54
55 public int getBankId() {
56 return bankId;
57 }
58
59 public void setBankId(int bankId) {
60 this.bankId = bankId;
61 }
62
63}
64@Entity(tableName = "history", foreignKeys = @ForeignKey(entity = Branch.class, parentColumns = "_id", childColumns = "branch_id"))
65public class History {
66 @PrimaryKey(autoGenerate = true)
67 @ColumnInfo(name = "_id")
68 private int id;
69
70 @ColumnInfo(name = "branch_id")
71 private int branchId;
72
73 public int getId() {
74 return id;
75 }
76
77 public void setId(int id) {
78 this.id = id;
79 }
80
81 public int getBranchId() {
82 return branchId;
83 }
84
85 public void setBranchId(int branchId) {
86 this.branchId = branchId;
87 }
88}
89public class HistoryViewModel extends AndroidViewModel {
90 final HistoryRepository repository;
91
92 public HistoryViewModel(Application application) {
93 super(application);
94 repository = new HistoryRepository(application);
95 }
96
97 public LiveData<List<HistoryCustomized>> getAll(){
98 return repository.getAll();
99 }
100
101 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token){
102 return repository.searchHistoryByBankOrBranch(token);
103 }
104
105 public void insert(History history){
106 repository.insert(history);
107 }
108}
109public class HistoryRepository {
110 private final HistoryDao dao;
111 AppDatabase db;
112
113
114 public HistoryRepository(Application application) {
115 db = AppDatabase.getInstance(application);
116 dao = db.getHistoryDao();
117 }
118
119 public LiveData<List<HistoryCustomized>> getAll() {
120 return dao.getAll();
121 }
122
123 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token) {
124 return dao.searchHistoryByBankOrBranch(token);
125 }
126
127 public void insert(History history){
128 try {
129 db.getTransactionExecutor().execute(new Runnable() {
130 @Override
131 public void run() {
132 dao.insert(history);
133 }
134 });
135 }catch (NullPointerException e){
136 e.printStackTrace();
137 }
138 }
139}
140
Here is HistoryDao
1public class BranchDetailsFragment extends Fragment implements View.OnClickListener {
2
3 private final Application application;
4 private final int branchIid;
5
6 private FragBranchDetailsBinding binding;//view-binding
7
8 public BranchDetailsFragment(Application application, int branchIid) {
9 //saving branchId
10 }
11
12 @Nullable
13 @Override
14 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
15 //normal stuff
16 }
17
18 @Override
19 public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
20 super.onViewCreated(view, savedInstanceState);
21 BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);
22
23 //inserting entry in history table
24 HistoryViewModel historyViewModel = new HistoryViewModel(application);
25 History history = new History();
26 history.setBranchId(branchIid);
27 historyViewModel.insert(history);
28
29 //fetching data from branches table
30 branchDetailsViewModel.getBranchCustomizedById(branchIid).observe(getViewLifecycleOwner(), new Observer<BranchCustomized>() {
31 @Override
32 public void onChanged(BranchCustomized branchCustomized) {
33 //get branch details and show them
34 }
35 });
36 }
37}
38@Entity(tableName = "branches")
39public class Branch {
40 @PrimaryKey(autoGenerate = true)
41 @ColumnInfo(name = "_id")
42 private int id;
43
44 @ColumnInfo(name = "bank_id")
45 private int bankId;
46
47 public int getId() {
48 return id;
49 }
50
51 public void setId(int id) {
52 this.id = id;
53 }
54
55 public int getBankId() {
56 return bankId;
57 }
58
59 public void setBankId(int bankId) {
60 this.bankId = bankId;
61 }
62
63}
64@Entity(tableName = "history", foreignKeys = @ForeignKey(entity = Branch.class, parentColumns = "_id", childColumns = "branch_id"))
65public class History {
66 @PrimaryKey(autoGenerate = true)
67 @ColumnInfo(name = "_id")
68 private int id;
69
70 @ColumnInfo(name = "branch_id")
71 private int branchId;
72
73 public int getId() {
74 return id;
75 }
76
77 public void setId(int id) {
78 this.id = id;
79 }
80
81 public int getBranchId() {
82 return branchId;
83 }
84
85 public void setBranchId(int branchId) {
86 this.branchId = branchId;
87 }
88}
89public class HistoryViewModel extends AndroidViewModel {
90 final HistoryRepository repository;
91
92 public HistoryViewModel(Application application) {
93 super(application);
94 repository = new HistoryRepository(application);
95 }
96
97 public LiveData<List<HistoryCustomized>> getAll(){
98 return repository.getAll();
99 }
100
101 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token){
102 return repository.searchHistoryByBankOrBranch(token);
103 }
104
105 public void insert(History history){
106 repository.insert(history);
107 }
108}
109public class HistoryRepository {
110 private final HistoryDao dao;
111 AppDatabase db;
112
113
114 public HistoryRepository(Application application) {
115 db = AppDatabase.getInstance(application);
116 dao = db.getHistoryDao();
117 }
118
119 public LiveData<List<HistoryCustomized>> getAll() {
120 return dao.getAll();
121 }
122
123 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token) {
124 return dao.searchHistoryByBankOrBranch(token);
125 }
126
127 public void insert(History history){
128 try {
129 db.getTransactionExecutor().execute(new Runnable() {
130 @Override
131 public void run() {
132 dao.insert(history);
133 }
134 });
135 }catch (NullPointerException e){
136 e.printStackTrace();
137 }
138 }
139}
140@Dao
141public interface HistoryDao {
142 @Query("select history.branch_id, bank, branch from history\n" +
143 "join branches on branches._id=history.branch_id\n" +
144 "join banks on banks._id=branches.bank_id")
145 LiveData<List<HistoryCustomized>> getAll();
146
147 @Query("select history.branch_id, bank, branch from history\n" +
148 "join branches on branches._id=history.branch_id\n" +
149 "join banks on banks._id=branches.bank_id\n" +
150 "where bank like :token or branch like :token")
151 LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token);
152
153 @Transaction
154 @Insert
155 void insert(History history);
156}
157
I know there is some problem with threading because whenever I run this in emulator (BranchFragment), it crash quickly, but when I debug it, it show proper data, though not insert entry in history table. Room has many threading issues.
Here is AppDatabase:
1public class BranchDetailsFragment extends Fragment implements View.OnClickListener {
2
3 private final Application application;
4 private final int branchIid;
5
6 private FragBranchDetailsBinding binding;//view-binding
7
8 public BranchDetailsFragment(Application application, int branchIid) {
9 //saving branchId
10 }
11
12 @Nullable
13 @Override
14 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
15 //normal stuff
16 }
17
18 @Override
19 public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
20 super.onViewCreated(view, savedInstanceState);
21 BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);
22
23 //inserting entry in history table
24 HistoryViewModel historyViewModel = new HistoryViewModel(application);
25 History history = new History();
26 history.setBranchId(branchIid);
27 historyViewModel.insert(history);
28
29 //fetching data from branches table
30 branchDetailsViewModel.getBranchCustomizedById(branchIid).observe(getViewLifecycleOwner(), new Observer<BranchCustomized>() {
31 @Override
32 public void onChanged(BranchCustomized branchCustomized) {
33 //get branch details and show them
34 }
35 });
36 }
37}
38@Entity(tableName = "branches")
39public class Branch {
40 @PrimaryKey(autoGenerate = true)
41 @ColumnInfo(name = "_id")
42 private int id;
43
44 @ColumnInfo(name = "bank_id")
45 private int bankId;
46
47 public int getId() {
48 return id;
49 }
50
51 public void setId(int id) {
52 this.id = id;
53 }
54
55 public int getBankId() {
56 return bankId;
57 }
58
59 public void setBankId(int bankId) {
60 this.bankId = bankId;
61 }
62
63}
64@Entity(tableName = "history", foreignKeys = @ForeignKey(entity = Branch.class, parentColumns = "_id", childColumns = "branch_id"))
65public class History {
66 @PrimaryKey(autoGenerate = true)
67 @ColumnInfo(name = "_id")
68 private int id;
69
70 @ColumnInfo(name = "branch_id")
71 private int branchId;
72
73 public int getId() {
74 return id;
75 }
76
77 public void setId(int id) {
78 this.id = id;
79 }
80
81 public int getBranchId() {
82 return branchId;
83 }
84
85 public void setBranchId(int branchId) {
86 this.branchId = branchId;
87 }
88}
89public class HistoryViewModel extends AndroidViewModel {
90 final HistoryRepository repository;
91
92 public HistoryViewModel(Application application) {
93 super(application);
94 repository = new HistoryRepository(application);
95 }
96
97 public LiveData<List<HistoryCustomized>> getAll(){
98 return repository.getAll();
99 }
100
101 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token){
102 return repository.searchHistoryByBankOrBranch(token);
103 }
104
105 public void insert(History history){
106 repository.insert(history);
107 }
108}
109public class HistoryRepository {
110 private final HistoryDao dao;
111 AppDatabase db;
112
113
114 public HistoryRepository(Application application) {
115 db = AppDatabase.getInstance(application);
116 dao = db.getHistoryDao();
117 }
118
119 public LiveData<List<HistoryCustomized>> getAll() {
120 return dao.getAll();
121 }
122
123 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token) {
124 return dao.searchHistoryByBankOrBranch(token);
125 }
126
127 public void insert(History history){
128 try {
129 db.getTransactionExecutor().execute(new Runnable() {
130 @Override
131 public void run() {
132 dao.insert(history);
133 }
134 });
135 }catch (NullPointerException e){
136 e.printStackTrace();
137 }
138 }
139}
140@Dao
141public interface HistoryDao {
142 @Query("select history.branch_id, bank, branch from history\n" +
143 "join branches on branches._id=history.branch_id\n" +
144 "join banks on banks._id=branches.bank_id")
145 LiveData<List<HistoryCustomized>> getAll();
146
147 @Query("select history.branch_id, bank, branch from history\n" +
148 "join branches on branches._id=history.branch_id\n" +
149 "join banks on banks._id=branches.bank_id\n" +
150 "where bank like :token or branch like :token")
151 LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token);
152
153 @Transaction
154 @Insert
155 void insert(History history);
156}
157@Database(entities = {Branch.class, History.class},
158 version = 1, exportSchema = false)
159public abstract class AppDatabase extends RoomDatabase {
160
161 public abstract BranchesDao getBranchesDao();
162 public abstract HistoryDao getHistoryDao();
163
164 public static AppDatabase getInstance(final Context context) {
165 dbInstance = buildDatabaseInstance(context);
166 return dbInstance;
167 }
168
169 private static AppDatabase buildDatabaseInstance(Context context) {
170 return Room.databaseBuilder(context,
171 AppDatabase.class,
172 "branch.db")
173 .createFromAsset("branch.db")
174 .fallbackToDestructiveMigration()
175 .build();
176 }
177
178 public static void cleanUp() {
179 dbInstance = null;
180 }
181
182}
183
Here is HistoryDao_Impl(autogenerated by Room library):
1public class BranchDetailsFragment extends Fragment implements View.OnClickListener {
2
3 private final Application application;
4 private final int branchIid;
5
6 private FragBranchDetailsBinding binding;//view-binding
7
8 public BranchDetailsFragment(Application application, int branchIid) {
9 //saving branchId
10 }
11
12 @Nullable
13 @Override
14 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
15 //normal stuff
16 }
17
18 @Override
19 public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
20 super.onViewCreated(view, savedInstanceState);
21 BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);
22
23 //inserting entry in history table
24 HistoryViewModel historyViewModel = new HistoryViewModel(application);
25 History history = new History();
26 history.setBranchId(branchIid);
27 historyViewModel.insert(history);
28
29 //fetching data from branches table
30 branchDetailsViewModel.getBranchCustomizedById(branchIid).observe(getViewLifecycleOwner(), new Observer<BranchCustomized>() {
31 @Override
32 public void onChanged(BranchCustomized branchCustomized) {
33 //get branch details and show them
34 }
35 });
36 }
37}
38@Entity(tableName = "branches")
39public class Branch {
40 @PrimaryKey(autoGenerate = true)
41 @ColumnInfo(name = "_id")
42 private int id;
43
44 @ColumnInfo(name = "bank_id")
45 private int bankId;
46
47 public int getId() {
48 return id;
49 }
50
51 public void setId(int id) {
52 this.id = id;
53 }
54
55 public int getBankId() {
56 return bankId;
57 }
58
59 public void setBankId(int bankId) {
60 this.bankId = bankId;
61 }
62
63}
64@Entity(tableName = "history", foreignKeys = @ForeignKey(entity = Branch.class, parentColumns = "_id", childColumns = "branch_id"))
65public class History {
66 @PrimaryKey(autoGenerate = true)
67 @ColumnInfo(name = "_id")
68 private int id;
69
70 @ColumnInfo(name = "branch_id")
71 private int branchId;
72
73 public int getId() {
74 return id;
75 }
76
77 public void setId(int id) {
78 this.id = id;
79 }
80
81 public int getBranchId() {
82 return branchId;
83 }
84
85 public void setBranchId(int branchId) {
86 this.branchId = branchId;
87 }
88}
89public class HistoryViewModel extends AndroidViewModel {
90 final HistoryRepository repository;
91
92 public HistoryViewModel(Application application) {
93 super(application);
94 repository = new HistoryRepository(application);
95 }
96
97 public LiveData<List<HistoryCustomized>> getAll(){
98 return repository.getAll();
99 }
100
101 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token){
102 return repository.searchHistoryByBankOrBranch(token);
103 }
104
105 public void insert(History history){
106 repository.insert(history);
107 }
108}
109public class HistoryRepository {
110 private final HistoryDao dao;
111 AppDatabase db;
112
113
114 public HistoryRepository(Application application) {
115 db = AppDatabase.getInstance(application);
116 dao = db.getHistoryDao();
117 }
118
119 public LiveData<List<HistoryCustomized>> getAll() {
120 return dao.getAll();
121 }
122
123 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token) {
124 return dao.searchHistoryByBankOrBranch(token);
125 }
126
127 public void insert(History history){
128 try {
129 db.getTransactionExecutor().execute(new Runnable() {
130 @Override
131 public void run() {
132 dao.insert(history);
133 }
134 });
135 }catch (NullPointerException e){
136 e.printStackTrace();
137 }
138 }
139}
140@Dao
141public interface HistoryDao {
142 @Query("select history.branch_id, bank, branch from history\n" +
143 "join branches on branches._id=history.branch_id\n" +
144 "join banks on banks._id=branches.bank_id")
145 LiveData<List<HistoryCustomized>> getAll();
146
147 @Query("select history.branch_id, bank, branch from history\n" +
148 "join branches on branches._id=history.branch_id\n" +
149 "join banks on banks._id=branches.bank_id\n" +
150 "where bank like :token or branch like :token")
151 LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token);
152
153 @Transaction
154 @Insert
155 void insert(History history);
156}
157@Database(entities = {Branch.class, History.class},
158 version = 1, exportSchema = false)
159public abstract class AppDatabase extends RoomDatabase {
160
161 public abstract BranchesDao getBranchesDao();
162 public abstract HistoryDao getHistoryDao();
163
164 public static AppDatabase getInstance(final Context context) {
165 dbInstance = buildDatabaseInstance(context);
166 return dbInstance;
167 }
168
169 private static AppDatabase buildDatabaseInstance(Context context) {
170 return Room.databaseBuilder(context,
171 AppDatabase.class,
172 "branch.db")
173 .createFromAsset("branch.db")
174 .fallbackToDestructiveMigration()
175 .build();
176 }
177
178 public static void cleanUp() {
179 dbInstance = null;
180 }
181
182}
183@SuppressWarnings({"unchecked", "deprecation"})
184public final class HistoryDao_Impl implements HistoryDao {
185 private final RoomDatabase __db;
186
187 private final EntityInsertionAdapter<History> __insertionAdapterOfHistory;
188
189 public HistoryDao_Impl(RoomDatabase __db) {
190 this.__db = __db;
191 this.__insertionAdapterOfHistory = new EntityInsertionAdapter<History>(__db) {
192 @Override
193 public String createQuery() {
194 return "INSERT OR ABORT INTO `history` (`_id`,`branch_id`) VALUES (nullif(?, 0),?)";
195 }
196
197 @Override
198 public void bind(SupportSQLiteStatement stmt, History value) {
199 stmt.bindLong(1, value.getId());
200 stmt.bindLong(2, value.getBranchId());
201 }
202 };
203 }
204
205 @Override
206 public void insert(final History history) {
207 __db.assertNotSuspendingTransaction();
208 __db.beginTransaction();
209 try {
210 __insertionAdapterOfHistory.insert(history);
211 __db.setTransactionSuccessful();
212 } finally {
213 __db.endTransaction();
214 }
215 }
216
217 @Override
218 protected void finalize() {
219 _statement.release();
220 }
221 });
222 }
223}
224
1public class BranchDetailsFragment extends Fragment implements View.OnClickListener {
2
3 private final Application application;
4 private final int branchIid;
5
6 private FragBranchDetailsBinding binding;//view-binding
7
8 public BranchDetailsFragment(Application application, int branchIid) {
9 //saving branchId
10 }
11
12 @Nullable
13 @Override
14 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
15 //normal stuff
16 }
17
18 @Override
19 public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
20 super.onViewCreated(view, savedInstanceState);
21 BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);
22
23 //inserting entry in history table
24 HistoryViewModel historyViewModel = new HistoryViewModel(application);
25 History history = new History();
26 history.setBranchId(branchIid);
27 historyViewModel.insert(history);
28
29 //fetching data from branches table
30 branchDetailsViewModel.getBranchCustomizedById(branchIid).observe(getViewLifecycleOwner(), new Observer<BranchCustomized>() {
31 @Override
32 public void onChanged(BranchCustomized branchCustomized) {
33 //get branch details and show them
34 }
35 });
36 }
37}
38@Entity(tableName = "branches")
39public class Branch {
40 @PrimaryKey(autoGenerate = true)
41 @ColumnInfo(name = "_id")
42 private int id;
43
44 @ColumnInfo(name = "bank_id")
45 private int bankId;
46
47 public int getId() {
48 return id;
49 }
50
51 public void setId(int id) {
52 this.id = id;
53 }
54
55 public int getBankId() {
56 return bankId;
57 }
58
59 public void setBankId(int bankId) {
60 this.bankId = bankId;
61 }
62
63}
64@Entity(tableName = "history", foreignKeys = @ForeignKey(entity = Branch.class, parentColumns = "_id", childColumns = "branch_id"))
65public class History {
66 @PrimaryKey(autoGenerate = true)
67 @ColumnInfo(name = "_id")
68 private int id;
69
70 @ColumnInfo(name = "branch_id")
71 private int branchId;
72
73 public int getId() {
74 return id;
75 }
76
77 public void setId(int id) {
78 this.id = id;
79 }
80
81 public int getBranchId() {
82 return branchId;
83 }
84
85 public void setBranchId(int branchId) {
86 this.branchId = branchId;
87 }
88}
89public class HistoryViewModel extends AndroidViewModel {
90 final HistoryRepository repository;
91
92 public HistoryViewModel(Application application) {
93 super(application);
94 repository = new HistoryRepository(application);
95 }
96
97 public LiveData<List<HistoryCustomized>> getAll(){
98 return repository.getAll();
99 }
100
101 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token){
102 return repository.searchHistoryByBankOrBranch(token);
103 }
104
105 public void insert(History history){
106 repository.insert(history);
107 }
108}
109public class HistoryRepository {
110 private final HistoryDao dao;
111 AppDatabase db;
112
113
114 public HistoryRepository(Application application) {
115 db = AppDatabase.getInstance(application);
116 dao = db.getHistoryDao();
117 }
118
119 public LiveData<List<HistoryCustomized>> getAll() {
120 return dao.getAll();
121 }
122
123 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token) {
124 return dao.searchHistoryByBankOrBranch(token);
125 }
126
127 public void insert(History history){
128 try {
129 db.getTransactionExecutor().execute(new Runnable() {
130 @Override
131 public void run() {
132 dao.insert(history);
133 }
134 });
135 }catch (NullPointerException e){
136 e.printStackTrace();
137 }
138 }
139}
140@Dao
141public interface HistoryDao {
142 @Query("select history.branch_id, bank, branch from history\n" +
143 "join branches on branches._id=history.branch_id\n" +
144 "join banks on banks._id=branches.bank_id")
145 LiveData<List<HistoryCustomized>> getAll();
146
147 @Query("select history.branch_id, bank, branch from history\n" +
148 "join branches on branches._id=history.branch_id\n" +
149 "join banks on banks._id=branches.bank_id\n" +
150 "where bank like :token or branch like :token")
151 LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token);
152
153 @Transaction
154 @Insert
155 void insert(History history);
156}
157@Database(entities = {Branch.class, History.class},
158 version = 1, exportSchema = false)
159public abstract class AppDatabase extends RoomDatabase {
160
161 public abstract BranchesDao getBranchesDao();
162 public abstract HistoryDao getHistoryDao();
163
164 public static AppDatabase getInstance(final Context context) {
165 dbInstance = buildDatabaseInstance(context);
166 return dbInstance;
167 }
168
169 private static AppDatabase buildDatabaseInstance(Context context) {
170 return Room.databaseBuilder(context,
171 AppDatabase.class,
172 "branch.db")
173 .createFromAsset("branch.db")
174 .fallbackToDestructiveMigration()
175 .build();
176 }
177
178 public static void cleanUp() {
179 dbInstance = null;
180 }
181
182}
183@SuppressWarnings({"unchecked", "deprecation"})
184public final class HistoryDao_Impl implements HistoryDao {
185 private final RoomDatabase __db;
186
187 private final EntityInsertionAdapter<History> __insertionAdapterOfHistory;
188
189 public HistoryDao_Impl(RoomDatabase __db) {
190 this.__db = __db;
191 this.__insertionAdapterOfHistory = new EntityInsertionAdapter<History>(__db) {
192 @Override
193 public String createQuery() {
194 return "INSERT OR ABORT INTO `history` (`_id`,`branch_id`) VALUES (nullif(?, 0),?)";
195 }
196
197 @Override
198 public void bind(SupportSQLiteStatement stmt, History value) {
199 stmt.bindLong(1, value.getId());
200 stmt.bindLong(2, value.getBranchId());
201 }
202 };
203 }
204
205 @Override
206 public void insert(final History history) {
207 __db.assertNotSuspendingTransaction();
208 __db.beginTransaction();
209 try {
210 __insertionAdapterOfHistory.insert(history);
211 __db.setTransactionSuccessful();
212 } finally {
213 __db.endTransaction();
214 }
215 }
216
217 @Override
218 protected void finalize() {
219 _statement.release();
220 }
221 });
222 }
223}
22404-06 13:58:35.080 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.button.MaterialButtonHelper.createBackground
22504-06 13:58:35.080 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.button.MaterialButtonHelper.setRippleColor
22604-06 13:58:35.090 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'com.google.android.material.chip.Chip$2', referenced from method com.google.android.material.chip.Chip.initOutlineProvider
22704-06 13:58:35.090 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.chip.Chip.updateFrameworkRippleBackground
22804-06 13:58:35.100 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.chip.ChipDrawable.updateFrameworkCloseIconRipple
22904-06 13:58:35.770 2471-2498/com.appsbharti.bharatbankdetails E/AndroidRuntime: FATAL EXCEPTION: arch_disk_io_2
230 android.database.sqlite.SQLiteConstraintException: foreign key constraint failed (code 19)
231 at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
232 at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:775)
233 at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
234 at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
235 at androidx.sqlite.db.framework.FrameworkSQLiteStatement.executeInsert(FrameworkSQLiteStatement.java:51)
236 at androidx.room.EntityInsertionAdapter.insert(EntityInsertionAdapter.java:64)
237 at com.appsbharti.bharatbankdetails.Daos.HistoryDao_Impl.insert(HistoryDao_Impl.java:48)
238 at com.appsbharti.bharatbankdetails.Repositories.HistoryRepository$1.run(HistoryRepository.java:41)
239 at androidx.room.TransactionExecutor$1.run(TransactionExecutor.java:45)
240 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
241 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
242 at java.lang.Thread.run(Thread.java:856)
24304-06 13:58:39.170 1395-1481/system_process E/ThrottleService: problem during onPollAlarm: java.lang.IllegalStateException: problem parsing stats: java.io.FileNotFoundException: /proc/net/xt_qtaguid/iface_stat_all: open failed: ENOENT (No such file or directory)
244
Sometimes It throw this error:
1public class BranchDetailsFragment extends Fragment implements View.OnClickListener {
2
3 private final Application application;
4 private final int branchIid;
5
6 private FragBranchDetailsBinding binding;//view-binding
7
8 public BranchDetailsFragment(Application application, int branchIid) {
9 //saving branchId
10 }
11
12 @Nullable
13 @Override
14 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
15 //normal stuff
16 }
17
18 @Override
19 public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
20 super.onViewCreated(view, savedInstanceState);
21 BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);
22
23 //inserting entry in history table
24 HistoryViewModel historyViewModel = new HistoryViewModel(application);
25 History history = new History();
26 history.setBranchId(branchIid);
27 historyViewModel.insert(history);
28
29 //fetching data from branches table
30 branchDetailsViewModel.getBranchCustomizedById(branchIid).observe(getViewLifecycleOwner(), new Observer<BranchCustomized>() {
31 @Override
32 public void onChanged(BranchCustomized branchCustomized) {
33 //get branch details and show them
34 }
35 });
36 }
37}
38@Entity(tableName = "branches")
39public class Branch {
40 @PrimaryKey(autoGenerate = true)
41 @ColumnInfo(name = "_id")
42 private int id;
43
44 @ColumnInfo(name = "bank_id")
45 private int bankId;
46
47 public int getId() {
48 return id;
49 }
50
51 public void setId(int id) {
52 this.id = id;
53 }
54
55 public int getBankId() {
56 return bankId;
57 }
58
59 public void setBankId(int bankId) {
60 this.bankId = bankId;
61 }
62
63}
64@Entity(tableName = "history", foreignKeys = @ForeignKey(entity = Branch.class, parentColumns = "_id", childColumns = "branch_id"))
65public class History {
66 @PrimaryKey(autoGenerate = true)
67 @ColumnInfo(name = "_id")
68 private int id;
69
70 @ColumnInfo(name = "branch_id")
71 private int branchId;
72
73 public int getId() {
74 return id;
75 }
76
77 public void setId(int id) {
78 this.id = id;
79 }
80
81 public int getBranchId() {
82 return branchId;
83 }
84
85 public void setBranchId(int branchId) {
86 this.branchId = branchId;
87 }
88}
89public class HistoryViewModel extends AndroidViewModel {
90 final HistoryRepository repository;
91
92 public HistoryViewModel(Application application) {
93 super(application);
94 repository = new HistoryRepository(application);
95 }
96
97 public LiveData<List<HistoryCustomized>> getAll(){
98 return repository.getAll();
99 }
100
101 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token){
102 return repository.searchHistoryByBankOrBranch(token);
103 }
104
105 public void insert(History history){
106 repository.insert(history);
107 }
108}
109public class HistoryRepository {
110 private final HistoryDao dao;
111 AppDatabase db;
112
113
114 public HistoryRepository(Application application) {
115 db = AppDatabase.getInstance(application);
116 dao = db.getHistoryDao();
117 }
118
119 public LiveData<List<HistoryCustomized>> getAll() {
120 return dao.getAll();
121 }
122
123 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token) {
124 return dao.searchHistoryByBankOrBranch(token);
125 }
126
127 public void insert(History history){
128 try {
129 db.getTransactionExecutor().execute(new Runnable() {
130 @Override
131 public void run() {
132 dao.insert(history);
133 }
134 });
135 }catch (NullPointerException e){
136 e.printStackTrace();
137 }
138 }
139}
140@Dao
141public interface HistoryDao {
142 @Query("select history.branch_id, bank, branch from history\n" +
143 "join branches on branches._id=history.branch_id\n" +
144 "join banks on banks._id=branches.bank_id")
145 LiveData<List<HistoryCustomized>> getAll();
146
147 @Query("select history.branch_id, bank, branch from history\n" +
148 "join branches on branches._id=history.branch_id\n" +
149 "join banks on banks._id=branches.bank_id\n" +
150 "where bank like :token or branch like :token")
151 LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token);
152
153 @Transaction
154 @Insert
155 void insert(History history);
156}
157@Database(entities = {Branch.class, History.class},
158 version = 1, exportSchema = false)
159public abstract class AppDatabase extends RoomDatabase {
160
161 public abstract BranchesDao getBranchesDao();
162 public abstract HistoryDao getHistoryDao();
163
164 public static AppDatabase getInstance(final Context context) {
165 dbInstance = buildDatabaseInstance(context);
166 return dbInstance;
167 }
168
169 private static AppDatabase buildDatabaseInstance(Context context) {
170 return Room.databaseBuilder(context,
171 AppDatabase.class,
172 "branch.db")
173 .createFromAsset("branch.db")
174 .fallbackToDestructiveMigration()
175 .build();
176 }
177
178 public static void cleanUp() {
179 dbInstance = null;
180 }
181
182}
183@SuppressWarnings({"unchecked", "deprecation"})
184public final class HistoryDao_Impl implements HistoryDao {
185 private final RoomDatabase __db;
186
187 private final EntityInsertionAdapter<History> __insertionAdapterOfHistory;
188
189 public HistoryDao_Impl(RoomDatabase __db) {
190 this.__db = __db;
191 this.__insertionAdapterOfHistory = new EntityInsertionAdapter<History>(__db) {
192 @Override
193 public String createQuery() {
194 return "INSERT OR ABORT INTO `history` (`_id`,`branch_id`) VALUES (nullif(?, 0),?)";
195 }
196
197 @Override
198 public void bind(SupportSQLiteStatement stmt, History value) {
199 stmt.bindLong(1, value.getId());
200 stmt.bindLong(2, value.getBranchId());
201 }
202 };
203 }
204
205 @Override
206 public void insert(final History history) {
207 __db.assertNotSuspendingTransaction();
208 __db.beginTransaction();
209 try {
210 __insertionAdapterOfHistory.insert(history);
211 __db.setTransactionSuccessful();
212 } finally {
213 __db.endTransaction();
214 }
215 }
216
217 @Override
218 protected void finalize() {
219 _statement.release();
220 }
221 });
222 }
223}
22404-06 13:58:35.080 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.button.MaterialButtonHelper.createBackground
22504-06 13:58:35.080 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.button.MaterialButtonHelper.setRippleColor
22604-06 13:58:35.090 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'com.google.android.material.chip.Chip$2', referenced from method com.google.android.material.chip.Chip.initOutlineProvider
22704-06 13:58:35.090 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.chip.Chip.updateFrameworkRippleBackground
22804-06 13:58:35.100 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.chip.ChipDrawable.updateFrameworkCloseIconRipple
22904-06 13:58:35.770 2471-2498/com.appsbharti.bharatbankdetails E/AndroidRuntime: FATAL EXCEPTION: arch_disk_io_2
230 android.database.sqlite.SQLiteConstraintException: foreign key constraint failed (code 19)
231 at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
232 at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:775)
233 at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
234 at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
235 at androidx.sqlite.db.framework.FrameworkSQLiteStatement.executeInsert(FrameworkSQLiteStatement.java:51)
236 at androidx.room.EntityInsertionAdapter.insert(EntityInsertionAdapter.java:64)
237 at com.appsbharti.bharatbankdetails.Daos.HistoryDao_Impl.insert(HistoryDao_Impl.java:48)
238 at com.appsbharti.bharatbankdetails.Repositories.HistoryRepository$1.run(HistoryRepository.java:41)
239 at androidx.room.TransactionExecutor$1.run(TransactionExecutor.java:45)
240 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
241 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
242 at java.lang.Thread.run(Thread.java:856)
24304-06 13:58:39.170 1395-1481/system_process E/ThrottleService: problem during onPollAlarm: java.lang.IllegalStateException: problem parsing stats: java.io.FileNotFoundException: /proc/net/xt_qtaguid/iface_stat_all: open failed: ENOENT (No such file or directory)
244--------- beginning of crash
2452021-04-07 17:05:06.152 4247-4279/com.appsbharti.bharatbankdetails E/AndroidRuntime: FATAL EXCEPTION: arch_disk_io_2
246 Process: com.appsbharti.bharatbankdetails, PID: 4247
247 android.database.sqlite.SQLiteReadOnlyDatabaseException: attempt to write a readonly database (code 1032 SQLITE_READONLY_DBMOVED)
248 at android.database.sqlite.SQLiteConnection.nativeExecuteForString(Native Method)
249 at android.database.sqlite.SQLiteConnection.executeForString(SQLiteConnection.java:655)
250 at android.database.sqlite.SQLiteConnection.setJournalMode(SQLiteConnection.java:336)
251 at android.database.sqlite.SQLiteConnection.setWalModeFromConfiguration(SQLiteConnection.java:298)
252 at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:217)
253 at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:195)
254 at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:503)
255 at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:204)
256 at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:196)
257 at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:880)
258 at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:865)
259 at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:739)
260 at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:729)
261 at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:355)
262 at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:298)
263 at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:92)
264 at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:53)
265 at androidx.room.SQLiteCopyOpenHelper.getWritableDatabase(SQLiteCopyOpenHelper.java:90)
266 at androidx.room.RoomDatabase.inTransaction(RoomDatabase.java:476)
267 at androidx.room.RoomDatabase.assertNotSuspendingTransaction(RoomDatabase.java:281)
268 at com.appsbharti.bharatbankdetails.Daos.HistoryDao_Impl.insert(HistoryDao_Impl.java:45)
269 at com.appsbharti.bharatbankdetails.Repositories.HistoryRepository$1.run(HistoryRepository.java:37)
270 at androidx.room.TransactionExecutor$1.run(TransactionExecutor.java:45)
271 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
272 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
273 at java.lang.Thread.run(Thread.java:764)
274
I have added android_metadata table manually when I throws error of can't fine locale en_US.
1public class BranchDetailsFragment extends Fragment implements View.OnClickListener {
2
3 private final Application application;
4 private final int branchIid;
5
6 private FragBranchDetailsBinding binding;//view-binding
7
8 public BranchDetailsFragment(Application application, int branchIid) {
9 //saving branchId
10 }
11
12 @Nullable
13 @Override
14 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
15 //normal stuff
16 }
17
18 @Override
19 public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
20 super.onViewCreated(view, savedInstanceState);
21 BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);
22
23 //inserting entry in history table
24 HistoryViewModel historyViewModel = new HistoryViewModel(application);
25 History history = new History();
26 history.setBranchId(branchIid);
27 historyViewModel.insert(history);
28
29 //fetching data from branches table
30 branchDetailsViewModel.getBranchCustomizedById(branchIid).observe(getViewLifecycleOwner(), new Observer<BranchCustomized>() {
31 @Override
32 public void onChanged(BranchCustomized branchCustomized) {
33 //get branch details and show them
34 }
35 });
36 }
37}
38@Entity(tableName = "branches")
39public class Branch {
40 @PrimaryKey(autoGenerate = true)
41 @ColumnInfo(name = "_id")
42 private int id;
43
44 @ColumnInfo(name = "bank_id")
45 private int bankId;
46
47 public int getId() {
48 return id;
49 }
50
51 public void setId(int id) {
52 this.id = id;
53 }
54
55 public int getBankId() {
56 return bankId;
57 }
58
59 public void setBankId(int bankId) {
60 this.bankId = bankId;
61 }
62
63}
64@Entity(tableName = "history", foreignKeys = @ForeignKey(entity = Branch.class, parentColumns = "_id", childColumns = "branch_id"))
65public class History {
66 @PrimaryKey(autoGenerate = true)
67 @ColumnInfo(name = "_id")
68 private int id;
69
70 @ColumnInfo(name = "branch_id")
71 private int branchId;
72
73 public int getId() {
74 return id;
75 }
76
77 public void setId(int id) {
78 this.id = id;
79 }
80
81 public int getBranchId() {
82 return branchId;
83 }
84
85 public void setBranchId(int branchId) {
86 this.branchId = branchId;
87 }
88}
89public class HistoryViewModel extends AndroidViewModel {
90 final HistoryRepository repository;
91
92 public HistoryViewModel(Application application) {
93 super(application);
94 repository = new HistoryRepository(application);
95 }
96
97 public LiveData<List<HistoryCustomized>> getAll(){
98 return repository.getAll();
99 }
100
101 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token){
102 return repository.searchHistoryByBankOrBranch(token);
103 }
104
105 public void insert(History history){
106 repository.insert(history);
107 }
108}
109public class HistoryRepository {
110 private final HistoryDao dao;
111 AppDatabase db;
112
113
114 public HistoryRepository(Application application) {
115 db = AppDatabase.getInstance(application);
116 dao = db.getHistoryDao();
117 }
118
119 public LiveData<List<HistoryCustomized>> getAll() {
120 return dao.getAll();
121 }
122
123 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token) {
124 return dao.searchHistoryByBankOrBranch(token);
125 }
126
127 public void insert(History history){
128 try {
129 db.getTransactionExecutor().execute(new Runnable() {
130 @Override
131 public void run() {
132 dao.insert(history);
133 }
134 });
135 }catch (NullPointerException e){
136 e.printStackTrace();
137 }
138 }
139}
140@Dao
141public interface HistoryDao {
142 @Query("select history.branch_id, bank, branch from history\n" +
143 "join branches on branches._id=history.branch_id\n" +
144 "join banks on banks._id=branches.bank_id")
145 LiveData<List<HistoryCustomized>> getAll();
146
147 @Query("select history.branch_id, bank, branch from history\n" +
148 "join branches on branches._id=history.branch_id\n" +
149 "join banks on banks._id=branches.bank_id\n" +
150 "where bank like :token or branch like :token")
151 LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token);
152
153 @Transaction
154 @Insert
155 void insert(History history);
156}
157@Database(entities = {Branch.class, History.class},
158 version = 1, exportSchema = false)
159public abstract class AppDatabase extends RoomDatabase {
160
161 public abstract BranchesDao getBranchesDao();
162 public abstract HistoryDao getHistoryDao();
163
164 public static AppDatabase getInstance(final Context context) {
165 dbInstance = buildDatabaseInstance(context);
166 return dbInstance;
167 }
168
169 private static AppDatabase buildDatabaseInstance(Context context) {
170 return Room.databaseBuilder(context,
171 AppDatabase.class,
172 "branch.db")
173 .createFromAsset("branch.db")
174 .fallbackToDestructiveMigration()
175 .build();
176 }
177
178 public static void cleanUp() {
179 dbInstance = null;
180 }
181
182}
183@SuppressWarnings({"unchecked", "deprecation"})
184public final class HistoryDao_Impl implements HistoryDao {
185 private final RoomDatabase __db;
186
187 private final EntityInsertionAdapter<History> __insertionAdapterOfHistory;
188
189 public HistoryDao_Impl(RoomDatabase __db) {
190 this.__db = __db;
191 this.__insertionAdapterOfHistory = new EntityInsertionAdapter<History>(__db) {
192 @Override
193 public String createQuery() {
194 return "INSERT OR ABORT INTO `history` (`_id`,`branch_id`) VALUES (nullif(?, 0),?)";
195 }
196
197 @Override
198 public void bind(SupportSQLiteStatement stmt, History value) {
199 stmt.bindLong(1, value.getId());
200 stmt.bindLong(2, value.getBranchId());
201 }
202 };
203 }
204
205 @Override
206 public void insert(final History history) {
207 __db.assertNotSuspendingTransaction();
208 __db.beginTransaction();
209 try {
210 __insertionAdapterOfHistory.insert(history);
211 __db.setTransactionSuccessful();
212 } finally {
213 __db.endTransaction();
214 }
215 }
216
217 @Override
218 protected void finalize() {
219 _statement.release();
220 }
221 });
222 }
223}
22404-06 13:58:35.080 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.button.MaterialButtonHelper.createBackground
22504-06 13:58:35.080 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.button.MaterialButtonHelper.setRippleColor
22604-06 13:58:35.090 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'com.google.android.material.chip.Chip$2', referenced from method com.google.android.material.chip.Chip.initOutlineProvider
22704-06 13:58:35.090 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.chip.Chip.updateFrameworkRippleBackground
22804-06 13:58:35.100 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.chip.ChipDrawable.updateFrameworkCloseIconRipple
22904-06 13:58:35.770 2471-2498/com.appsbharti.bharatbankdetails E/AndroidRuntime: FATAL EXCEPTION: arch_disk_io_2
230 android.database.sqlite.SQLiteConstraintException: foreign key constraint failed (code 19)
231 at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
232 at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:775)
233 at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
234 at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
235 at androidx.sqlite.db.framework.FrameworkSQLiteStatement.executeInsert(FrameworkSQLiteStatement.java:51)
236 at androidx.room.EntityInsertionAdapter.insert(EntityInsertionAdapter.java:64)
237 at com.appsbharti.bharatbankdetails.Daos.HistoryDao_Impl.insert(HistoryDao_Impl.java:48)
238 at com.appsbharti.bharatbankdetails.Repositories.HistoryRepository$1.run(HistoryRepository.java:41)
239 at androidx.room.TransactionExecutor$1.run(TransactionExecutor.java:45)
240 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
241 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
242 at java.lang.Thread.run(Thread.java:856)
24304-06 13:58:39.170 1395-1481/system_process E/ThrottleService: problem during onPollAlarm: java.lang.IllegalStateException: problem parsing stats: java.io.FileNotFoundException: /proc/net/xt_qtaguid/iface_stat_all: open failed: ENOENT (No such file or directory)
244--------- beginning of crash
2452021-04-07 17:05:06.152 4247-4279/com.appsbharti.bharatbankdetails E/AndroidRuntime: FATAL EXCEPTION: arch_disk_io_2
246 Process: com.appsbharti.bharatbankdetails, PID: 4247
247 android.database.sqlite.SQLiteReadOnlyDatabaseException: attempt to write a readonly database (code 1032 SQLITE_READONLY_DBMOVED)
248 at android.database.sqlite.SQLiteConnection.nativeExecuteForString(Native Method)
249 at android.database.sqlite.SQLiteConnection.executeForString(SQLiteConnection.java:655)
250 at android.database.sqlite.SQLiteConnection.setJournalMode(SQLiteConnection.java:336)
251 at android.database.sqlite.SQLiteConnection.setWalModeFromConfiguration(SQLiteConnection.java:298)
252 at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:217)
253 at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:195)
254 at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:503)
255 at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:204)
256 at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:196)
257 at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:880)
258 at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:865)
259 at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:739)
260 at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:729)
261 at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:355)
262 at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:298)
263 at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:92)
264 at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:53)
265 at androidx.room.SQLiteCopyOpenHelper.getWritableDatabase(SQLiteCopyOpenHelper.java:90)
266 at androidx.room.RoomDatabase.inTransaction(RoomDatabase.java:476)
267 at androidx.room.RoomDatabase.assertNotSuspendingTransaction(RoomDatabase.java:281)
268 at com.appsbharti.bharatbankdetails.Daos.HistoryDao_Impl.insert(HistoryDao_Impl.java:45)
269 at com.appsbharti.bharatbankdetails.Repositories.HistoryRepository$1.run(HistoryRepository.java:37)
270 at androidx.room.TransactionExecutor$1.run(TransactionExecutor.java:45)
271 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
272 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
273 at java.lang.Thread.run(Thread.java:764)
274CREATE TABLE "android_metadata" (
275 "locale" TEXT
276);
277
and added en_US
entry to locale column.
ANSWER
Answered 2021-Apr-07 at 13:14OK there was a simple issue behind those all errors. I haven't fetched AppDatabase inside synchronized
block.
Inside AppDatabse class, I changed newInsance
method from:
1public class BranchDetailsFragment extends Fragment implements View.OnClickListener {
2
3 private final Application application;
4 private final int branchIid;
5
6 private FragBranchDetailsBinding binding;//view-binding
7
8 public BranchDetailsFragment(Application application, int branchIid) {
9 //saving branchId
10 }
11
12 @Nullable
13 @Override
14 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
15 //normal stuff
16 }
17
18 @Override
19 public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
20 super.onViewCreated(view, savedInstanceState);
21 BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);
22
23 //inserting entry in history table
24 HistoryViewModel historyViewModel = new HistoryViewModel(application);
25 History history = new History();
26 history.setBranchId(branchIid);
27 historyViewModel.insert(history);
28
29 //fetching data from branches table
30 branchDetailsViewModel.getBranchCustomizedById(branchIid).observe(getViewLifecycleOwner(), new Observer<BranchCustomized>() {
31 @Override
32 public void onChanged(BranchCustomized branchCustomized) {
33 //get branch details and show them
34 }
35 });
36 }
37}
38@Entity(tableName = "branches")
39public class Branch {
40 @PrimaryKey(autoGenerate = true)
41 @ColumnInfo(name = "_id")
42 private int id;
43
44 @ColumnInfo(name = "bank_id")
45 private int bankId;
46
47 public int getId() {
48 return id;
49 }
50
51 public void setId(int id) {
52 this.id = id;
53 }
54
55 public int getBankId() {
56 return bankId;
57 }
58
59 public void setBankId(int bankId) {
60 this.bankId = bankId;
61 }
62
63}
64@Entity(tableName = "history", foreignKeys = @ForeignKey(entity = Branch.class, parentColumns = "_id", childColumns = "branch_id"))
65public class History {
66 @PrimaryKey(autoGenerate = true)
67 @ColumnInfo(name = "_id")
68 private int id;
69
70 @ColumnInfo(name = "branch_id")
71 private int branchId;
72
73 public int getId() {
74 return id;
75 }
76
77 public void setId(int id) {
78 this.id = id;
79 }
80
81 public int getBranchId() {
82 return branchId;
83 }
84
85 public void setBranchId(int branchId) {
86 this.branchId = branchId;
87 }
88}
89public class HistoryViewModel extends AndroidViewModel {
90 final HistoryRepository repository;
91
92 public HistoryViewModel(Application application) {
93 super(application);
94 repository = new HistoryRepository(application);
95 }
96
97 public LiveData<List<HistoryCustomized>> getAll(){
98 return repository.getAll();
99 }
100
101 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token){
102 return repository.searchHistoryByBankOrBranch(token);
103 }
104
105 public void insert(History history){
106 repository.insert(history);
107 }
108}
109public class HistoryRepository {
110 private final HistoryDao dao;
111 AppDatabase db;
112
113
114 public HistoryRepository(Application application) {
115 db = AppDatabase.getInstance(application);
116 dao = db.getHistoryDao();
117 }
118
119 public LiveData<List<HistoryCustomized>> getAll() {
120 return dao.getAll();
121 }
122
123 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token) {
124 return dao.searchHistoryByBankOrBranch(token);
125 }
126
127 public void insert(History history){
128 try {
129 db.getTransactionExecutor().execute(new Runnable() {
130 @Override
131 public void run() {
132 dao.insert(history);
133 }
134 });
135 }catch (NullPointerException e){
136 e.printStackTrace();
137 }
138 }
139}
140@Dao
141public interface HistoryDao {
142 @Query("select history.branch_id, bank, branch from history\n" +
143 "join branches on branches._id=history.branch_id\n" +
144 "join banks on banks._id=branches.bank_id")
145 LiveData<List<HistoryCustomized>> getAll();
146
147 @Query("select history.branch_id, bank, branch from history\n" +
148 "join branches on branches._id=history.branch_id\n" +
149 "join banks on banks._id=branches.bank_id\n" +
150 "where bank like :token or branch like :token")
151 LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token);
152
153 @Transaction
154 @Insert
155 void insert(History history);
156}
157@Database(entities = {Branch.class, History.class},
158 version = 1, exportSchema = false)
159public abstract class AppDatabase extends RoomDatabase {
160
161 public abstract BranchesDao getBranchesDao();
162 public abstract HistoryDao getHistoryDao();
163
164 public static AppDatabase getInstance(final Context context) {
165 dbInstance = buildDatabaseInstance(context);
166 return dbInstance;
167 }
168
169 private static AppDatabase buildDatabaseInstance(Context context) {
170 return Room.databaseBuilder(context,
171 AppDatabase.class,
172 "branch.db")
173 .createFromAsset("branch.db")
174 .fallbackToDestructiveMigration()
175 .build();
176 }
177
178 public static void cleanUp() {
179 dbInstance = null;
180 }
181
182}
183@SuppressWarnings({"unchecked", "deprecation"})
184public final class HistoryDao_Impl implements HistoryDao {
185 private final RoomDatabase __db;
186
187 private final EntityInsertionAdapter<History> __insertionAdapterOfHistory;
188
189 public HistoryDao_Impl(RoomDatabase __db) {
190 this.__db = __db;
191 this.__insertionAdapterOfHistory = new EntityInsertionAdapter<History>(__db) {
192 @Override
193 public String createQuery() {
194 return "INSERT OR ABORT INTO `history` (`_id`,`branch_id`) VALUES (nullif(?, 0),?)";
195 }
196
197 @Override
198 public void bind(SupportSQLiteStatement stmt, History value) {
199 stmt.bindLong(1, value.getId());
200 stmt.bindLong(2, value.getBranchId());
201 }
202 };
203 }
204
205 @Override
206 public void insert(final History history) {
207 __db.assertNotSuspendingTransaction();
208 __db.beginTransaction();
209 try {
210 __insertionAdapterOfHistory.insert(history);
211 __db.setTransactionSuccessful();
212 } finally {
213 __db.endTransaction();
214 }
215 }
216
217 @Override
218 protected void finalize() {
219 _statement.release();
220 }
221 });
222 }
223}
22404-06 13:58:35.080 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.button.MaterialButtonHelper.createBackground
22504-06 13:58:35.080 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.button.MaterialButtonHelper.setRippleColor
22604-06 13:58:35.090 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'com.google.android.material.chip.Chip$2', referenced from method com.google.android.material.chip.Chip.initOutlineProvider
22704-06 13:58:35.090 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.chip.Chip.updateFrameworkRippleBackground
22804-06 13:58:35.100 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.chip.ChipDrawable.updateFrameworkCloseIconRipple
22904-06 13:58:35.770 2471-2498/com.appsbharti.bharatbankdetails E/AndroidRuntime: FATAL EXCEPTION: arch_disk_io_2
230 android.database.sqlite.SQLiteConstraintException: foreign key constraint failed (code 19)
231 at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
232 at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:775)
233 at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
234 at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
235 at androidx.sqlite.db.framework.FrameworkSQLiteStatement.executeInsert(FrameworkSQLiteStatement.java:51)
236 at androidx.room.EntityInsertionAdapter.insert(EntityInsertionAdapter.java:64)
237 at com.appsbharti.bharatbankdetails.Daos.HistoryDao_Impl.insert(HistoryDao_Impl.java:48)
238 at com.appsbharti.bharatbankdetails.Repositories.HistoryRepository$1.run(HistoryRepository.java:41)
239 at androidx.room.TransactionExecutor$1.run(TransactionExecutor.java:45)
240 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
241 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
242 at java.lang.Thread.run(Thread.java:856)
24304-06 13:58:39.170 1395-1481/system_process E/ThrottleService: problem during onPollAlarm: java.lang.IllegalStateException: problem parsing stats: java.io.FileNotFoundException: /proc/net/xt_qtaguid/iface_stat_all: open failed: ENOENT (No such file or directory)
244--------- beginning of crash
2452021-04-07 17:05:06.152 4247-4279/com.appsbharti.bharatbankdetails E/AndroidRuntime: FATAL EXCEPTION: arch_disk_io_2
246 Process: com.appsbharti.bharatbankdetails, PID: 4247
247 android.database.sqlite.SQLiteReadOnlyDatabaseException: attempt to write a readonly database (code 1032 SQLITE_READONLY_DBMOVED)
248 at android.database.sqlite.SQLiteConnection.nativeExecuteForString(Native Method)
249 at android.database.sqlite.SQLiteConnection.executeForString(SQLiteConnection.java:655)
250 at android.database.sqlite.SQLiteConnection.setJournalMode(SQLiteConnection.java:336)
251 at android.database.sqlite.SQLiteConnection.setWalModeFromConfiguration(SQLiteConnection.java:298)
252 at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:217)
253 at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:195)
254 at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:503)
255 at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:204)
256 at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:196)
257 at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:880)
258 at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:865)
259 at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:739)
260 at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:729)
261 at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:355)
262 at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:298)
263 at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:92)
264 at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:53)
265 at androidx.room.SQLiteCopyOpenHelper.getWritableDatabase(SQLiteCopyOpenHelper.java:90)
266 at androidx.room.RoomDatabase.inTransaction(RoomDatabase.java:476)
267 at androidx.room.RoomDatabase.assertNotSuspendingTransaction(RoomDatabase.java:281)
268 at com.appsbharti.bharatbankdetails.Daos.HistoryDao_Impl.insert(HistoryDao_Impl.java:45)
269 at com.appsbharti.bharatbankdetails.Repositories.HistoryRepository$1.run(HistoryRepository.java:37)
270 at androidx.room.TransactionExecutor$1.run(TransactionExecutor.java:45)
271 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
272 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
273 at java.lang.Thread.run(Thread.java:764)
274CREATE TABLE "android_metadata" (
275 "locale" TEXT
276);
277public static AppDatabase getInstance(final Context context) {
278 dbInstance = buildDatabaseInstance(context);
279 return dbInstance;
280}
281
to
1public class BranchDetailsFragment extends Fragment implements View.OnClickListener {
2
3 private final Application application;
4 private final int branchIid;
5
6 private FragBranchDetailsBinding binding;//view-binding
7
8 public BranchDetailsFragment(Application application, int branchIid) {
9 //saving branchId
10 }
11
12 @Nullable
13 @Override
14 public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
15 //normal stuff
16 }
17
18 @Override
19 public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
20 super.onViewCreated(view, savedInstanceState);
21 BranchDetailsViewModel branchDetailsViewModel = new BranchDetailsViewModel(application);
22
23 //inserting entry in history table
24 HistoryViewModel historyViewModel = new HistoryViewModel(application);
25 History history = new History();
26 history.setBranchId(branchIid);
27 historyViewModel.insert(history);
28
29 //fetching data from branches table
30 branchDetailsViewModel.getBranchCustomizedById(branchIid).observe(getViewLifecycleOwner(), new Observer<BranchCustomized>() {
31 @Override
32 public void onChanged(BranchCustomized branchCustomized) {
33 //get branch details and show them
34 }
35 });
36 }
37}
38@Entity(tableName = "branches")
39public class Branch {
40 @PrimaryKey(autoGenerate = true)
41 @ColumnInfo(name = "_id")
42 private int id;
43
44 @ColumnInfo(name = "bank_id")
45 private int bankId;
46
47 public int getId() {
48 return id;
49 }
50
51 public void setId(int id) {
52 this.id = id;
53 }
54
55 public int getBankId() {
56 return bankId;
57 }
58
59 public void setBankId(int bankId) {
60 this.bankId = bankId;
61 }
62
63}
64@Entity(tableName = "history", foreignKeys = @ForeignKey(entity = Branch.class, parentColumns = "_id", childColumns = "branch_id"))
65public class History {
66 @PrimaryKey(autoGenerate = true)
67 @ColumnInfo(name = "_id")
68 private int id;
69
70 @ColumnInfo(name = "branch_id")
71 private int branchId;
72
73 public int getId() {
74 return id;
75 }
76
77 public void setId(int id) {
78 this.id = id;
79 }
80
81 public int getBranchId() {
82 return branchId;
83 }
84
85 public void setBranchId(int branchId) {
86 this.branchId = branchId;
87 }
88}
89public class HistoryViewModel extends AndroidViewModel {
90 final HistoryRepository repository;
91
92 public HistoryViewModel(Application application) {
93 super(application);
94 repository = new HistoryRepository(application);
95 }
96
97 public LiveData<List<HistoryCustomized>> getAll(){
98 return repository.getAll();
99 }
100
101 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token){
102 return repository.searchHistoryByBankOrBranch(token);
103 }
104
105 public void insert(History history){
106 repository.insert(history);
107 }
108}
109public class HistoryRepository {
110 private final HistoryDao dao;
111 AppDatabase db;
112
113
114 public HistoryRepository(Application application) {
115 db = AppDatabase.getInstance(application);
116 dao = db.getHistoryDao();
117 }
118
119 public LiveData<List<HistoryCustomized>> getAll() {
120 return dao.getAll();
121 }
122
123 public LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token) {
124 return dao.searchHistoryByBankOrBranch(token);
125 }
126
127 public void insert(History history){
128 try {
129 db.getTransactionExecutor().execute(new Runnable() {
130 @Override
131 public void run() {
132 dao.insert(history);
133 }
134 });
135 }catch (NullPointerException e){
136 e.printStackTrace();
137 }
138 }
139}
140@Dao
141public interface HistoryDao {
142 @Query("select history.branch_id, bank, branch from history\n" +
143 "join branches on branches._id=history.branch_id\n" +
144 "join banks on banks._id=branches.bank_id")
145 LiveData<List<HistoryCustomized>> getAll();
146
147 @Query("select history.branch_id, bank, branch from history\n" +
148 "join branches on branches._id=history.branch_id\n" +
149 "join banks on banks._id=branches.bank_id\n" +
150 "where bank like :token or branch like :token")
151 LiveData<List<HistoryCustomized>> searchHistoryByBankOrBranch(String token);
152
153 @Transaction
154 @Insert
155 void insert(History history);
156}
157@Database(entities = {Branch.class, History.class},
158 version = 1, exportSchema = false)
159public abstract class AppDatabase extends RoomDatabase {
160
161 public abstract BranchesDao getBranchesDao();
162 public abstract HistoryDao getHistoryDao();
163
164 public static AppDatabase getInstance(final Context context) {
165 dbInstance = buildDatabaseInstance(context);
166 return dbInstance;
167 }
168
169 private static AppDatabase buildDatabaseInstance(Context context) {
170 return Room.databaseBuilder(context,
171 AppDatabase.class,
172 "branch.db")
173 .createFromAsset("branch.db")
174 .fallbackToDestructiveMigration()
175 .build();
176 }
177
178 public static void cleanUp() {
179 dbInstance = null;
180 }
181
182}
183@SuppressWarnings({"unchecked", "deprecation"})
184public final class HistoryDao_Impl implements HistoryDao {
185 private final RoomDatabase __db;
186
187 private final EntityInsertionAdapter<History> __insertionAdapterOfHistory;
188
189 public HistoryDao_Impl(RoomDatabase __db) {
190 this.__db = __db;
191 this.__insertionAdapterOfHistory = new EntityInsertionAdapter<History>(__db) {
192 @Override
193 public String createQuery() {
194 return "INSERT OR ABORT INTO `history` (`_id`,`branch_id`) VALUES (nullif(?, 0),?)";
195 }
196
197 @Override
198 public void bind(SupportSQLiteStatement stmt, History value) {
199 stmt.bindLong(1, value.getId());
200 stmt.bindLong(2, value.getBranchId());
201 }
202 };
203 }
204
205 @Override
206 public void insert(final History history) {
207 __db.assertNotSuspendingTransaction();
208 __db.beginTransaction();
209 try {
210 __insertionAdapterOfHistory.insert(history);
211 __db.setTransactionSuccessful();
212 } finally {
213 __db.endTransaction();
214 }
215 }
216
217 @Override
218 protected void finalize() {
219 _statement.release();
220 }
221 });
222 }
223}
22404-06 13:58:35.080 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.button.MaterialButtonHelper.createBackground
22504-06 13:58:35.080 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.button.MaterialButtonHelper.setRippleColor
22604-06 13:58:35.090 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'com.google.android.material.chip.Chip$2', referenced from method com.google.android.material.chip.Chip.initOutlineProvider
22704-06 13:58:35.090 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.chip.Chip.updateFrameworkRippleBackground
22804-06 13:58:35.100 2471-2471/com.appsbharti.bharatbankdetails E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.google.android.material.chip.ChipDrawable.updateFrameworkCloseIconRipple
22904-06 13:58:35.770 2471-2498/com.appsbharti.bharatbankdetails E/AndroidRuntime: FATAL EXCEPTION: arch_disk_io_2
230 android.database.sqlite.SQLiteConstraintException: foreign key constraint failed (code 19)
231 at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
232 at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:775)
233 at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
234 at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
235 at androidx.sqlite.db.framework.FrameworkSQLiteStatement.executeInsert(FrameworkSQLiteStatement.java:51)
236 at androidx.room.EntityInsertionAdapter.insert(EntityInsertionAdapter.java:64)
237 at com.appsbharti.bharatbankdetails.Daos.HistoryDao_Impl.insert(HistoryDao_Impl.java:48)
238 at com.appsbharti.bharatbankdetails.Repositories.HistoryRepository$1.run(HistoryRepository.java:41)
239 at androidx.room.TransactionExecutor$1.run(TransactionExecutor.java:45)
240 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
241 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
242 at java.lang.Thread.run(Thread.java:856)
24304-06 13:58:39.170 1395-1481/system_process E/ThrottleService: problem during onPollAlarm: java.lang.IllegalStateException: problem parsing stats: java.io.FileNotFoundException: /proc/net/xt_qtaguid/iface_stat_all: open failed: ENOENT (No such file or directory)
244--------- beginning of crash
2452021-04-07 17:05:06.152 4247-4279/com.appsbharti.bharatbankdetails E/AndroidRuntime: FATAL EXCEPTION: arch_disk_io_2
246 Process: com.appsbharti.bharatbankdetails, PID: 4247
247 android.database.sqlite.SQLiteReadOnlyDatabaseException: attempt to write a readonly database (code 1032 SQLITE_READONLY_DBMOVED)
248 at android.database.sqlite.SQLiteConnection.nativeExecuteForString(Native Method)
249 at android.database.sqlite.SQLiteConnection.executeForString(SQLiteConnection.java:655)
250 at android.database.sqlite.SQLiteConnection.setJournalMode(SQLiteConnection.java:336)
251 at android.database.sqlite.SQLiteConnection.setWalModeFromConfiguration(SQLiteConnection.java:298)
252 at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:217)
253 at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:195)
254 at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:503)
255 at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:204)
256 at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:196)
257 at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:880)
258 at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:865)
259 at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:739)
260 at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:729)
261 at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:355)
262 at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:298)
263 at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:92)
264 at androidx.sqlite.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:53)
265 at androidx.room.SQLiteCopyOpenHelper.getWritableDatabase(SQLiteCopyOpenHelper.java:90)
266 at androidx.room.RoomDatabase.inTransaction(RoomDatabase.java:476)
267 at androidx.room.RoomDatabase.assertNotSuspendingTransaction(RoomDatabase.java:281)
268 at com.appsbharti.bharatbankdetails.Daos.HistoryDao_Impl.insert(HistoryDao_Impl.java:45)
269 at com.appsbharti.bharatbankdetails.Repositories.HistoryRepository$1.run(HistoryRepository.java:37)
270 at androidx.room.TransactionExecutor$1.run(TransactionExecutor.java:45)
271 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
272 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
273 at java.lang.Thread.run(Thread.java:764)
274CREATE TABLE "android_metadata" (
275 "locale" TEXT
276);
277public static AppDatabase getInstance(final Context context) {
278 dbInstance = buildDatabaseInstance(context);
279 return dbInstance;
280}
281public static AppDatabase getInstance(final Context context) {
282 if (dbInstance == null)
283 synchronized (AppDatabase.class) {
284 if (dbInstance == null)
285 dbInstance = buildDatabaseInstance(context);
286 }
287// dbInstance = buildDatabaseInstance(context);
288 return dbInstance;
289}
290
Problem is that, Room implicitly call getReadableDatabase()
not getWritableDatabse()
of SqliteOpenHelper
class while fetching query results.
To fetched BranchDetails, I created AppDatabase instance with read-only access inside BranchDetailsRepository.
I fetched same read-only instance inside HistoryRepository(as AppDatbase follows Singleton patter).
So when I called insert(History history)
, it throws error.
There was no issue of Foreign Key.
Trigger which I created using SqliteStudio also working fine without any problem, no issue with that either.
QUESTION
Where to Save ViewModel State in Android's MVVM?
Asked 2020-Dec-25 at 07:21As a beginner to Android development, I am trying to clean up my codebase from my first app by converting it to the recommended MVVM structure. What I am currently stuck on, is trying to figure out the best way to store my view model's state.
In this example, the state I need to store is simply an ArrayList of strings (indicating which checkboxes in a recyclerview are checked). I am currently storing this ArrayList inside of my ViewModel as a field, wrapped inside of a MutableLivedata object, which my activity observes. This method of storing the ViewModel state as a field does not seem viable in the long run. I can imagine as my app grows my ViewModel classes would get quite bloated and messy.
I currently use a Firebase Realtime Database to store my data that I need persisted, accessed through a repository just as Android Architecture recommends. My ViewModel's state, however, does not need to be persisted after the app closes, so it would definitely not make sense to make network calls to my Firebase Database for it.
My question is: Where would make the most sense to save my ViewModel's state? The semi-sensible options I see in front of me are saving it as fields in my ViewModel class (my current approach), saving it in a Room database (and resetting the database each time the app is killed), or saving it as fields in my repository class (doesn't seem right). I'm open to suggestions!
ANSWER
Answered 2020-Dec-25 at 07:21It depends on your needs:
- If you want to keep state just for configuration changes, you do not need to do anything more. ViewModel will handle it for you.
- If you want to see the same state when you come back to that screen after closing it, then I would recommend to use a local cache solution such as Room. You can create a repository on top of room and inject it into your Viewmodel.
- If you want to keep state until application closes, you can also create an in-memory repository (a singleton repo with the state). When application is killed that memory will be reclaimed by the OS so that they will be cleared.
In any case storing data remotely does not seem to be the the solution that you are looking for.
I would also not rely on memory cache solution because of Android system memory reclaim situations.
You can go with the cache solution and clear your cache when you open the app again.
QUESTION
Android (Kotlin): Type mismatch in Observer
Asked 2020-Dec-16 at 04:36I am implementing an MVVM Android architecture in which in the main application component (MainActivity
), I listen to the ModelView
's LiveData
storage for any changes. However, in the following piece of code:
1private final var viewModel:ScheduleViewModel = ViewModelProviders.of(this).get(ScheduleViewModel::class.java)
2
3viewModel.getSchedule().observe(this, object:Observer<String> {
4 fun onChanged(feed:String){
5 }
6})
7
I get the following error:
1private final var viewModel:ScheduleViewModel = ViewModelProviders.of(this).get(ScheduleViewModel::class.java)
2
3viewModel.getSchedule().observe(this, object:Observer<String> {
4 fun onChanged(feed:String){
5 }
6})
7Required: Observer<in String!>
8Found:
9
Below are my imports:
1private final var viewModel:ScheduleViewModel = ViewModelProviders.of(this).get(ScheduleViewModel::class.java)
2
3viewModel.getSchedule().observe(this, object:Observer<String> {
4 fun onChanged(feed:String){
5 }
6})
7Required: Observer<in String!>
8Found:
9import android.os.Build
10import android.os.Bundle
11import android.util.Base64
12import androidx.annotation.Nullable
13import androidx.appcompat.app.AppCompatActivity
14import androidx.lifecycle.ViewModelProviders
15import androidx.loader.app.LoaderManager
16import androidx.loader.content.Loader
17import androidx.viewpager.widget.ViewPager
18import com.example.mvvmarchitecture.ui.main.TabsAdapter
19import com.google.android.material.tabs.TabLayout
20import java.io.InputStream
21import java.net.HttpURLConnection
22import java.net.URL
23import java.util.*
24
ANSWER
Answered 2020-Dec-16 at 03:36To fix that, replace Observer<String>
with Observer<in String>
.
But even easier, use a lambda instead of an anonymous object, so you don't have to worry about matching up the type:
1private final var viewModel:ScheduleViewModel = ViewModelProviders.of(this).get(ScheduleViewModel::class.java)
2
3viewModel.getSchedule().observe(this, object:Observer<String> {
4 fun onChanged(feed:String){
5 }
6})
7Required: Observer<in String!>
8Found:
9import android.os.Build
10import android.os.Bundle
11import android.util.Base64
12import androidx.annotation.Nullable
13import androidx.appcompat.app.AppCompatActivity
14import androidx.lifecycle.ViewModelProviders
15import androidx.loader.app.LoaderManager
16import androidx.loader.content.Loader
17import androidx.viewpager.widget.ViewPager
18import com.example.mvvmarchitecture.ui.main.TabsAdapter
19import com.google.android.material.tabs.TabLayout
20import java.io.InputStream
21import java.net.HttpURLConnection
22import java.net.URL
23import java.util.*
24viewModel.getSchedule().observe(this) { feed ->
25 //...
26}
27
Community Discussions contain sources that include Stack Exchange Network
Tutorials and Learning Resources in Android Architecture
Tutorials and Learning Resources are not available at this moment for Android Architecture