I have this problem here:
FATAL EXCEPTION: main Process: com.mytest.app, PID: 20586
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mytest.app/com.mytest.app.activities.home.HomeActivity}: android.app.Fragment$InstantiationException: Unable to instantiate fragment
com.mytest.app.activities.fragments.MyFragment: make sure class name exists, is public, and has an empty constructor that is public
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2371)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2423)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5327)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.mytest.app.activities.fragments.MyFragment: make sure class name exists, is public, and has an empty constructor that is public
at android.app.Fragment.instantiate(Fragment.java:605)
at android.app.FragmentState.instantiate(Fragment.java:98)
at android.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1759)
at android.app.Activity.onCreate(Activity.java:903)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:277)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:84)
at com.mytest.app.activities.MyActivity.onCreate(MyActivity.java:26)
at com.mytest.app.activities.home.HomeActivity.onCreate(HomeActivity.kt:83)
at android.app.Activity.performCreate(Activity.java:5343)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1088)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2331)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2423)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1342)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5327)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalAccessException: access to constructor not allowed
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1215)
at android.app.Fragment.instantiate(Fragment.java:590)
at android.app.FragmentState.instantiate(Fragment.java:98)
at android.app.FragmentManagerImpl.restoreAllState(FragmentManager.java:1759)
I tried to change my Kotlin Object to class using CompanionObject with a static constructor but i have the same result.
The problem is randomized when we are on another application and we want to come back to our app.
Any help?
Thanks.
------EDIT------
Here is my kotlin Object code:
object MyFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onResume() {
super.onResume()
}
override fun onDestroy() {
super.onDestroy()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_myfragment, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.mymenu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// handle item selection
when (item.itemId) {
R.id.action_my_results -> {
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
}
override fun onDetach() {
super.onDetach()
}}
When you are using object keyword, you make constructor to private then android cannot recreate your fragment. My workaround is :
class MyFragment : Fragment() {
companion object {
#JvmStatic val fragment = MyFragment()
}
// rest or your code
}
Related
SOLVED - kapt "androidx.room:room-compiler:$room_version" missing in build.gradle
When i'm adding ViewModelProvider to my code, after opening a fragment in which it's added, my app immediately closes. Below i've provided the whole fragment class and error message. I've tracked the issue, and the application worked perfectly fine, before adding just one line with ViewModelProvider. Any idea why it's happening?
AddFragment
class AddFragment : Fragment() {
private var _binding: FragmentAddBinding? = null
private val binding get() = _binding!!
private lateinit var mTaskViewModel: TaskViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
// Inflate the layout for this fragment
_binding = FragmentAddBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mTaskViewModel = ViewModelProvider(this)[TaskViewModel::class.java]
binding.newTaskButton.setOnClickListener { insertToDatabase() }
}
private fun insertToDatabase() {
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
ERROR
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.randoo, PID: 25691
java.lang.RuntimeException: Cannot create an instance of class com.example.randoo.data.TaskViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:320)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:304)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:278)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.kt:128)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:153)
at com.example.randoo.fragments.AddFragment.onViewCreated(AddFragment.kt:33)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3128)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:552)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1890)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1814)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1751)
at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:538)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:312)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:304)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:278)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.kt:128)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:153)
at com.example.randoo.fragments.AddFragment.onViewCreated(AddFragment.kt:33)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3128)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:552)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1890)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1814)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1751)
at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:538)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
Caused by: java.lang.RuntimeException: cannot find implementation for com.example.randoo.data.TaskDatabase. TaskDatabase_Impl does not exist
at androidx.room.Room.getGeneratedImplementation(Room.java:100)
at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1486)
at com.example.randoo.data.TaskDatabase$Companion.getDatabase(TaskDatabase.kt:28)
at com.example.randoo.data.TaskViewModel.<init>(TaskViewModel.kt:17)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:312)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:304)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:278)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.kt:128)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:153)
at com.example.randoo.fragments.AddFragment.onViewCreated(AddFragment.kt:33)
at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3128)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:552)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1890)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1814)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1751)
at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:538)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
TaskDatabase
#Database(entities = [Task::class], version = 1, exportSchema = false)
abstract class TaskDatabase : RoomDatabase() {
abstract fun taskDao(): TaskDao
companion object {
#Volatile
private var INSTANCE: TaskDatabase? = null
fun getDatabase(context: Context): TaskDatabase{
val tempInstance = INSTANCE
if (tempInstance != null){
return tempInstance
}
synchronized(this){
val instance = Room.databaseBuilder(
context.applicationContext,
TaskDatabase::class.java,
"task_database"
).build()
INSTANCE = instance
return instance
}
}
}
}
I am using a custom layout for my settings Fragment like this
class SettingsFragment : BaseFragment() {
private var settings: FragmentSettingsBinding? = null
override fun onCreateBaseView(
inflater: LayoutInflater,
parent: ViewGroup?,
savedInstanceState: Bundle?
) {
settings = FragmentSettingsBinding.inflate(inflater, parent, true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
childFragmentManager.apply {
popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
beginTransaction().apply {
replace(R.id.settings, Settings())
commit()
}
}
}
open class Settings :
PreferenceFragmentCompat(), Preference.OnPreferenceClickListener {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// recreate after some actions
}
}
}
Everything works fins until it come to recreate and than happens this:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapp, PID: 16108
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapp/com.example.myapp.activities.MainActivity}: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.myapp.fragments.SettingsFragment$Settings: could not find Fragment constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4031)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4197)
at android.app.ActivityThread.handleRelaunchActivityInner(ActivityThread.java:6334)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:6199)
at android.app.servertransaction.ActivityRelaunchItem.execute(ActivityRelaunchItem.java:71)
at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ClientTransactionHandler.executeTransaction(ClientTransactionHandler.java:65)
at android.app.ActivityThread.handleRelaunchActivityLocally(ActivityThread.java:6288)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2444)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:226)
at android.os.Looper.loop(Looper.java:313)
at android.app.ActivityThread.main(ActivityThread.java:8633)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:567)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1133)
Caused by: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.myapp.fragments.SettingsFragment$Settings: could not find Fragment constructor
at androidx.fragment.app.Fragment.instantiate(Fragment.java:630)
at androidx.fragment.app.FragmentContainer.instantiate(FragmentContainer.java:57)
at androidx.fragment.app.FragmentManager$2.instantiate(FragmentManager.java:448)
at androidx.fragment.app.FragmentState.instantiate(FragmentState.java:81)
at androidx.fragment.app.FragmentStateManager.<init>(FragmentStateManager.java:85)
at androidx.fragment.app.FragmentManager.restoreSaveStateInternal(FragmentManager.java:2410)
at androidx.fragment.app.Fragment.restoreChildFragmentState(Fragment.java:1934)
at androidx.fragment.app.Fragment.onCreate(Fragment.java:1911)
at androidx.fragment.app.Fragment.performCreate(Fragment.java:2981)
at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:474)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:257)
at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1374)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2841)
at androidx.fragment.app.FragmentManager.dispatchCreate(FragmentManager.java:2773)
at androidx.fragment.app.Fragment.restoreChildFragmentState(Fragment.java:1935)
at androidx.fragment.app.Fragment.onCreate(Fragment.java:1911)
at androidx.navigation.fragment.NavHostFragment.onCreate(NavHostFragment.kt:169)
at androidx.fragment.app.Fragment.performCreate(Fragment.java:2981)
at androidx.fragment.app.FragmentStateManager.create(FragmentStateManager.java:474)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:257)
at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1374)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2841)
E/AndroidRuntime: at androidx.fragment.app.FragmentManager.dispatchCreate(FragmentManager.java:2773)
at androidx.fragment.app.FragmentController.dispatchCreate(FragmentController.java:251)
at androidx.fragment.app.FragmentActivity.onCreate(FragmentActivity.java:252)
at com.example.myapp.activities.MainActivity.onCreate(MainActivity.kt:39)
at android.app.Activity.performCreate(Activity.java:8282)
at android.app.Activity.performCreate(Activity.java:8262)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4005)
... 17 more
Caused by: java.lang.NoSuchMethodException: com.example.myapp.fragments.SettingsFragment$Settings.<init> []
at java.lang.Class.getConstructor0(Class.java:2363)
at java.lang.Class.getConstructor(Class.java:1759)
at androidx.fragment.app.Fragment.instantiate(Fragment.java:615)
... 48 more
I searched for similar cases and unfortunately, did not find any suitable solution.
I use one single MainActivity with a FragmentContainerView on it. There is one BaseFragment with a custom layout and that layout owns my Settings as child Fragment.
What did I wrong?
I have a problem in Fragment Transaction.
I want to change the fragment that is showing when the button is clicked
but when I try to click it, the application shuts down.
It keeps showing the error message,
Binary XML file line #6: Error inflating, and
Unable to instantiate fragment make sure class name exists, is public, and has an empty constructor that is public
I tried to add the newInstace() code but it is still not working
Below is the error code and my Activity, Fragment code. I have no idea what is wrong...
Help me please.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.illo, PID: 10709
android.view.InflateException: Binary XML file line #6: Binary XML file line #6: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #6: Error inflating class fragment
Caused by: android.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.illo.WritePost1_Fragment: make sure class name exists, is public, and has an empty constructor that is public
at android.app.Fragment.instantiate(Fragment.java:538)
at android.app.FragmentContainer.instantiate(FragmentContainer.java:53)
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3547)
at android.app.FragmentController.onCreateView(FragmentController.java:102)
at android.app.Activity.onCreateView(Activity.java:6323)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:300)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:780)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at com.example.illo.WritePost_Step2_Fragment.onCreateView(WritePost_Step2_Fragment.kt:27)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:524)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.illo.WritePost1_Fragment" on path: DexPathList[[zip file "/data/app/com.example.illo-8XrFiUkhowzrFMYYQ7X5qw==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.illo-8XrFiUkhowzrFMYYQ7X5qw==/lib/x86, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.Fragment.instantiate(Fragment.java:524)
at android.app.FragmentContainer.instantiate(FragmentContainer.java:53)
at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:3547)
at android.app.FragmentController.onCreateView(FragmentController.java:102)
at android.app.Activity.onCreateView(Activity.java:6323)
at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:300)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:780)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at com.example.illo.WritePost_Step2_Fragment.onCreateView(WritePost_Step2_Fragment.kt:27)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2100)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:524)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
class WritePostActivity : AppCompatActivity() {
// step 프래그먼트 가져오기
lateinit var step1Fragment : WritePost_Step1_Fragment
lateinit var step2Fragment : WritePost_Step2_Fragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_write_post)
// 툴바 설정
toolbarSetting()
// 처음에는 step1로 설정
ShowStep1()
// step 이동 버튼
btn_step1.setOnClickListener {
ShowStep1()
Toast.makeText(this#WritePostActivity, "Write Post Step1", Toast.LENGTH_SHORT).show()
}
btn_step2.setOnClickListener {
ShowStep2()
Toast.makeText(this#WritePostActivity, "Write Post Step2", Toast.LENGTH_SHORT).show()
}
// 글 쓰기 완료 버튼! (누르면 게시글이 등록됨)
btn_write_post_ok.setOnClickListener {
// *----서버/DB 필요----*
// 포스트로 등록
}
}
// 툴바 세팅
fun toolbarSetting() {
// 툴바로 세팅
setSupportActionBar(toolbar_write_post)
supportActionBar?.setDisplayShowCustomEnabled(true)
supportActionBar?.setDisplayShowTitleEnabled(false)
supportActionBar?.setHomeAsUpIndicator(R.drawable.icon_to_left); // 뒤로 가기 버튼 커스텀
supportActionBar?.setDisplayHomeAsUpEnabled(true) // 뒤로 가기 버튼 자동 생성
// 뒤로가기 버튼 설정
toolbar_write_post.setNavigationOnClickListener {
finish() // 액티비티 끝내기
overridePendingTransition(R.anim.no_animation, R.anim.slide_out_left) // 애니메이션
}
}
fun ShowStep1(){
step1Fragment = WritePost_Step1_Fragment()
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_write_post, step1Fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit()
}
fun ShowStep2(){
step2Fragment = WritePost_Step2_Fragment()
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_write_post, step2Fragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.commit()
}
}
class WritePost_Step2_Fragment : Fragment() {
companion object {
fun newInstance(foo: Int): WritePost_Step2_Fragment {
val args= Bundle()
args.putInt("foo", foo)
val fragment= WritePost_Step2_Fragment()
fragment.arguments= args
return fragment
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: View = inflater.inflate(R.layout.fragment_write_post_step2, container, false)
return view
}
// Activity의 OnCreate와 같은 역할을 하는 함수
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
Log.d("life_cycle", "F onViewCreated")
super.onViewCreated(view, savedInstanceState)
}
}
you have error in you xml file (line no. 6 specifically), check your xml file first it is located in res/layout directory
I am working with MVVM architecture and I don't get it why am I having this error? My other classes have the same structure and they are working perfectly fine. Below i have shared the code for both my Fragment Class and the ViewModel Class along with the error
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.beyond.sellandtrack, PID: 5380
java.lang.RuntimeException: Cannot create an instance of class com.beyond.sellandtrack.screens.dashboard.DashboardViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:275)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.beyond.sellandtrack.screens.dashboard.DashboardFragment.onCreateView(DashboardFragment.kt:33)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2224)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1997)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:809)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7555)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.beyond.sellandtrack.screens.dashboard.DashboardFragment.onCreateView(DashboardFragment.kt:33)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2224)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1997)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:809)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7555)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)
Caused by: kotlin.KotlinNullPointerException
at com.beyond.sellandtrack.screens.dashboard.DashboardViewModel.<init>(DashboardViewModel.kt:20)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:267)
at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
at com.beyond.sellandtrack.screens.dashboard.DashboardFragment.onCreateView(DashboardFragment.kt:33)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.addAddedFragments(FragmentManager.java:2224)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1997)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1953)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
at android.os.Handler.handleCallback(Handler.java:809)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7555)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)
I/Process: Sending signal. PID: 5380 SIG: 9
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
Fragment Class
class DashboardFragment : Fragment() {
private lateinit var dashboardViewModel: DashboardViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val binding = DataBindingUtil.inflate<FragmentDashboardBinding>(
inflater,R.layout.fragment_dashboard,container,false
)
dashboardViewModel= ViewModelProvider(this).get(DashboardViewModel::class.java)
ViewModel Class
class DashboardViewModel(application: Application) : AndroidViewModel(application) {
lateinit var user: User
private var auth : FirebaseAuth = FirebaseAuth.getInstance()
private var repository: Repository = Repository()
init {
user = repository.getUserData()!!
}
You need to check if the getUserData is not null. in init block
init {
user = repository.getUserData()!! //you are forcefully marking this as non null
}
check if the getUserData() is returning null here or not. Which is null most probably and that's why it's failing
I think you should try Koin to inject and create instance of ViewModel.
Its easy to use and syntax is brief.
https://insert-koin.io/.
// Injected by constructor
class MyViewModel(val repo : MyRepository) : ViewModel()
// declared ViewModel using the viewModel keyword
val myModule : Module = module {
viewModel { MyViewModel(get()) }
single { MyRepository() }
}
// Just get it
class MyActivity() : AppCompatActivity() {
// lazy inject MyViewModel
val myViewModel : MyViewModel by viewModel()
}
I think your DashboardViewModel class should extending from ViewModel() not AndroidViewModel()
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
import androidx.lifecycle.ViewModel
class DashboardViewModel : ViewModel()
I'm new to Kotlin and I created a constant array to use in spinner inside of fragment. When I try to run the code, the app crashes. I've tried to find a solution, but couldn't.
The really weird part, it worked perfectly yesterday when I worked on it, and today it's crashes.
this is my fragment:
class PersonalDetailsFragment : Fragment() {
private lateinit var listener: OnChangeFragmentListener
override fun onAttach(context: Context?) {
super.onAttach(context)
listener = getListenerOrThrowException(OnChangeFragmentListener::class.java)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_personal_deatails, container, false)
v.spinnerAge.adapter = ArrayAdapter<Int>(context, android.R.layout.simple_list_item_1, LIST_AGE)
v.btnGoDetails.setOnClickListener { listener.changeFragment() }
return v
}
this is my Constant class:
class Constant {
companion object {
#JvmField val LIST_AGE = getAgeList()
private fun getAgeList(): Array<Int?> {
val array = arrayOfNulls<Int>(83)
for (i in array.indices){
var age = i + 17
array[i] = age
}
return array
}
}
Error Log:
2019-06-06 19:02:53.732 18331-18331/com.eldareini.kotlin.meet4match
E/tlin.meet4matc: No package ID 7f found for ID 0x7f0d0044.
2019-06-06 19:02:53.732 18331-18331/com.eldareini.kotlin.meet4match
D/AndroidRuntime: Shutting down VM
2019-06-06 19:02:53.736 18331-18331/com.eldareini.kotlin.meet4match E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.eldareini.kotlin.meet4match, PID: 18331
java.lang.ExceptionInInitializerError
at com.eldareini.kotlin.meet4match.signup.PersonalDetailsFragment.onCreateView(PersonalDetailsFragment.kt:57)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x7f0d0044
at android.content.res.Resources.getText(Resources.java:348)
at android.content.res.Resources.getString(Resources.java:441)
at com.eldareini.kotlin.meet4match.Constant.<clinit>(Constant.kt:69)
at com.eldareini.kotlin.meet4match.signup.PersonalDetailsFragment.onCreateView(PersonalDetailsFragment.kt:57)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)