Property not being initalized sometimes - android

I'm trying to handle fragment clicks in FragmentPagerAdapter, but sometimes I'm getting Fatal Exception: kotlin.UninitializedPropertyAccessException, which says that click listener property is not initialized.
So here is code for the PagerAdapter
class ApplicationListPagerAdapter(
fm: FragmentManager,
private val onListItemClick: (isSent: Boolean, application: Application) -> Unit,
private val onGoToScholarshipsTabClicked: () -> Unit,
private val onGoToPicksTabClicked: () -> Unit
): FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT),
ApplicationListFragment.ClickListener {
override fun getCount(): Int {
return 2
}
override fun getItem(position: Int): Fragment {
val isSent = position == 1
val fragment = ApplicationListFragment.newInstance(isSent)
fragment.setApplicationSelectListener(this)
return fragment
}
override fun getPageTitle(position: Int): CharSequence? {
return if (position == 0) "PICKS" else "SENT"
}
override fun applicationSelected(isSent: Boolean, application: Application) {
onListItemClick(isSent, application)
}
override fun goToScholarshipsTabClicked() {
onGoToScholarshipsTabClicked()
}
override fun goToPicksTabClicked() {
onGoToPicksTabClicked()
}
}
Code how I initialize it in fragment
private lateinit var clickListener: ClickListener
fun setApplicationSelectListener(clickListener: ClickListener) {
this.clickListener = clickListener
}
interface ClickListener {
fun applicationSelected(isSent: Boolean, application: Application)
fun goToScholarshipsTabClicked()
fun goToPicksTabClicked()
}
And here in onClick callback I'm getting crashes sometimes for some users.
private fun initRecyclerView(applications: List<Application>) {
application_list_recyclerView.adapter = ApplicationListItemsAdapter(
context!!,
applications.toMutableList(),
isSent,
this,
applicationViewModel.applicationService,
onClick = {
clickListener.applicationSelected(isSent, it)
},
onDelete = { application: Application, count: Int ->
scholarshipViewModel.unFavoriteScholarship(application.scholarship)
sharedViewModel.deletePickedScholarship(application.scholarship)
applicationSharedViewModel.updatePicksCount(count)
if (count == 0) {
showNoApplicationsFragment()
}
},
onUndoDelete = { application: Application, count: Int ->
sharedViewModel.undoDeletedScholarship(application.scholarship)
applicationSharedViewModel.updatePicksCount(count)
if (count == 1) {
hideNoApplicationsFragment()
}
}
)
application_list_recyclerView.layoutManager = LinearLayoutManager(context!!)
}
Thanks for any advice and I hope my explanation makes senes for everybody

Interface
interface OnItemClickListener {
//just a random method
fun itemClicked(positon: Int)
}
Inside Your Adapter class
private lateinit var listener: OnItemClickListener
fun attachListener(listener: OnItemClickListener){
this.listener = listener
}
Acticity/ Fragment
class MainActivity(): AppCompatActivity(), OnItemClickListener{
// implement interface in case you wanna use methods...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat)
// calling the listener method
myAdapter.attachListener(this)
}
}
above myAdapter is your adapter must be init first which is associate to your adapter class

Related

Handle search results after configuration change MVVM

I am building a movie app based on "The Movie DB". My app has only one activity with a recyclerview and one search action button (SearchView).
As soon as the app starts,the recyclerview filled with popularMovies list.
When I search for a movie I get the results and everything is fine,but when I rotate the screen I get the popularMovies list and not my search results.
Now I know the reason,its happening because in onCreate I have initMoviesRecyclerView() that fill the recyclerview with popularMovies.
My question is how can I keep the search results without filling the recyclerview with popularMovies ? How can I do this the correct way ?
This is the Repository Class:
class MainRepository {
//MutableLiveData
private val popularMoviesMutableLiveData = MutableLiveData<List<Movie>>()
private val searchAfterMutableLiveData = MutableLiveData<List<Movie>>()
// API
private val apiService : GetFromApi = APIService.retrofitClientRequest
private val apiKey = "NOT"
fun getPopularMoviesList() : MutableLiveData<List<Movie>>{
apiService.getPopularMovies(apiKey,1)?.enqueue(object : Callback<MovieListResult?> {
override fun onResponse(
call: Call<MovieListResult?>,
response: Response<MovieListResult?>
) {
if (response.isSuccessful){
popularMoviesMutableLiveData.value = response.body()?.moviesResults
Log.e("MovieListResults","Result: ${popularMoviesMutableLiveData.value}")
}
}
override fun onFailure(call: Call<MovieListResult?>, t: Throwable) {
Log.e("MovieListResults","Failed: ${t.message}")
}
})
return popularMoviesMutableLiveData
}
fun searchAfter(searchAfter : String) : MutableLiveData<List<Movie>>{
apiService.searchAfter(apiKey,searchAfter)?.enqueue(object : Callback<MovieListResult?> {
override fun onResponse(
call: Call<MovieListResult?>,
response: Response<MovieListResult?>
) {
if (response.isSuccessful){
searchAfterMutableLiveData.value = response.body()?.moviesResults
Log.e("SearchMovieListResults","Result: ${searchAfterMutableLiveData.value}")
}
}
override fun onFailure(call: Call<MovieListResult?>, t: Throwable) {
Log.e("SearchMovieListResults","Failed: ${t.message}")
}
})
return searchAfterMutableLiveData
}
}
This is the viewModel class:
class MainViewModel : ViewModel(){
//Repository
private val mainRepository = MainRepository()
//MutableLiveData
var popularMoviesMutableLiveData = MutableLiveData<List<Movie>>()
var searchAfterMutableLiveData = MutableLiveData<List<Movie>>()
//The Main Movie List
var mainMovieList = listOf<Movie>()
fun getPopularMovies() : LiveData<List<Movie>>{
popularMoviesMutableLiveData = mainRepository.getPopularMoviesList()
popularMoviesMutableLiveData.value = mainMovieList
return popularMoviesMutableLiveData
}
fun getMovieBySearch(searchAfter : String) : LiveData<List<Movie>>{
searchAfterMutableLiveData = mainRepository.searchAfter(searchAfter)
searchAfterMutableLiveData.value = mainMovieList
return searchAfterMutableLiveData
}
}
This is the MainActivity class:
class MainActivity : AppCompatActivity() {
//ViewModel
private val mainViewModel : MainViewModel by viewModels()
// Views
private lateinit var mainRecyclerView : RecyclerView
private lateinit var mainAdapter : MainRecyclerViewAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initMoviesRecyclerView()
}
private fun initMoviesRecyclerView() {
mainRecyclerView = findViewById(R.id.mainRecyclerView)
mainRecyclerView.setHasFixedSize(true)
mainRecyclerView.layoutManager = GridLayoutManager(this,1)
mainViewModel.getPopularMovies().observe(this, object : Observer<List<Movie>?> {
override fun onChanged(newList: List<Movie>?) {
if (newList != null) {
mainViewModel.mainMovieList = newList
mainAdapter = MainRecyclerViewAdapter(mainViewModel.mainMovieList)
mainRecyclerView.adapter = mainAdapter
}
}
})
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main_menu,menu)
val searchView = menu.findItem(R.id.menu_search_movie).actionView as androidx.appcompat.widget.SearchView
searchView.queryHint = "Search By Name,Actor .."
searchView.setOnQueryTextListener(object : androidx.appcompat.widget.SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(whileTextChange: String?): Boolean {
//Clear SearchView
searchView.isIconified = true
searchView.setQuery("", false)
searchView.onActionViewCollapsed()
mainViewModel.getMovieBySearch(whileTextChange.toString()).observe(this#MainActivity,object : Observer<List<Movie>?> {
override fun onChanged(newList: List<Movie>?) {
if (newList != null) {
mainViewModel.mainMovieList = newList
mainAdapter.changeCurrentList(mainViewModel.mainMovieList)
}
}
})
return false
}
override fun onQueryTextChange(whileTextChange: String?): Boolean {
Log.e("onQueryTextChange","Text: $whileTextChange")
return false
}
})
return true
}
}
Thank you!
I don't see where you actually populate the data inside the ViewModel. But it all looked good.
This line is a bit suspicious:
mainViewModel.mainMovieList = newList
You should not update the ViewModel from the View lifeCycle. Also, you should not update the ViewModel during the observe call.
So after sometime I manage to work around it with a simple solution:
I created a function in the viewModel,to check if the search list value is null:
fun startFromSearch(): Boolean {
return searchAfterMutableLiveData.value != null
}
After that I made an if statement in the initMoviesRecyclerView(), and that's it!
private fun initMoviesRecyclerView() {
mainRecyclerView = findViewById(R.id.mainRecyclerView)
mainRecyclerView.setHasFixedSize(true)
mainRecyclerView.layoutManager = GridLayoutManager(this,1)
mainAdapter = MainRecyclerViewAdapter(mainViewModel.mainMovieList,this)
mainRecyclerView.adapter = mainAdapter
if (!mainViewModel.startFromSearch()){
mainViewModel.getPopularMovies(1).observe(this, object : Observer<List<Movie>?> {
override fun onChanged(newList: List<Movie>?) {
if (newList != null) {
mainAdapter = MainRecyclerViewAdapter(newList,this#MainActivity)
mainRecyclerView.adapter = mainAdapter
}
}
})
}
}

The buttons of my introSlider aren't working, why is this happening - question Updated

I'm trying to build an app that has an intro slider when it's installed. I followed a tutorial.
However, I have an error and the app doesn't even open.
Here is some code:
Class Intro
class Intro : AppCompatActivity(), View.OnClickListener {
lateinit var mPager : ViewPager
var layouts : IntArray = intArrayOf(R.layout.first_slide,R.layout.second_slide,R.layout.third_slide)
lateinit var dotsLayout : LinearLayout
lateinit var dots: Array<ImageView>
lateinit var mAdapter : PageAdapter
lateinit var btnNext: Button
lateinit var btnSkip: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_intro)
if(PrefManager(this).checkPreferences()){goToHomePage()}
if(Build.VERSION.SDK_INT >=19)
{
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
}else{
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
}
mPager=findViewById(R.id.pager)
mAdapter= PageAdapter(layouts,this)
mPager.adapter= mAdapter
dotsLayout = findViewById(R.id.dots)
btnNext = findViewById(R.id.btnNext)
btnSkip=findViewById(R.id.btnSkip)
btnSkip.setOnClickListener { this }
btnNext.setOnClickListener { this }
createDots(0)
mPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
}
override fun onPageSelected(position: Int) {
createDots(position)
if(position == layouts.size){
btnNext.setText("DONE")
btnSkip.visibility=View.INVISIBLE
}else{
btnNext.setText("NEXT")
btnSkip.visibility=View.VISIBLE
}
}
})
}
fun createDots(position:Int){
if(dotsLayout!=null){
dotsLayout.removeAllViews()
}
dots = Array(layouts.size,{i -> ImageView(this)})
for(i in 0..layouts.size -1) {
dots[i] = ImageView(this)
if (i == position) {
dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.active_dots))
} else {
dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.inactive_dots))
}
var params: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
params.setMargins(4,0,4,0)
dotsLayout.addView(dots[i],params)
}
}
override fun onClick(v: View?) {
when(v!!.id){
R.id.btnSkip ->{
goToHomePage()
PrefManager(this).writeSharedPreferences()
}
R.id.btnNext ->{
loadNextSlide()
}
}
}
private fun goToHomePage() {
startActivity(Intent(this, HomePage::class.java))
finish()
}
private fun loadNextSlide() {
var nextSlide: Int = mPager.currentItem+1
if(nextSlide<layouts.size){
mPager.setCurrentItem(nextSlide)
}
else{
goToHomePage()
PrefManager(this).writeSharedPreferences()
}
}
}
Class PrefManager
class PrefManager {
lateinit var context : Context
lateinit var pref: SharedPreferences
constructor(context: Context) {
this.context = context
getSharedPreferences()
}
private fun getSharedPreferences(){
pref = context.getSharedPreferences(context.getString(R.string.pref_name), Context.MODE_PRIVATE)
}
fun writeSharedPreferences(){
var editor : SharedPreferences.Editor=pref.edit()
editor.putString(context.getString(R.string.pref_key),"NEXT")
editor.commit()
}
fun checkPreferences() : Boolean
{
var status: Boolean = false
status = !pref.getString(context.getString(R.string.pref_key),null).equals("null")
return status
}
fun clearPreferences(){
pref.edit().clear().commit()
context.startActivity(Intent(context, HomePage::class.java))
(context as AppCompatActivity).finish()
}
}
The app works but the buttons next and skip don't respond whe clicked. Why is this happening?
Update: I changed some redundant thing on the code and uncommented the part that I've previous commented, and I don't have the error anymore. But the buttons still don't work

Why Firebase Realtime database is not working

I have written the code in Kotlin language
I need the firebase realtime database to add a child with user's UID with email as it's value under the users column when the user signs up. The Login is successful and then it passes to the main activity .The users details is listed in Authentication-> Users but the realtime database is not working and also when I click the back button it opens the main activity again and again ,after a number of clicks it goes back the login page and exits,maybe this is because it could not connect to the database.
Please help me with necessary changes.
Here is the code
MAIN ACTIVITY
private var mFirebaseAnalytics: FirebaseAnalytics?=null
class MainActivity : AppCompatActivity() {
var listofContacts = ArrayList<Contacts>()
var adapter: ContactsAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mFirebaseAnalytics= FirebaseAnalytics.getInstance(this)
listofContacts.add(Contacts("NAME", 123456789))
adapter = ContactsAdapter(this, listofContacts)
listview.adapter=adapter
}
inner class ContactsAdapter : BaseAdapter {
var contactslist = ArrayList<Contacts>()
var context: Context? = null
constructor(context: Context, contactslist: ArrayList<Contacts>) : super() {
this.contactslist = contactslist
this.context = context
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val contact = contactslist[position]
val inflater = context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val myView = inflater.inflate(R.layout.contact_view, null)
myView.name.text = contact.name!!
myView.num.text = contact.num.toString()!!
myView.setOnClickListener {
val intent= Intent(context,ContactInfo::class.java!!)
intent.putExtra("name",contact.name!!)
intent.putExtra("num",contact.num!!)
context!!.startActivity(intent)
}
return myView
}
override fun getItem(position: Int): Any {
return contactslist[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return contactslist.size
}
}
}
LOGIN
private var mAuth:FirebaseAuth?=null
var database=FirebaseDatabase.getInstance()
var myRef=database.reference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
mAuth = FirebaseAuth.getInstance()
}
fun loginevent(view: View){
login(etun.text.toString(),pw.text.toString())
}
fun login(email:String,password:String){
mAuth!!.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(this){task ->
if(task.isSuccessful){
Toast.makeText(applicationContext,"Login Successful", Toast.LENGTH_LONG).show()
LoadMain()
}
else
Toast.makeText(applicationContext,"Login Failed", Toast.LENGTH_LONG).show()
}
}
override fun onStart() {
super.onStart()
LoadMain()
}
fun LoadMain(){
var currentuser=mAuth!!.currentUser
if(currentuser!=null) {
myRef.child("Users").child(currentuser.uid).setValue(currentuser.email)
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("email", currentuser.email)
intent.putExtra("uid", currentuser.uid)
startActivity(intent)
}
}
}

Why l can`t set listener in Kotlin?

I have OnClickInterface (with method fun onClickShape()) Main.class, and FlipFragment.class and ImageView (which called image in my code). My goal is make listener for image.
interface OnClickInterface {
fun onClickShape()
}
MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initTabs()
var flip = FlipFragment()
flip.listener = object : OnClickInterface {
override fun onClickShape() {
Log.d("MainActivity", "Shape Pressed")
ToastUtils.showSuccessMessage(baseContext, "sometext")
}
}
}
fun initTabs() {
var adapter = TabsPagerFragmentAdapter(supportFragmentManager)
mViewPager.adapter = adapter
mTabLayout.setupWithViewPager(mViewPager)
}
}
onCreate in FlipFragment
var image = view.findViewById<ImageView>(R.id.fShapeView)
image.setOnClickListener(View.OnClickListener {
Log.d("FlipFragment", "PRESSED")
if (listener != null)
listener!!.onClickShape()
})
App was loading well, without errors. But when I pressed in the image I show in my log FlipFragment: PRESSED that's mean that my application call method from FragmentFlip, not override method from MainActivity. Why?
I searched error . My app show NPE here.
flip.listener = object : OnClickInterface {
override fun onClickShape() {
Log.d("MainActivity", "Shape Pressed")
ToastUtils.showSuccessMessage(baseContext, "someText")
}}
Why listener = null . I defined it with anonymous class.
All code in FlipFragment
class FlipFragment : Fragment() {
private var layout = R.layout.view_flip
var listener: OnClickInterface? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
var view: View
view = inflater!!.inflate(layout, container, false)
var image = view.findViewById<ImageView>(R.id.fShapeView)
image.setOnClickListener(View.OnClickListener {
Log.d("FlipFragment", "PRESSED")
if (listener != null){
listener!!.onClickShape()}
})
return view
}
companion object {
fun getInstanse(): FlipFragment {
var args = Bundle()
var flipFragment = FlipFragment()
flipFragment.arguments = args
return flipFragment
}
}
}
If you need all code it is FragmentPagerAdapter.class
class TabsPagerFragmentAdapter(fm: FragmentManager?) : FragmentPagerAdapter(fm) {
var tabs: Array<String> = arrayOf("Flip", "Multi")
override fun getItem(position: Int) = when(position){
0 -> FlipFragment.getInstanse()
1 -> Mulit.getInstanse() //it is empty now
else -> FlipFragment.getInstanse()
}
override fun getPageTitle(position: Int) = tabs[position]
override fun getCount() = tabs.size
}

How to call baseactivity function from viewmodel in android

Hi I have LoginActivity and LoginViewModel and some more classes. I have showLoading and hideLoading in the BaseActivity so it can be accessible from each activity.
I am able to call LoginActivity method from the LoginViewModel like mNavigator?.startForgotPasswordActivity()
I want to call it from the LoginViewModel then what the way to do it using MVVM ? or I am going with wrong approach. Please suggest what is the correct way to do this ?
BaseActivity.kt
abstract class BaseActivity : AppCompatActivity(), AnkoLogger {
private val progressBar: ProgressBar? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
protected fun getToolbar(): Toolbar {
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
return toolbar
}
protected fun performDependencyInjection() {
AndroidInjection.inject(this);
}
#TargetApi(Build.VERSION_CODES.M)
fun requestPermissionsSafely(permissions: Array<String>, requestCode: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissions, requestCode)
}
}
#TargetApi(Build.VERSION_CODES.M)
fun hasPermission(permission: String): Boolean {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
}
fun isNetworkConnected(): Boolean {
return NetworkUtils.isNetworkConnected(applicationContext)
}
fun showLoading() {
hideLoading()
// show progress bar
}
fun hideLoading() {
// hide progress bar
}
}
LoginActivity.kt
class LoginActivity : BaseActivity(), LoginNavigator {
#Inject
lateinit var loginViewModel: LoginViewModel
override fun onCreate(savedInstanceState: Bundle?) {
performDependencyInjection()
super.onCreate(savedInstanceState)
val activityLoginBinding: ActivityLoginBinding = DataBindingUtil.setContentView<ActivityLoginBinding>(this, R.layout.activity_login)
activityLoginBinding.loginViewModel = loginViewModel
loginViewModel.mNavigator = this
}
override fun startHomeActivity() {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun startRegistrationActivity() {
startActivity(Intent(this, RegistrationActivity::class.java))
}
override fun startForgotPasswordActivity() {
startActivity(Intent(this, ForgotPasswordActivity::class.java))
}
override fun handleError(throwable: Throwable) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
}
LoginViewModel.kt
class LoginViewModel : BaseViewModel<LoginNavigator>(), AnkoLogger {
val emailField = ObservableField<String>()
private val email: String
get() = emailField.get()
val passwordField = ObservableField<String>()
private val password: String
get() = passwordField.get()
#Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE")
fun login(view: View) {
if (isEmailAndPasswordValid(email, password)) {
ApiHelperImpl().doServerLoginApiCall(email, password)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : CallbackWrapper<LoginResponse>() {
override fun onSuccess(loginResponse: LoginResponse) {
info { loginResponse }
}
})
}
}
/**
* Validate email and password. It checks email and password is empty or not
* and validate email address is correct or not
* #param email email address for login
* #param password password for login
* #return true if email and password pass all conditions else false
*/
private fun isEmailAndPasswordValid(email: String, password: String): Boolean {
if (email.isEmpty()) return false
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) return false
if (password.isEmpty()) return false
return true
}
}
BaseViewModel.kt
abstract class BaseViewModel<N> {
var mNavigator: N? = null
}
There can be 2 approach for same
1) Use all functions i.e related to UI update or UI event listener from a view (Activity or Fragment) according to mvp and from viewmodel only try to manage data like api's and other logic
class LoginActivity : BaseActivity(), LoginNavigator {
#Inject
lateinit var mLoginViewModel: LoginViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
mLoginViewModel.mNavigator = this
callApi()
}
private fun callApi() {
showLoading()
mLoginViewModel.callApi()
}
override fun openHomeScreen(model: Model) {
hideLoading()
showSnackBar(constraint_root, model.Domain)
}
}
class LoginViewModel(sessionManager: SessionManager, requestInterface: RequestInterface) : BaseViewModel<LoginNavigator>(sessionManager, requestInterface) {
fun callApi() {
requestInterface.getServiceIP()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::handleResponse, this::handleError)
}
private fun handleResponse(model: Model) {
if (model.Domain == null) {
mNavigator!!.openHomeScreen(model)
} else {
}
}
private fun handleError(error: Throwable) {
error.printStackTrace()
}
}
2)
In Login interface add a function
interface LoginNavigator {
fun openHomeScreen()
fun getActivity(): BaseActivity
}
In LoginActivity override the function and return
override fun getActivity(): BaseActivity = this
Now using navigator you can access base activity & call show/hide loader function
mNavigator!!.getActivity().showLoading()

Categories

Resources