I am trying to use Hilt on a sample project
but when i compiled my project, i have this sample error message :
Cause: com.example.pokemon.ui.Hilt_MainActivity
This is my activity aclass:
#AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private var binding: ActivityMainBinding? = null
private var isFavoriteListVisible = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding?.root)
supportFragmentManager.beginTransaction()
.replace(R.id.frameLayout, Home())
.commit()
binding?.changeFragment
?.setOnClickListener {
if (isFavoriteListVisible) {
isFavoriteListVisible = false
binding?.changeFragment?.text = "Favorites"
supportFragmentManager.beginTransaction()
.replace(R.id.frameLayout, Home())
.commit()
} else {
isFavoriteListVisible = true
binding?.changeFragment?.text = "Home"
supportFragmentManager.beginTransaction()
.replace(R.id.frameLayout, Favorites())
.commit()
}
}
}
}
What can i do to resolve it or have more details about this issue
Related
I have an error saying "Error inflating class fragment". I saw different solutions like one is saying to extend fragment activity but this is not fragment this is an activity so are there any other solutions?
Following is my main activity
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
addFragment(HomeFragment.newInstance())
binding.navView.show(0)
binding.navView.add(MeowBottomNavigation.Model(1, R.drawable.ic_dashboard_black_24dp))
binding.navView.add(MeowBottomNavigation.Model(2, R.drawable.ic_dashboard_black_24dp))
binding.navView.setOnClickMenuListener {
when(it.id){
0->{
Toast.makeText(this, "Home Fragment", Toast.LENGTH_SHORT).show()
replaceFragment(HomeFragment.newInstance())
}
1->{
Toast.makeText(this, "Notifications Fragment", Toast.LENGTH_SHORT).show()
replaceFragment(NotificationFragment.newInstance())
}
}
}
}
private fun replaceFragment(fragment: Fragment) {
val fragmentTransition = supportFragmentManager.beginTransaction()
fragmentTransition.replace(R.id.nav_host_fragment_activity_main, fragment).addToBackStack(Fragment::class.java.simpleName).commit()
}
private fun addFragment(fragment: Fragment) {
val fragmentTransition = supportFragmentManager.beginTransaction()
fragmentTransition.add(R.id.nav_host_fragment_activity_main, fragment).addToBackStack(Fragment::class.java.simpleName).commit()
}
}
I changes frgment to frameLayout and error is gone now
I created a Login/Register Page and I get this error while trying to click Register Button.This method should send me to Register Page where I can register a new account.The problem is I get this error when I click the register button: android app code error
How can I resolve this error ?
Here is my code and other screenshots:
class LoginFragment : Fragment() {
private lateinit var username: EditText
private lateinit var password: EditText
private lateinit var fAuth: FirebaseAuth
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_login, container, false)
username = view.findViewById(R.id.log_username)
password = view.findViewById(R.id.log_password)
fAuth = Firebase.auth
view.findViewById<Button>(R.id.btn_register).setOnClickListener {
val navRegister = activity as FragmentNav
navRegister.navigateFrag(RegisterFragment(),false)
}
view.findViewById<Button>(R.id.btn_login).setOnClickListener {
validateForm()
}
return view
}
private fun firebaseSignIn(){
fAuth.signInWithEmailAndPassword(username.text.toString(),password.text.toString()).addOnCompleteListener{
task ->
if(task.isSuccessful){
}else{
Toast.makeText(context,"Register Successful",Toast.LENGTH_SHORT).show()
var navHome = activity as FragmentNav
navHome.navigateFrag(HomeFragment(),addToStack = true)
}
}
}
private fun validateForm() {
val icon = AppCompatResources.getDrawable(requireContext(), R.drawable.erroricon)
icon?.setBounds(0, 0, icon.intrinsicWidth, icon.intrinsicHeight)
when {
TextUtils.isEmpty(username.text.toString().trim()) -> {
username.setError("Please Enter Username")
}
TextUtils.isEmpty(password.text.toString().trim()) -> {
password.setError("Please Enter Password")
}
username.text.toString().isNotEmpty() &&
password.text.toString().isNotEmpty() -> {
if (username.text.toString().matches(Regex("[a-zA-Z0-9._]+#[a-z]+\\\\.+[a-z]+"))) {
firebaseSignIn()
} else {
username.setError("Please Enter Valid Email Id")
}
}
}
}
I get this error here:
error
FragmentNav {
fun navigateFrag(fragment: Fragment, addToStack:Boolean )
}
Here is the navigation between buttons register/login :
class LoginActivity : AppCompatActivity(R.layout.login_activity),FragmentNav {
private lateinit var fAuth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.login_activity)
fAuth = Firebase.auth
val currentUser = fAuth.currentUser
if(currentUser !=null){
supportFragmentManager.beginTransaction()
.add(com.google.android.material.R.id.container,HomeFragment()).addToBackStack(null)
.commit()
}
supportFragmentManager.beginTransaction()
.add(com.google.android.material.R.id.container,LoginFragment())
.commit()
}
override fun navigateFrag(fragment: Fragment, addToStack: Boolean) {
val transaction = supportFragmentManager
.beginTransaction()
.replace(com.google.android.material.R.id.container,fragment)
if(addToStack){
transaction.addToBackStack(null)
}
transaction.commit()
}
}
That interface is totally useless if you are not passing the MainActivity context to the LoginFragment. Change LoginFragment constructor to this:
class LoginFragment(private val mListener: FragmentNav) : Fragment()
and in onClick() of the register button, call navigateFrag like this:
mListener.navigateFrag(RegisterFragment(),false)
And finally in MainActivity, pass context to LoginFragment like this:
supportFragmentManager.beginTransaction()
.add(com.google.android.material.R.id.container,LoginFragment(this))
.commit()
private val dashboardFragment = DashboardFragment
private val settingsFragment = SettingsFragment
private val infoFragment = InfoFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHomePageBinding.inflate(layoutInflater)
setContentView(binding?.root)
replaceFragment(dashboardFragment)
}
private fun replaceFragment(fragment: Fragment){
if(fragment != null){
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.frag_container, fragment)
transaction.commit()
}
}
I have 3 fragments setup in my project namely - Dashboard, settings and Info. I am getting an error for type mismatch everytime I enter my fragment name in the function replaceFragment. I am referring to this video - https://www.youtube.com/watch?v=v8MbOjBCu0o&t=1s
You need to instantiate these fields . right now they r just pointing to the class type . Its similar to new keyword in java .
private val dashboardFragment = DashboardFragment()
private val settingsFragment = SettingsFragment()
private val infoFragment = InfoFragment()
I am calling a DialogFragment in another fragment like bellow:
#CoursesFragmentScope
class CoursesFragment : DaggerFragment(),
DefaultLifecycleObserver,
CourseTypeListDialogFragment.ApplySelectedCourseTypeFilter {
#OnClick(R.id.btnCourseType)
fun btnCourseTypeClick() {
val fm = activity!!.supportFragmentManager
val courseTypeListDialogFragment =
CourseTypeListDialogFragment()
courseTypeListDialogFragment.isCancelable = false
courseTypeListDialogFragment.setStyle(
DialogFragment.STYLE_NO_TITLE,
0
)
courseTypeListDialogFragment.setTargetFragment(this, 1)
courseTypeListDialogFragment.show(fm, "")
}
}
And my DialogFragment is like bellow:
class CourseTypeListDialogFragment: DaggerAppCompatDialogFragment(), CourseTypeAdapter.CourseTypeListener {
interface ApplySelectedCourseTypeFilter {
fun applySelectedCourseType()
}
..some code..
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
ButterKnife.bind(this, view)
iApplySelectedCourseTypeFilter = targetFragment as ApplySelectedCourseTypeFilter
}
..some code..
}
But get me bellow error in this line:
courseTypeListDialogFragment.setTargetFragment(this, 1)
And say me:
Fragment CourseTypeListDialogFragment{92f4a96 (cbe1689e-1367-4436-8de6-3797320e7d41) } declared target fragment CoursesFragment{422cc09 (9d16e30b-fd71-44a8-8c45-8a866b62c135) id=0x7f0800d5} that does not belong to this FragmentManager!
What can I do?
Both classes are from same package:
import dagger.android.support.DaggerAppCompatDialogFragment
import dagger.android.support.DaggerFragment
I removed courseTypeListDialogFragment.setTargetFragment(this, 1) and opened dialog but not work my interface in dialog.
I am using from fragments in activity like bellow:
class MainActivity : DaggerAppCompatActivity() {
#BindView(R.id.nav_view)
lateinit var navView: BottomNavigationView
override fun onCreate(savedInstanceState: Bundle?) {
super<DaggerAppCompatActivity>.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
ButterKnife.bind(this)
val navController = findNavController(R.id.nav_host_fragment)
navView.setupWithNavController(navController)
navView.menu.findItem(R.id.navigation_courses).setIcon(
IconDrawable(this, MaterialCommunityIcons.mdi_account_box)
.colorRes(R.color.colorPrimaryDark)
.actionBarSize())
navView.menu.findItem(R.id.navigation_login).setIcon(
IconDrawable(this, MaterialCommunityIcons.mdi_login)
.colorRes(R.color.colorPrimaryDark)
.actionBarSize())
}
}
change this line
val fm = activity!!.supportFragmentManager
to
val fm = fragmentManager
read the following blog
https://medium.com/better-programming/what-is-target-fragment-da0e7c7f345c
I'm trying to get a viewpager in an already existing fragment.
In another project I had no issues when the viewpager was in activity_main.xml
One of the things I tried is the following:
ViewPagerAdapter.kt
class ViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> KapperKeuze1Fragment()
1 -> KapperKeuze2Fragment()
else -> KapperKeuze3Fragment()
}
}
override fun getCount(): Int {
return 3
}
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
lateinit var homeFragment: HomeFragment
lateinit var afspraakFragment: AfspraakFragment
lateinit var overFragment: OverFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val bottomNavigation : BottomNavigationView = findViewById(R.id.bot_nav)
homeFragment = HomeFragment()
supportFragmentManager
.beginTransaction()
.replace(R.id.frame_layout, homeFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit()
bottomNavigation.setOnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.home -> {
homeFragment = HomeFragment()
supportFragmentManager
.beginTransaction()
.replace(R.id.frame_layout, homeFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit()
}
R.id.afspraak -> {
afspraakFragment = AfspraakFragment()
supportFragmentManager
.beginTransaction()
.replace(R.id.frame_layout, afspraakFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit()
}
R.id.over -> {
overFragment = OverFragment()
supportFragmentManager
.beginTransaction()
.replace(R.id.frame_layout, overFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit()
}
}
true
}
val adapter = ViewPagerAdapter(supportFragmentManager)
val pager = findViewById<View>(R.id.viewPager) as ViewPager
pager.adapter = adapter
}
}
fragment_afspraak.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
The error occurs in MainActivity.kt at: val pager = findViewById<View>(R.id.viewPager) as ViewPager
And gives:
Caused by: kotlin.TypeCastException: null cannot be cast to non-null type androidx.viewpager.widget.ViewPager
Use childFragmentManager instead of supportFragmentManager
Because it returns a private FragmentManager for placing and managing Fragments inside of this Fragment.(You ViewPager fragments located in you afspraak fragment)
So set your ViewPager in your AfspraakFragment as below :
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = ViewPagerAdapter(childFragmentManager)
val pager = view.findViewById(R.id.viewPager) as ViewPager
pager.adapter = adapter
}