Wear OS - settting up project with fragments - android

I'm trying to set up a Wear OS project. I have some experience with normal android development but Wear os is new for me.
I'm used to just having one MainActivity and some fragments. But I'm trying to make that work for Wear OS but with no success. It keeps crashing when I want to use viewBinding in the OverviewFragment.kt.
I got the following project now:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.wear.widget.BoxInsetLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/box_inset_layout_padding"
tools:context=".MainActivity"
tools:deviceIds="wear">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/inner_frame_layout_padding"
app:layout_boxedEdges="left|right">
<include
layout="#layout/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</androidx.wear.widget.BoxInsetLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.wear.widget.BoxInsetLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/nav_graph" />
</androidx.wear.widget.BoxInsetLayout>
fragment_overview.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.OverviewFragment">
<TextView
android:id="#+id/tvOverview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:text="overview"
android:textAlignment="center" />
</FrameLayout>
MainActivity.kt
class MainActivity : FragmentActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
}
OverviewFragment.kt
class OverviewFragment : Fragment() {
private var _binding: FragmentOverviewBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_overview, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.tvOverview.setOnClickListener {
println("great")
}
}
}
Just a simple design, but it does not like the binding.tvOverview.setOnClickListener part in OverviewFragment.kt. It just keeps crashing.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.krakert.tracker, PID: 7261
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.krakert.tracker/com.krakert.tracker.MainActivity}: android.view.InflateException: Binary XML file line #17: Binary XML file line #8: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.view.InflateException: Binary XML file line #17: Binary XML file line #8: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
Caused by: java.lang.NullPointerException
at com.krakert.tracker.ui.OverviewFragment.getBinding(OverviewFragment.kt:15)
at com.krakert.tracker.ui.OverviewFragment.onViewCreated(OverviewFragment.kt:28)
I would like some help here, setting the project up. Really new to Wear OS
Thanks!

Not sure how this can work and suspect this is where the NullPointerException comes from
private var _binding: FragmentOverviewBinding? = null
private val binding get() = _binding!!
compare to the example at https://developer.android.com/topic/libraries/view-binding#fragments
which sets _binding in onCreateView

Related

Handle android.view.InflateException: Error inflating class fragment

I am trying to build an app with a single activity that hosts multiple fragments. I am also using Nav Graph and Data Binding.
I am getting this error which I can't find a way around it even after reviewing similar questions on StackOverflow. All I am getting is old ways about using support fragment manager and maps fragment which are not helping my issue.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.uxstate.goldsearchkotlin/com.uxstate.goldsearchkotlin.MainActivity}: android.view.InflateException: Binary XML file line #9 in com.uxstate.goldsearchkotlin:layout/activity_main: Binary XML file line #9 in com.uxstate.goldsearchkotlin:layout/activity_main: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #9 in com.uxstate.goldsearchkotlin:layout/activity_main: Binary XML file line #9 in com.uxstate.goldsearchkotlin:layout/activity_main: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #9 in com.uxstate.goldsearchkotlin:layout/activity_main: Binary XML file line #9 in com.uxstate.goldsearchkotlin:layout/activity_main: Error inflating class fragment
Caused by: android.view.InflateException: Binary XML file line #9 in com.uxstate.goldsearchkotlin:layout/activity_main: Error inflating class fragment
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property adapter has not been initialized
at com.uxstate.goldsearchkotlin.MainListFragment.getAdapter(MainListFragment.kt:23)
at com.uxstate.goldsearchkotlin.MainListFragment.onViewCreated(MainListFragment.kt:57)
This is my NavHostFragment which is the main cause of the crash.
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="#navigation/nav_graph" />
Surprisingly, if I change <fragment> to FrameLayout the app is not crashing but the layout is not working right with FrameLayout.
This is how I inflate the layout for the home fragment.
class MainListFragment : Fragment() {
private val viewModel: ListViewModel by activityViewModels()
private var _binding: FragmentMainListBinding? = null
private val binding get() = _binding!!
lateinit var adapter: MainAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMainListBinding.inflate(inflater, container, false)
val root: View = binding.root
return root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Add click listener to floating action button
binding.fabMain.setOnClickListener {
addListItem()
}
adapter = MainAdapter(viewModel.mainList)
main_list_view.adapter = adapter
main_list_view.layoutManager = LinearLayoutManager(requireContext())
}
Need help on how to address this exception.
The error came about because I had not initialized lateinit var adapter: MainAdapter
I initialized this inside onCreateView() and the app did not crash.

DrawerLayout returning null in Kotlin Android application

I'm starting to learn Kotlin for Android apps. This is one of my first projects and I'm trying to set a toggle listener for my drawer menu, but getting an error because it is being returned as null. The ID I'm using to find it seems to be set correctly.
activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolBar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:title="#string/app_name"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rv_list"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="#+id/toolBar"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
The drawer_menu.xml file:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:openDrawer="start" xmlns:app="http://schemas.android.com/apk/res-auto">
<include layout="#layout/activity_main"/>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/menu"/>
</androidx.drawerlayout.widget.DrawerLayout>
And the MainActivity.kt (where I'm setting the toggle)
class MainActivity : AppCompatActivity() {
private val rvList: RecyclerView by lazy {
findViewById<RecyclerView>(R.id.rv_list)
}
private val adapter = ContactAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initDrawer()
bindViews()
updateList()
}
private fun initDrawer() {
val drawerLayout = findViewById<View>(R.id.drawerLayout) as DrawerLayout
val toolBar = findViewById<View>(R.id.toolBar) as Toolbar
setSupportActionBar(toolBar)
val toggle = ActionBarDrawerToggle(this, drawerLayout, toolBar, R.string.open_drawer, R.string.close_drawer)
drawerLayout.addDrawerListener(toggle)
toggle.syncState()
}
...
}
And this is the error I'm getting:
2022-01-19 10:16:29.863 10567-10567/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: curso.android.contactlist, PID: 10567
java.lang.RuntimeException: Unable to start activity ComponentInfo{curso.android.contactlist/curso.android.contactlist.MainActivity}: java.lang.NullPointerException: null cannot be cast to non-null type androidx.drawerlayout.widget.DrawerLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2861)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2943)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1630)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6626)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:811)
Caused by: java.lang.NullPointerException: null cannot be cast to non-null type androidx.drawerlayout.widget.DrawerLayout
at curso.android.contactlist.MainActivity.initDrawer(MainActivity.kt:34)
at curso.android.contactlist.MainActivity.onCreate(MainActivity.kt:27)
at android.app.Activity.performCreate(Activity.java:7032)
at android.app.Activity.performCreate(Activity.java:7023)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1236)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2814)
Does anyone know why is it returning null?
the drawer_menu isn't inside activity_main but the other way around. so replace
setContentView(R.layout.activity_main)
with
setContentView(R.layout.drawer_menu)
There might be more problems but this is what I noticed at first
Am i missing something, or is your Drawer layout not part of the activity_main.xml? If that is the case, then its logical why your findViewById<View>(R.id.drawerLayout) will return null.

In this news app, I keep getting InflateException

java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.newsapp/com.example.newsapp.ui.MainActivity}:
android.view.InflateException: Binary XML file line #25 in
com.example.newsapp:layout/activity_main: Binary XML file line #25 in
com.example.newsapp:layout/activity_main: Error inflating class
fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
class MainActivity : AppCompatActivity() {
lateinit var viewModel : NewsViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val newsRepository = NewsRepository(ArticleDatabase(this))
val viewModelProviderFactory = NewsViewModelProviderFactory(newsRepository)
viewModel = ViewModelProvider(this, viewModelProviderFactory).get(NewsViewModel::class.java)
bottomNavigationView.setupWithNavController(nav_host_fragment_container.findNavController())
}
<FrameLayout
android:id="#+id/flFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/bottomNavigationView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<fragment
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/nav_host_fragment_container"
app:defaultNavHost="true"
app:navGraph="#navigation/news_nav_graph"/>
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="56dp"
app:backgroundTint="#color/grey"
app:menu="#menu/bottom_navigation_menu"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"/>
You have two mistakes in the code
First, you name the listview and the listfiles with the same variable name
// look at that in these lines, both of them had the same variable name
private lateinit var list: ListView
val list = dir.listFiles()
Second, the part which makes the exception in this line
val list = dir.listFiles() // dir.listFiles() returns null
check this answer if you want to get a list of files in directory as I understand

listview must not be null

I am a beginner at programming. I have an error message when I start my app and do not know what to do with the code. Can someone help me please.
Here is my code:
Activity :
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val items = ArrayList<String>()
items.add("Test1")
items.add("Test2")
items.add("Test3")
listview1.adapter = Adapter1(this, items)
val transaction1 = supportFragmentManager.beginTransaction()
fragment1Button1.setOnClickListener{
transaction1.replace(R.id.fragment1Platz,Fragment1())
transaction1.commit()
}
}
}
Fragment :
class Fragment1 : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_fragment1, container, false)
}
}
Adapter:
class Adapter1 (context : Context, items : ArrayList<String>) : BaseAdapter() {
private val context: Context = context
private val items: ArrayList<String> = items
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val listeneintrag = LayoutInflater.from(context).inflate(R.layout.adapter1_layout,parent, false)
listeneintrag.findViewById<TextView>(R.id.adapter_textfeld1).text = items.get(position)
return listeneintrag
}
override fun getItem(position: Int): String {
return items.get(position)
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return items.size
}
}
Error stacktrace:
2020-02-01 13:37:17.972 10729-10729/? E/AndroidRuntime: FATAL
EXCEPTION: main Process: strauss2002.yannick.fragmentetest, PID: 10729
java.lang.RuntimeException: Unable to start activity
ComponentInfo{strauss2002.yannick.fragmentetest/strauss2002.yannick.fragmentetest.MainActivity}:
java.lang.IllegalStateException: listview1 must not be null at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106) at
android.os.Looper.loop(Looper.java:164) at
android.app.ActivityThread.main(ActivityThread.java:6494) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) Caused
by: java.lang.IllegalStateException: listview1 must not be null at
strauss2002.yannick.fragmentetest.MainActivity.onCreate(MainActivity.kt:29)
at android.app.Activity.performCreate(Activity.java:7009) at
android.app.Activity.performCreate(Activity.java:7000) at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106) at
android.os.Looper.loop(Looper.java:164) at
android.app.ActivityThread.main(ActivityThread.java:6494) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Here is my updated Main Activity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val listview1=findViewById<ListView>(R.id.listview1)
val items = ArrayList<String>()
items.add("Test1")
items.add("Test2")
items.add("Test3")
listview1.adapter = Adapter1(this, items)
val transaction1 = supportFragmentManager.beginTransaction()
fragment1Button1.setOnClickListener{
transaction1.replace(R.id.fragment1Platz,Fragment1())
transaction1.commit()
}
}
}
And here is the new error message:
2020-02-02 11:15:15.935 12764-12764/strauss2002.yannick.fragmentetest E/AndroidRuntime: FATAL EXCEPTION: main
Process: straus
s2002.yannick.fragmentetest, PID: 12764
java.lang.RuntimeException: Unable to start activity ComponentInfo{strauss2002.yannick.fragmentetest/strauss2002.yannick.fragmentetest.MainActivity}: java.lang.IllegalStateException: listview1 must not be null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.IllegalStateException: listview1 must not be null
at strauss2002.yannick.fragmentetest.MainActivity.onCreate(MainActivity.kt:28)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6494) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
Here is the xml of the activity_main:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/fragment1Platz"
android:layout_width="410dp"
android:layout_height="495dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent">
</FrameLayout>
<Button
android:id="#+id/fragment1Button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:text="Öffne Fragment 1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.529"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here is the xml of the fragment_fragment1:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragment1">
<!-- TODO: Update blank fragment layout -->
<ListView
android:id="#+id/listview1"
android:layout_width="match_parent"
android:layout_height="322dp"/>
</FrameLayout>
Here is the xml of the adapter1_layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/adapter_textfeld1"
android:layout_width="137dp"
android:layout_height="53dp"
android:layout_marginTop="128dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Because you didn't call findViewById for listview1.
Add listview1=findViewById(R.id.yourListViewIdInXml); just after setContentView method of oncreate
Or if you are using kotlin synthetic then make sure that listview1 resides in activity_main.xml file
Update
The problem persists because you are calling findViewById on an id(listview1) which is not available in activity_main.xml. Note that in case of activities, when you call findViewById it searches id in the layout file which is passed in setContentView method, that is activity_main.xml in your case. So when you called findViewById<ListView>(R.id.listview1) it searches listview1 in activity_main.xml, but as we know that there is no view available in activity_main.xml which has id=listview1, so findViewById simply returns null and that's why you are getting this error. So to get rid of this exception change:
val listview1=findViewById<ListView>(R.id.listview1)
to this:
val listview1=findViewById<ListView>(R.id.kontaktliste)
I had the same issue. I resolved just putting the setContentView(activity_layout) in the onResume method.
I don't know why this error hasn't occurred in other activities with a listView
The reason you are getting Null Exception is that you are trying to access listView1 before the fragment view is completely created which means listView1 doesn't exist yet.
So you have to move that part of the code you have in your MainActivity to the onCreateView method of your fragment like so:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_fragment1, container, false)
val items = ArrayList<String>()
items.add("Test1")
items.add("Test2")
items.add("Test3")
//THIS IS HOW YOU REFERENCE YOU VIEWS IN A FRAGMENT IN KOTLIN
rootView.listview1.adapter = Adapter1(this, items)
return rootView
}
And pay attention that in a fragment, you have to reference the views through the inflated rootView for your fragment.

NavHostFragment error inflating class fragment when screen is rotated

I'm creating an application where it uses the Navigation Architecture, but my navigation has no default host, and can be set based on the selected destination by the user.
So this is the setup of my NavHostFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var finalHost: NavHostFragment? = null
when (bundle) {
REQUEST_FIRST -> {
finalHost = NavHostFragment.create(R.navigation.navigation_first)
}
REQUEST_SECOND -> {
finalHost = NavHostFragment.create(R.navigation.navigation_second)
}
REQUEST_THIRD -> {
finalHost = NavHostFragment.create(R.navigation.navigation_third)
}
}
supportFragmentManager.beginTransaction()
.replace(R.id.fragmentMain, finalHost!!)
.setPrimaryNavigationFragment(finalHost)
.commit()
}
and this is my main activity layout.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black">
<!-- some stuff -->
<fragment
android:id="#+id/fragmentMain"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
So, my MainActivity is loading correctly but when I start to rotate the screen of the device, It encounters some errors.
java.lang.RuntimeException: Unable to start activity ComponentInfo: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class fragment
the said error is pointing on my setContentView(R.layout.activity_main) and the NavHostFragment <fragment> in layout.
any help is appreciated, Thanks!

Categories

Resources