I'm new at app development and Kotlin and I'm trying to do my first app for learning purposes but I'm kinda lost.
Right now, I have an activity where to log in to my app via firebase. Then what I'm trying to do is a bottom navigation bar where to go between activities. Via some tutorials, I found that the best way to develop is via fragments instead of activities, but I don't know how to work with them.
So right now I have two questions:
- How to do that when I open my app after login my main activity shows a fragment directly instead after clicking on a button: in the first photo you can see my navigation bar that opens with Home selected but its main activity and it's only when I click again on home that goes to fragment
- How can I implement buttons inside fragments and go to other activities? For example, on my profile fragment I want to have a log out button that when I click on it goes to my login activity, but it always crashes and gives me this error :
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.appilerna, PID: 2263 java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.button.MaterialButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at Fragments.ProfileFragment.logOut(ProfileFragment.kt:48) at Fragments.ProfileFragment.onCreateView(ProfileFragment.kt:42) 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:883) at android.os.Handler.dispatchMessage(Handler.java:100) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7356) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
My code for main activity:
class MainActivity : AppCompatActivity() {
private val calendarFragment = CalendarFragment()
private val favoritesFragment = FavoritesFragment()
private val profileFragment = ProfileFragment()
private val homeFragment = HomeFragment()
private val searchFragment = SearchFragment()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bottom_navigation.setOnItemSelectedListener { it:MenuItem ->
when (it.itemId) {
R.id.ic_home -> replaceFragment(homeFragment)
R.id.ic_search -> replaceFragment(searchFragment)
R.id.ic_favourites -> replaceFragment(favoritesFragment)
R.id.ic_calendar -> replaceFragment(calendarFragment)
R.id.ic_account -> replaceFragment(profileFragment)
}
true
}
}
private fun replaceFragment(fragment: Fragment){
if(fragment != null){
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.fragment_container, fragment)
transaction.commit()
}
}
}
My main activity xml:
<?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"
android:background="@color/backgroundColor" >
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@ id/bottom_navigation"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="@menu/menu"
android:background="@color/salmon"
app:itemIconTint="@color/white"
app:itemTextColor="@color/white" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="@ id/fragment_container"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@ id/bottom_navigation"/>
</androidx.constraintlayout.widget.ConstraintLayout>
My ProfileFragment code:
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
* Use the [ProfileFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class ProfileFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(ARG_PARAM1)
param2 = it.getString(ARG_PARAM2)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_profile, container, false)
logOut(view)
return view
}
fun logOut(view: View){
logoutButton.setOnClickListener(View.OnClickListener {
FirebaseAuth.getInstance().signOut()
//view.context.startActivity(Intent(view.context, LogInActivity::class.java))
val intent = Intent(activity, LogInActivity::class.java)
activity?.startActivity(intent)
})
}
companion object {
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ProfileFragment.
*/
// TODO: Rename and change types and number of parameters
@JvmStatic fun newInstance(param1: String, param2: String) =
ProfileFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
}
My profile fragment xml:
<androidx.constraintlayout.widget.ConstraintLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="Fragments.ProfileFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:id="@ id/profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Profile"
android:textSize="36sp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"/>
<com.google.android.material.button.MaterialButton
android:id="@ id/logoutButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="160dp"
android:layout_marginLeft="160dp"
android:layout_marginRight="163dp"
android:layout_marginEnd="163dp"
android:layout_marginBottom="16dp"
android:text="LOG OUT"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
Thank you
EDIT
I just found answer for my first question doing this on Main Activity:
ft.replace(android.R.id.content, homeFragment)
ft.commit()
bottom_navigation.setOnItemSelectedListener { it: MenuItem ->
when (it.itemId) {
R.id.ic_home -> replaceFragment(homeFragment)
R.id.ic_search -> replaceFragment(searchFragment)
R.id.ic_favourites -> replaceFragment(favoritesFragment)
R.id.ic_calendar -> replaceFragment(calendarFragment)
R.id.ic_account -> replaceFragment(profileFragment)
}
true
}
}
private fun replaceFragment(fragment: Fragment){
if(fragment != null){
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(android.R.id.content, fragment)
transaction.commit()
}
}
But still having troubles with my profile Logout button.
CodePudding user response:
Solution of your crash- you have not initialized MaterialButton
fun logOut(view: View){
//Add this line
**var logoutButton= view.findViewById<MaterialButton>(R.id.logoutButton)**
//---------
logoutButton.setOnClickListener(View.OnClickListener {
FirebaseAuth.getInstance().signOut()
//view.context.startActivity(Intent(view.context, LogInActivity::class.java))
val intent = Intent(activity, LogInActivity::class.java)
activity?.startActivity(intent)
})
}
CodePudding user response:
Sorry, but your question is too wide to answer and I think all of your questions answers you can find in this tutorial: https://www.youtube.com/watch?v=v8MbOjBCu0o
Here you can see how to use fragments with android bottom navigation bar and using button click listener in a fragment
CodePudding user response:
First, you need to know how to work with NavHost
and NavController
, I think this link will help you.