So i have a class like this
class Fragment{
private val binding: MyFragmentBinding
}
MyFragmentBinding has a private field "webView", which I want to access.
First step:
val firstField = fragment.javaClass.getDeclaredField("binding")
This works and I got a field with my binding class. But in this class I want to access the field with the name "webView".
How can I do this?
Get the referenced object, and then repeat the whole process for the field in that object.
val binding = fragment.javaClass.getDeclaredField("binding").get(fragment)
val webView = binding.javaClass.getDeclaredField("webView").get(binding)
Related
When my application starts I create object with some data and I want to share the same instance of object between services/viewModels.
Is it possible to inject the same instance of data class to viewModel using Koin?
Edit:
I create user object in MainViewModel when app loaded data from firebase at start.
#IgnoreExtraProperties
#Keep
data class User(
val id: String = "",
val name: String? = null,
val surname: String? = null,
val email: String? = null,
val avatarUrl: String? = null
)
If your view model inherits from KoinComponent, you can access getKoin method to declare your user object.
class MainViewModel : ViewModel(), KoinComponent {
The user object will be available to rest of your application after declaration.
// user created from data from firebase ...
fun insertKoinFor(user: User) {
// declare koin the user of type User
getKoin().declare<User>(user)
// or declare with a named qualifier
getKoin().declare(user, named("myUser"))
}
Hope, it helps.
I would create a holder object, say UserManager, to hold an optional User instance. This holder is something you can provide in your koin graph as single, and whatever component responsible setting up the User instance (for example your MainViewModel) can update the instance inside the singleton holder.
I am currently building an app and I have added Dagger Hilt in order to define a single class to access data. the injection seems working fine but I am not able to store a value in the data class I use.
I have created a Singleton first, which is used by the code to set/get value from a data structure.
#Singleton
class CarListMemorySource #Inject constructor() : CarListInterface {
private var extendedCarList: ExtendedCarList? = null
override fun setListOfVehicles(listOfVehicles: List<item>)
{
extendedCarList?.listOfVehicles = listOfVehicles
}
}
When I am calling setListOfVehicles the listOfVehicules contains 10 items but
The data structure ExtendedCarList is defined as below:
data class ExtendedCarList(
var listOfVehicles: List<item>
)
The Singleton in passed using Hilt like for example in the viewModel below:
#HiltViewModel
class HomeScreenViewModel #Inject constructor(
private val carList: CarListMemorySource
): ViewModel() {
fun getList() {
--> DO SOMETHING TO Get A ListA
carList.setListOfVehicles(ListA)
}
}
And in the activity, using the viewModel, I am just doing this:
#AndroidEntryPoint
class HomeScreenActivity: AppCompatActivity() {
private val viewModel: HomeScreenViewModel by viewModels()
....
viewModel.getList()
....
}
Any idea why and how to fix it ?
Thanks
you never initialize extendedCarList.
extendedCarList?.listOfVehicles = listOfVehicles
above line is exactly the same as
if (extendedCarList != null) extendedCarList.listOfVehicles = listOfVehicles
But it never passes the null check.
I think just changing
private var extendedCarList: ExtendedCarList? = null
to
private val extendedCarList = ExtendedCarList()
might solve it
I want to check the lateinit propery initialized or not inside an extension method.
I want to execute simple function call to lateinit property safely inside an extenstion method.
I can use this::property.isInitialized.
Want to write some extension like:
fun <T> T?.executeSafety(func: T.() -> (Unit)) { this?.func() }
Then we can easily execute simple methods on lateinit property. Please help on this
On Kotlin 1.2 and up, we can quickly check whether a lateinit property has been initialised or not using a reflection based API.
Here's how it works:
lateinit var fullName: String
if (::fullName.isInitialized) {
print("Hi, $fullName")
}
Since this reflection API works only on properties which are defined:
In the same class where the check is being made
In an outer class
As top-level in the same file
We can check lateinit properties of other classes by adding a new method on the target class:
class LateComer {
lateinit var student: Student
fun isStudentInitialised() = ::student.isInitialized
}
I've a class that needs to be include in lots of my activities , so I've made a class that needs to access the view .
this is my code :
class Toolbar{
private lateinit var typeface:Typeface;
private lateinit var context:Context
private lateinit var tvToolbar:TextView;
fun MakeToolbar(context:Context, title:String){
this.context=context
init();
}
private fun init() {
typeface= Func.getTypeFace(context)!!
tvToolbar=((Activity)context).findViewById
}
the problem is , in java I can easily access the context and use findViewById to get my view , Buy I can't do it in kotlin and it couldn't find the view .
How can I access a view in a non activity class?
Is tvToolbar=((Activity)context).findViewById really your code? It won't event compile in Kotlin, or Java for that matter.
The syntactically correct way would be this:
tvToolbar = (context as Activity).findViewById(R.id.tvToolbar)
Though I recommend against passing your entire activity object to another class. Why don't you just pass in a reference to your view? And be sure to read about WeakReferences.
I am learning Kotlin, and I googled how to create a class in kotlin. So, I created the below class as a test.
In the main activity, I am trying to instantiate an object from the class Board, but i get the following error:
classifier Board does not have a companion object
please let me know how to intantiate an object of an the class Board?
MainActivity:
class ActMain : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_act_main)
Board board = new Board(name = "ABC");
}
}
Board.kt:
data class Board(val name: String) {
var age: Int = 0
}
Kotlin does not use new.
Board board = new Board(name = "ABC");
is incorrect. Use
val board = Board("ABC")
Your code reflects the Java syntax... sort of. Kotlin has type inference, so you don't need to specify the class type. However, if you do specify it, it's different from Java:
val board: Board = Board("ABC")
Semi-colons are also not generally used in Kotlin, although they won't break the compilation if you use them.
name = "ABC" just isn't valid syntax no matter if it's Java or Kotlin. Actually it is (from #hotkey): https://kotlinlang.org/docs/reference/functions.html#named-arguments
Unlike Java, in Kotlin this is the correct way
MainActivity.kt
class ActMain : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_act_main)
val board = Board("ABC")
board.age = 12
}
}
Board.kt
class Board(val name: String) {
var age: Int = 0
}
try to forget java
val board = Board("name")
in kotlin
when you want to declare new object yon can do like this.
val board = Board("ABC")
if you declare object by using val keyword. it look as you use final in java. the variable which you declared can not recreate again.
var board = Board("ABC")
if you use var to declare it look as normal variable in java
Anyway in kotlin you will see something that It doesn't contain in java such as
scoping function as link below. it will help you write your code is more easily.
https://kotlin.guide/scoping-functions
I hope this help :)