I'm trying to retrieve lost data from my Firebase and then implement some basic crud so that I can barely pass this paper. Here are the source codes that I'm using:
activity_admin_main.xml: this is the UI for the functions, I have yet to add the buttons for the crud methods mentioned before, and this is only an attempt to list the documents in a Firebase collection called "course"
<?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"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/appbackground"
android:paddingTop="?attr/actionBarSize">
<ImageView
android:id="@+id/imageView2"
android:layout_width="45dp"
android:layout_height="43dp"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.056"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/appicon" />
<TextView
android:id="@+id/tvName"
android:layout_width="220dp"
android:layout_height="40dp"
android:layout_marginTop="16dp"
android:background="@color/edit_text_background"
android:fontFamily="@font/aldrich"
android:text="tvName"
android:textAlignment="center"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.109"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView2" />
<TextView
android:id="@+id/tvEmail"
android:layout_width="330sp"
android:layout_height="30sp"
android:layout_marginTop="20dp"
android:background="@color/edit_text_background"
android:fontFamily="@font/aldrich"
android:text="TextView"
android:textAlignment="center"
android:textSize="22sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.259"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvName" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="@color/button_background_color"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="@menu/bottom_nav_menu" />
<fragment
android:id="@+id/nav_host_fragment_activity_admin_main"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:layout_constraintBottom_toTopOf="@id/nav_view"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="@navigation/mobile_navigation" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragment_course.xml: this is the xml of the code with a problem, there are two other fragment xmls, but those are still empty for now, and share similar crud functions, so I could just modify the complete code that does function well
<?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=".ui.courses.CourseFragment">
<ScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription=" ">
<LinearLayout
android:id="@+id/containerLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- TextViews dynamically added here -->
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
AdminMain.kt: this is the Kotlin file for the whole navigation view, and the function I used to retrieve the name value from my firestore, not much to see here... I think
package com.example.assignment
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.example.assignment.databinding.ActivityAdminMainBinding
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
class AdminMain : AppCompatActivity() {
private lateinit var binding: ActivityAdminMainBinding
lateinit var tvNameObj: TextView
lateinit var tvEmailObj: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAdminMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val db = Firebase.firestore
tvNameObj = findViewById(R.id.tvName)
tvEmailObj = findViewById(R.id.tvEmail)
val navView: BottomNavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_activity_admin_main)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
val appBarConfiguration = AppBarConfiguration(
setOf(
R.id.navigation_course, R.id.navigation_dashboard, R.id.navigation_notifications
)
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
var name = ""
val email = intent.getStringExtra("email")
if (email != null) {
db.collection("admin")
.whereEqualTo("email", email)
.get()
.addOnSuccessListener { documents ->
if (!documents.isEmpty) {
val document = documents.documents[0]
name = document.getString("name").toString()
if (name != "") {
tvNameObj.text = name
tvEmailObj.text = email
Log.i("Successful", "Name retrieved successfully")
}
} else {
// Handle case where no document is found
Log.w("Not found", "Name not found")
}
}
.addOnFailureListener { exception ->
// Handle any errors here
Log.wtf("WTF", "What The Fxxk happened!?", exception)
}
}
}
}
And finally, CourseFragment.kt, this is where the problem occurred, for now I'm only attempting to retrieve and display the data from Firebase and store them in textViews that will be stored in a linear layout, then store the linear layout in the scrollView so that it only contain one direct child.
package com.example.assignment.ui.courses
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.assignment.databinding.FragmentCourseBinding
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
class CourseFragment : Fragment() {
private var _binding: FragmentCourseBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val courseViewModel =
ViewModelProvider(this).get(CourseViewModel::class.java)
_binding = FragmentCourseBinding.inflate(inflater, container, false)
val root: View = binding.root
val scrollView: ScrollView = binding.scrollView
val linearLayout: LinearLayout = LinearLayout(context)
linearLayout.orientation = LinearLayout.VERTICAL
// Fetch data from Firestore
val db = Firebase.firestore
db.collection("course")
.get()
.addOnSuccessListener { documents ->
for (document in documents) {
// Create a TextView for each document
val textView = TextView(context)
textView.text = document.data.toString()
// Add the TextView to the LinearLayout
linearLayout.addView(textView)
}
// Add the LinearLayout to the ScrollView
scrollView.addView(linearLayout)
}
.addOnFailureListener { exception ->
Log.w("Not Found", "Error getting documents: ", exception)
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
So my problem is that Android Studio keeps returning this error about having more than 1 child, and I have tried moving scrollView.addView(linearLayout)
to other lines but still to no avail. What can I try next?
And here's the fatal error message:
FATAL EXCEPTION: main
Process: com.example.assignment, PID: 21660
java.lang.IllegalStateException: ScrollView can host only one direct child
at android.widget.ScrollView.addView(ScrollView.java:261)
at com.example.assignment.ui.courses.CourseFragment$onCreateView$1.invoke(CourseFragment.kt:54)
at com.example.assignment.ui.courses.CourseFragment$onCreateView$1.invoke(CourseFragment.kt:44)
at com.example.assignment.ui.courses.CourseFragment.onCreateView$lambda$0(CourseFragment.kt:44)
at com.example.assignment.ui.courses.CourseFragment.$r8$lambda$k4oKZ0mPYZVACvyeiTV-bMatA7Q(Unknown Source:0)
at com.example.assignment.ui.courses.CourseFragment$$ExternalSyntheticLambda0.onSuccess(Unknown Source:2)
at com.google.android.gms.tasks.zzm.run(com.google.android.gms:play-services-tasks@@18.1.0:1)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
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)
You are adding a new LinearLayout in your fragment instead of using the one already present in your XML.
The correct fragment code should be:
class CourseFragment : Fragment() {
private var _binding: FragmentCourseBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val courseViewModel =
ViewModelProvider(this).get(CourseViewModel::class.java)
_binding = FragmentCourseBinding.inflate(inflater, container, false)
val root: View = binding.root
val scrollView: ScrollView = binding.scrollView
val linearLayout: LinearLayout = binding.containerLayout
// Fetch data from Firestore
val db = Firebase.firestore
db.collection("course")
.get()
.addOnSuccessListener { documents ->
for (document in documents) {
// Create a TextView for each document
val textView = TextView(context)
textView.text = document.data.toString()
// Add the TextView to the LinearLayout
linearLayout.addView(textView)
}
}
.addOnFailureListener { exception ->
Log.w("Not Found", "Error getting documents: ", exception)
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
First thing get the correct LinearLayout using binding
val linearLayout: LinearLayout = binding.containerLayout
Remove scrollView.addView(linearLayout)
, you already have that in your XML.