How to declare variables in Android (Kotlin) using Google code style? - kotlin

I started to build the app in Kotlin and I want to know how to correctly initialize variables. For example in Java it was like:
private TextView mSomeTextView;
And then we call findViewById in some methods. But in Kotlin I can't just write something like that, I need to:
private val textView: TextView = findViewById(R.id.text)
I write it under onCreate as I used to. Question: is it right place for it? If no -- where and how should I do it?

You should use lateinit:
private lateinit var textView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
...
textView = findViewById(R.id.text)
}

Related

How to solve error with View Binding in Kotlin

Here I'm getting this error
package lk.ac.kln.mit.stu.mobileapplicationdevelopment.activities
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View.inflate
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import lk.ac.kln.mit.stu.mobileapplicationdevelopment.R
class ShoppingActivity : AppCompatActivity() {
val binding by lazy{
ActivityShoppingBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_shopping)
setContentView(binding.root)
val navController = findNavController(R.id.shoppingHostFragment)
binding.bottomNavigation.setupWithNavContoller(navController)
}
}
Anyone know the reason to fail this code?
I tried adding below lines to the gradel as well
buildFeatures {
viewBinding true
}
You can better use this, this way the binding can be set in the onCreate as before this it can not build UI components.
var binding: ActivityShoppingBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityShoppingBinding.inflate(layoutInflater)
binding?.let {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_shopping)
setContentView(binding.root)
val navController = findNavController(R.id.shoppingHostFragment)
binding.bottomNavigation.setupWithNavContoller(navController)
}
}
ActivityShoppingBinding is in red because it's not recognised by the IDE - usually this means you haven't imported it, so it doesn't know what it is. And you don't have an import line for that class, so that's probably your problem!
The easiest fix is just to put your cursor over the error and do Alt+Enter (or whatever) or click the lightbulb icon that appears, and the IDE will offer to import it for you. Once that binding class is imported it should work fine.
Also you're calling setContentView twice - that's pointless (you're inflating a layout then throwing it away immediately) and it can introduce bugs if you accidentally set things on a layout that isn't being displayed. You should only be calling it once, with binding.root in this case.
You might want to look at the recommended way of initialising view binding in Activities (and the Fragments section too if you're using them). Avoid using lazy for UI stuff, since it can only be assigned once you can run into issues (mostly with Fragments, but the example in that link uses lateinit too)

Best practice when using mutableState with jetpack compose inside viewmodel with exposing mutable state

I have the following ViewModel
#HiltViewModel
class ShareViewModel #Inject constructor(
private val taskRepository: TaskRepository
): ViewModel() {
private val searchAppBarStateMutableState: MutableState<SearchAppBarState> = mutableStateOf(SearchAppBarState.CLOSED)
val searchAppBarState: State<SearchAppBarState> = searchAppBarStateMutableState
private val listOfTaskMutableStateFlow = MutableStateFlow<List<TodoTaskEntity>>(emptyList())
val listOfTaskStateFlow = listOfTaskMutableStateFlow.asStateFlow()
}
I never expose mutableStateFlow as in the example above. And SonarLint will show a warning when doing this.
MutableStateFlow" and "MutableSharedFlow" should not be exposed
So I apply the same technique to the mutableState
However, If I do like this below, I don't get any warning.
val searchAppBarStateMutableState: MutableState<SearchAppBarState> = mutableStateOf(SearchAppBarState.CLOSED)
Just wondering what is the best practice for using MutableState with jetpack compose.
To use mutableState with viewmodel, define mutableState with private setter inside viewmodel, ex -
var isVisible by mutableState(false)
private set
By doing above we can read the mutable state from outside of viewmodel but not update it. To update create a public function inside viewmodel, ex -
fun setVisibility(value: Boolean) {
isVisible = value
}
By making a setter function we are following separation of concerns and having a single source of truth for editing the mutableState.
I think the error is in that you are setting
val searchAppBarState: State<SearchAppBarState> = searchAppBarStateMutableState
if you want to share private value as not mutable you shouldn't set it equal rather you can use get modifier
val searchAppBarState: State<SearchAppBarState> get() = searchAppBarStateMutableState
Also it would be better to name it with underscore as many developers are used to like:
private val _searchAppBarState: MutableState<SearchAppBarState> = mutableStateOf(SearchAppBarState.CLOSED)
val searchAppBarState: State<SearchAppBarState> get() = _searchAppBarState

I am using android studio and the mainactivity class is .kt type. I keep having this error: Expecting member declaration

I am using android studio and I have some issues with this piece of code. Could someone tell me what I am doing wrong?
The system keeps telling me "Expecting member declaration."
This is the code
class MainActivity: AppCompatActivity() {
class TextView totalTextView; //This is where I am having the error
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
I am assuming you are trying to create a totalTextView variable. In kotlin you can declare a variable like this
lateinit var totalTextView : TotalTextView
This is not right way to create or define object of TextView.
1 > var totalTextView : TextView ? = null
1 > lateint var totalTextView : TextView
In kotlin, No need to define id of ViewGroup items , avoid to define the instance of view item when you are using kotlin

How to inject dependency using koin in top level function

I have top-level function like
fun sendNotification(context:Context, data:Data) {
...//a lot of code here
}
That function creates notifications, sometimes notification can contain image, so I have to download it. I`m using Glide which is wrapped over interface ImageManager, so I have to inject it. I use Koin for DI and the problem is that I cannot write
val imageManager: ImageManager by inject()
somewhere in my code, because there is no something that implements KoinComponent interface.
The most obvious solution is to pass already injected somewhere else imageManager as parameter of function but I dont want to do it, because in most cases I dont need imageManager: it depends on type of Data parameter.
Easiest way is to create KoinComponent object as wrapper and then to get variable from it:
val imageManager = object:KoinComponent {val im: ImageManager by inject()}.im
Btw its better to wrap it by some function, for example I use
inline fun <reified T> getKoinInstance(): T {
return object : KoinComponent {
val value: T by inject()
}.value
}
So if I need instance I just write
val imageManager:ImageManager = getKoinInstance()
or
val imageManager = getKoinInstance<ImageManager>()
I did it in this way
fun Route.general() {
val repo: OperationRepo by lazy { GlobalContext.get().koin.get() }
...
}

New to Kotlin..having issues with Optionals and Casting

Just ver confused about casting and how to set up class variables. In java it was possible to do
private var mSectionsStatePageAdapter : SectionsStatePagerAdapter? = null
private val mViewPager : ViewPager? = null
now we're in kotlin
class MainActivity : AppCompatActivity() {
private var mSectionsStatePageAdapter : SectionsStatePagerAdapter? = null
private val mViewPager : ViewPager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val mytoolbar:Toolbar = findViewById(R.id.top_toolbar)
setSupportActionBar(mytoolbar)
mSectionsStatePageAdapter = SectionsStatePagerAdapter(getSupportFragmentManager())
mViewPager = findViewById(R.id.viewpager1)
setupViewPager(mViewPager)
}
fun setupViewPager(viewPager :ViewPager):Unit {
var adapter : SectionsStatePagerAdapter = SectionsStatePagerAdapter(getSupportFragmentManager())
adapter.addFragment(Fragment1(),"Fragment1")
viewPager.setAdapter(adapter)
}
I'm getting val can't be reassigned...
Error:(65, 24) Smart cast to 'ViewPager!' is impossible, because 'mViewPager' is a mutable property that could have been changed by this time
For Android, it is common to use lateinit var because you create the object outside of constructor (in onCreate, etc). You can go with two route:
lateinit var variable:Type
var variable:Type?
I would recommend if your variable should be available when you are ready to use it. You do not need to do null check. lateinit mean late initialization. Kotlin use null to represent not yet initialized, so you cannot use nullable type and assign null on it.
If your variable is nullable, then you should go the second way.
Beside, if you are handling views, you should use Android extension to do it. You don't need to findViewById in Activity or Fragment yourself.
There are two things happening here.
First, as #gyosida points out, you have defined your mPager property as val instead of var so it cannot be reassigned in the line mViewPager = findViewById(R.id.viewpager1). As #Joshua points out, you either have to make it a var or you need to make it a lateinit val to solve the problem of it not being initialised with the class instance.
The second is represented by the actual error you describe of, 'mutable property that could have been changed', and you will continue to see this if you make it a var. The approach of using lateinit is most likely the better idea.
However, to explain this error, in your method declaration of:
fun setupViewPager(viewPager: ViewPager): Unit {
you have said that the argument for viewPager cannot be null. If it were, it would be viewPager: ViewPager?. So, if you pass something that could be null into it, you will get a compile error.
What Kotlin is telling you is that in between the lines:
mViewPager = findViewById(R.id.viewpager1)
and
setupViewPager(mViewPager)
something - imagine another method on another thread - could potentially have changed the value of mViewPager from that assigned instance to null. Therefore it's not safe to pass it in.
The only way to solve this without changing the method is supply a value that is guaranteed to be non-null. There are a few ways you could do that:
assign your value to a method-level variable that can't be interfered with, and supply that as the argument
only call your function if the value is non-null, e.g. mViewPager?.let{ pager -> setupViewPager(pager)}
assert that mViewPager will not be null, leaving any violations to fail at runtime, e.g. setupViewPager(mViewPager!!)