How to do a Room request inside of a class method? - android

I follower exactly this tutorial in order to implement Room in my Android project :
https://www.techiediaries.com/android-room-tutorial/
I want to have a method inside my class Traject that takes a List of TrajectJson and add it to the Database using my trajectDao.
But the problem is i cant access the database in my class method because it needs a context.
Is there a way to get the instance of my database without a context?

Related

How to share the same instance of a data class across all my view models?

I'm very new to android development and struggling to find this answer. Is it possible to share the same instance of a data class across all my view models?
Currently when my app first starts, I'm fetching my user's app preferences from a Firestore DB and instantiating a data class instance I have defined to hold all user preferences. I want to have all my view models to have access to the user preferences without every view model having to make the Firestore DB call and creating its own data class instance. Is it possible to share the same instance of a data class between all of my view models?
I could use dagger hilt to to fetch the preferences from Firestore, create my data class instance, and provide that as a dependency of injection....but if a user updates their preferences after loading the app then those updates won't reflect in the data class instance that is injected via dagger hilt, correct?
Admittedly I might be going about this the wrong way. I'm ultimately trying to understand what the best way to share my app preferences that are stored in an external DB to all of my view models.
After getting the data in your viewModel , initialize the related viewmodel in your fragment as activityViewModel as below;
val shareViewModel by activityViewModels<ShareViewModel>()
If you use it in your activity just set this for owner parameter as below;
val shareViewModel = ViewModelProvider(this)[ShareViewModel::class.java]
It provides you sharing data across your app
Moreover, check this codelab https://developer.android.com/codelabs/basic-android-kotlin-training-shared-viewmodel

Saving data in the Application scope in Android

I am building an application in Android with multiple activities. I have a list of an object of type TodoItem that I get from a collection in Firestore database, and I need to access the list from more than one activity to make changes and updates to the list.
To do that, I thought about saving the list in the Application scope (is it a good idea?). For this reason, I created a class MyApplication extends Application (and added it to the Manifest file).
Instead of just adding the list as a class field of MyApplication I thought that maybe I should create a class named DataManager that will hold application-wide information such as my list of TodoItems (and here I ask again: is it a good idea? or maybe there is a better solution?).
At this point I am trying to decide what is a better approach to create and save the DataManager class:
One idea is to make DataManager a Singleton class and save it as a class field of MyApplication. This way, the activities will be able to get the instance of the class using DataManager.getInstance() without the need to get it from the application class with a getter method. In this approach, I will have to create the instance of DataManager and init the field of the application with it in the OnCreate() method of the application.
The second idea is to make it a non-singleton, add DataManager field to MyApplication, and create a getter named getDataManager() in the application class. The getter will check if the field is null (i.e. already initialized or not) and will create a new instance correspondingly. This way, the activities will get the instance using ((MyApplication) getApplication()).getDataManager().
I would like to hear what do you think about my approaches to solve the problem, and if you have any other suggestions or other ways to improve my suggested design.
A nice way when your data source is simple. You can create a singleton class to hold and manage data, including read and write from the singleton.
When you want to use complex data, you can store it to your device disk rather than memory. Android application support you to store your data with file, database, or key-value preference. As for your case, you can use database to store your todolist. Android support sqlite for these work, and we have official orm library called room.
raw sqlite: https://developer.android.com/training/data-storage/sqlite
room library: https://developer.android.com/topic/libraries/architecture/room

Context Related Problems inside MVP presenter

I am new to android MVP pattern and working on my project i have some basic problem related to Android Context in the presenter. Although there are many answers related to this but i didn't get a perfect one which can solve my problem.
I have following queries:
how to access shared preferences inside presenter.
how to access other system services inside presenter.
if i am working on SQLite Databases then during any transaction in my database which is done by call from presenter to my SQLite Helper class need context to access database.
If i will pass my activity context in presenter then it will a problem during unit testing, also it is a violation according to MVP Format.
I need a perfect solution so that my code quality is not degraded.
Note: I dont want to use dagger tool so the answer should be dagger independent
In MVP you dont use Context or anything else from the Android SDK/Framework in the Presenter (P) layer! This layer is for anything else than Android related stuff.
1) how to access shared preferences inside presenter.
You don't. If you need a value from a SharedPrefences in the Presenter then you could pass the value to the Presenter via a method call.
Example:
class MainActivity{
String birthday = SharedPrefence.getString(..);
presenter.setSavedBirtday(birthday);
}
2) how to access other system services inside presenter.
As metioned before; You don't acesss System services in the Presenter.
What you can do is call the a System Service from the Presenter.
Example with Vibrator:
1 - Create an interface:
interface OnSystemServiceCaller{
onVibratorCall();
}
2 - Implement it in a Activity
class MainActivity implements OnSystemServiceCaller{
#Override
onVibratorCall(){
Vibrator v = (Vibrator) getSystemService(VIBRATOR);
v.vibrate(50);
}
}
3 - Call from presenter
class Presenter{
OnSystemServiceCaller listener;
public void ifButtonClicked(){
listener.onVibrateCall();
}
}
3) if i am working on SQLite Databases then during any transaction in my database which is done by call from presenter to my SQLite Helper class need context to access database.
Some wont like this answers other will, this is just a suggestion.
You can access your SQLite by using a global ApplicationContext() in your app class (Class that extend Application; see how here since your SQLlite is global for the whole app and not just a particular Activity And when you need to pass data from SQLite to a Activity then you pass it first to the Presenter and from Presenter to your Activity the same way we send a call to our Vibrator method

Correct way of retrieving certain objects from db in Android using AndroidAnnotations and GreenDAO

I'm having trouble in designing my app for Android.
I'm using AndroidAnnotations and greenDAO.
I have an activity which has a GridView. This GridView is populated with Objects retrieved from the database, using greenDAO. When the user click an item, I open other activity, passing the id of the item that was clicked using an intent extra (I tried passing the whole object, using Serializable, but I got an error in greenDAO). This other activity should display a list of objects that are from the first object.
Explaining better:
Object A has a field orders (List) that are a ToMany relation in GreenDao.
The user clicks the Object A and should be redirected to a screen that has this list of Orders.
My idea is to pass the Object A id to the other activity and retrieve it again from the database.
To the view list I'm using the exact code of https://github.com/excilys/androidannotations/wiki/Adapters-and-lists, that consists of:
ObjectItemView class (extends LinearLayout) annotated with #EViewGroup
ObjectFinder class (has all the things needed for greenDAO), annotated with #EBean
ObjectListAdapter (extends BaseAdapter) annotated with #EBean
ObjectListActivity (extends Activity) annotated with #EActivity
ObjectFinder has a method that returns a list of objects.
ObjectListAdapter injects the ObjectFinder using the #Bean annotation and uses it to populate a list of objects.
ObjectListActivity then injects the ObjectListAdapter and set this adapter to the ObjectList.
This works well if you want to retrieve all the entities of the database, using a findAll method.
The problem is that a need a particular entity and #EBean classes do not allow to pass any parameter in the builder, so I can't 'reach' the finder or the builder to tell it what entity to retrieve.
What should I do?

open sqlite database in android

How can i open a database in a class that is not a subclass of Activity?
In a subclass of Activity, i can use openOrCreateDatabase() but can i open a database in a different class?
I tried making the database instance a static one and open it in an Activity and get the static instance in the other class, but it throws an exception stating the database is closed.
Check out this tutorial.
I went through it and it's a really good tutorial on how to use SQLite in Android.
Essentially you need to create a database helper class that will do the table creation. Then you can use this helper class in your Activity to create your database and or tables.
It's common practice to use a SQLite Database Adapter and sometimes a helper class that is separate from the activity that is utilizing the database. Here is a link to a example that uses the code. THe vogella tutorial is also good but the use of a ContentProvider makes it a bit tough to understand what things need to be in there for a SQLite DB only.
Essentially, the helper class is responsible for creating, updating and deleting the DB while the adapter class handles the methods for changing values, deleting rows, and actually calling the helper to open the database.

Categories

Resources