How to fetch resource id in fragment using kotlin in android? - android

I tried to this code which is mention below, but getting crash during run time. The error occurred is Android Run time:
FATAL EXCEPTION: main Process: com.root.specialbridge, PID: 17706 kotlin.KotlinNullPointerException at com.root.specialbridge.fragments.profile_fragment.WallFragments.initializeView(WallFragments.kt:49)
class WallFragments : Fragment(){
private var wallAdapter: WallAdapter? = null
private var wall_recycler: RecyclerView? = null
private val wallArrayList: ArrayList<Wall>? = null
private var mainlayout: LinearLayout? = null
private var no_result_found_layout: RelativeLayout? = null
private var userProfileWallInterface: UserProfileWallInterface? = null
internal var wallActivityBeanse: MutableList<WallActivityBeans> = ArrayList()
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater!!.inflate(R.layout.wall_fragments, container, false)
userProfileWallInterface = UserProfileWallPresentation(activity, this)
initializeView()
wallAdapter = WallAdapter(activity, wallActivityBeanse)
wall_recycler!!.adapter = wallAdapter
return view
}
fun initializeView() {
wall_recycler = view!!.findViewById(R.id.wall_recycler_id) as RecyclerView
mainlayout = view!!.findViewById(R.id.mainlayout) as LinearLayout
no_result_found_layout = view!!.findViewById(R.id.no_result_found_layout) as RelativeLayout
wall_recycler!!.layoutManager = LinearLayoutManager(activity)
wall_recycler!!.setHasFixedSize(true)
if (AuthPreference(activity).isGetMemberProfile) {
userProfileWallInterface!!.getMemberProfileWall(view!!)
} else {
userProfileWallInterface!!.getUserProfileWall(AuthPreference(activity).token, AuthPreference(activity).user.id, view!!)
}
}
companion object {
val instance: WallFragments
get() = WallFragments() }}

Add
apply plugin: 'kotlin-android-extensions'
in the app level gradle file and
import
import kotlinx.android.synthetic.main.fragment_your_fragment_name.view.*
in the onCreateView of your fragment (e.g. if the id of your textview is textView)
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater!!.inflate(R.layout.fragment_splashfragment, container, false)
view.textView.text = "hello" //add your view before id else getting nullpointer exception
return view
}
UPDATE:
declare viewOfLayout in your class instead of view.
class yourfragment:Fragment(){
private lateinit var viewOfLayout: View
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
viewOfLayout = inflater!!.inflate(R.layout.fragment_splashfragment, container, false)
viewOfLayout.textView.text = "hello" //add your view before id else will get nullpointer exception
return viewOfLayout
}
}

Introducing Kotlin Android Extensions.
You do not have to use findViewById anymore. Using this plugin you can use the UI component directly as a global field. Supported in Activities, fragments and views.
Example,
To refer text view from the layout below,
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/hello"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, MyActivity"/>
</android.support.constraint.ConstraintLayout>
in activity you can simply write,
// Using R.layout.activity_main from the main source set
import kotlinx.android.synthetic.main.activity_main.*
class MyActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Instead of findViewById(R.id.hello) as TextView
hello?.setText("Hello, world!")
}
}
in fragments,
// Using R.layout.fragment_content from the main source set
import kotlinx.android.synthetic.main.fragment_content.*
class ContentFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_content, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Instead of view.findViewById(R.id.hello) as TextView
hello?.setText("Hello, world!")
}
}
and for views,
// Using R.layout.item_view_layout from the main source set
import kotlinx.android.synthetic.main.item_view_layout.*
class ItemViewHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bindData(data: String) {
// Instead of itemView.findViewById(R.id.hello) as TextView
itemView.hello?.setText(data)
}
}
And, you should not use !! everywhere, unless you want NullPointerException explicitly.
Instead use anyone from the following:
Do null check with safe call - ?., Eg. nullableVariable?.method()
Use non-null object using ?.let{ }, Eg. nullableVariable?.let { it.method() }
Supplying a backup value for the nullable variable using elvis operator - ?:, Eg. nullableVariable ?: <backupValue>.
Read more about Null Safety in Kotlin.

Initialization of view in fragment :
wall_recycler=view.findViewById<RecyclerView>(R.id.wall_recycler_id)
mainlayout = view.findViewById<LinearLayout>(R.id.mainlayout)
The problem is that you are accessing it too soon. requireView() and view returns null in onCreateView.I have find all views in onViewCreated().
Try doing it in the onViewCreated method:
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
wall_recycler=requireView().findViewById<RecyclerView>(R.id.wall_recycler_id)
mainlayout = requireView().findViewById<LinearLayout>(R.id.mainlayout)
mainlayout.setOnClickListener { Log.d(TAG, "onViewCreated(): hello world");}
}

Related

Setting setOnClickListener using bindings android kotlin

I have been doing a tutorial that is a bit out of date and uses synthetics rather than bindings. I am trying to use bindins. I am trying to set up a listener in a fragment (AddEditFragment.kt). It's using a callback to MainActivity.onSaveClicked.
In AddEditFragment I use an import for the binding
import com.funkytwig.tasktimer.databinding.FragmentAddEditBinding
I have a lateinit on the first line of the class defenition
class AddEditFragment : Fragment() {
private lateinit var binding: FragmentAddEditBinding
I am initializing the bunding in onActivityCreated and setting up the listner. I can use findViewById to get the ID
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val addEditSave = view?.findViewById(R.id.addEditSave) as Button
addEditSave.setOnClickListener { listener?.onSaveClicked() }
}
And this works fine but if I try to use the binding
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
binding.addEditSave.setOnClickListener { listener?.onSaveClicked() }
}
The code does not show any errrors but it does not seem to create the listner. I have a Log.d in the onSaveClicked callback function and when I use the first (findViewById) version of the function it works (it calles onSaveClicked) but with the second version (using bindings) onSaveClicked does not get called when I click the Button.
I Cant figre out why the second version does not work, I thought the two versions of onActivityCreated should do the same thing.
The interface in AddEditFragment.kt is
interface OnSaveClicked {
fun onSaveClicked()
}
In fragment you should add your view in onCreateView or in OnViewCreated not in onActivityCreated
Please refer link for more details.
private var _binding: FragmentAddEditBinding? = 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? {
_binding = FragmentAddEditBinding.inflate(inflater, container, false)
val view = binding.root
binding.addEditSave.setOnClickListener { listener?.onSaveClicked() }
return view
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
OK, thanks for all the help. turned out I was doing the inflate wrong.
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
Log.d(TAG, "onCreateView")
binding = FragmentAddEditBinding.inflate(layoutInflater, container, false)
return binding.root
}
I was doing
binding = FragmentAddEditBinding.inflate(layoutInflater)
I missed out on the last 2 args as I was taking the code from the inflate when I am in an Activity, not a Fragment. I think it is to do with the layout effecticly being in the parent.

Android Studio: Set Text in fragment

I've recently picked up an Android Studio project I started a year ago in Kotlin.
It features three fragments that can be navigated through by a bottom navigation bar.
Now, to break my current issue down to a simple example that even doesn't work for me:
Given there's a the editText object exercise in fragment_home.xml and I want to call and alter it in HomeFragment.kt.
I checked every source of advice I could find from Google & Stackoverflow and came up with the following code in HomeFragment.kt (partially pre-coded by AndroidStudio):
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val root: View = binding.root
val view: View = inflater!!.inflate(R.layout.fragment_home,container,false)
view.exercise.setText("This is an exceptionally hardcoded string")
The last line stands for every object I tried to reach. I also tried onClickListening for buttons like so:
val btnNewExercise = view.findViewById<Button>(R.id.btn_new_exercise)
btnNewExercise.setOnClickListener {view
Toast.makeText(view.context, "New exercise will be generated", Toast.LENGTH_SHORT).show()
println("Generated a new exercise")
}
but nothing happens when I start the app/ hit the buttons - I seem to can't get through to the actual view's objects to access them. Even ran into NullPointerExceptions on my way to a solution.
I could supply the fragment and layout files if needed - just thought this way it might be easier at first.
If anybody could tell me where I'm wrong I'd be really grateful! Thanks in advance!
You inflated the layout twice.
Remove this. You already inflated the layout using view binding in the FragmentHomeBinding.inflate... call
val view: View = inflater!!.inflate(R.layout.fragment_home,container,false)
and replace
view.exercise.setText("This is an exceptionally hardcoded string")
with (using binding
binding.exercise.setText("This is an exceptionally hardcoded string")
then the last line on your onCreateView should be
return binding.root
Note: You should have these class properties:
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
So it will look like this:
//move your view model as a class property so it will be accessible by other class methods
private val homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!//transform to immutable
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
//use the immutable view binding property
binding.exercise.setText("This is an exceptionally hardcoded string")
return binding.root
}
For more info, read view binding
Try this solution.
class HomeFragment : Fragment() {
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val homeViewModel =
ViewModelProvider(this).get(HomeViewModel::class.java)
_binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.exercise.text="This is an exceptionally hardcoded string"
binding.btnNewExercise.setOnClickListener {
Toast.makeText(view.context, "New exercise will be generated", Toast.LENGTH_SHORT).show()
println("Generated a new exercise")
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
You need to return the view you made in the OnCreateView .

viewBinding not making any changes inside fragment

My Goal
I am trying to access the widget that was created inside my fragment using viewBinding.
What I have done / Info about my app
The language I am using is kotlin.
I have already added the code below into gradle:
buildFeatures{
dataBinding = true
viewBinding = true
}
I have tested binding.aTextView.setText("Code working.") inside my main activity and it works.
What's the problem
I have tested the setText code inside activity and it works. The problem right now is the same code when I move into the fragment it wouldn't work. And I am sure that the code has been executed as I putted a toast above it and the toast executed successfully which mean it should have at least reached that point before but not sure due to what reason there wasn't any changes.
My mainActivity Code:
class MainProgramActivity : AppCompatActivity() {
lateinit var binding: ActivityMainProgramBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainProgramBinding.inflate(layoutInflater)
setContentView(binding.root)
replaceFragment(FragmentMainPage())
}
private fun replaceFragment(fragment: Fragment){
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.fragmentContainerView,fragment)
fragmentTransaction.commit()
}
}
My fragment code:
class FragmentMainPage : Fragment(R.layout.fragment_main_page) {
lateinit var binding: FragmentMainPageBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
Toast.makeText(getActivity(),"Text!",Toast.LENGTH_SHORT).show();
binding = FragmentMainPageBinding.inflate(layoutInflater)
binding.aTextView.setText("Code working") //<-- I want this code to make changes towards the textView
return super.onCreateView(inflater, container, savedInstanceState)
}
}
The aTextView itself is empty at the beginning, the expected result will be the aTextView to show "Code working".
I see two problems with your code. First, exactly what Michael pointed out. You're returning the super method when you should be returning the View you just created (binding.root). Second, you're currenly leaking your fragment. When you viewbind a fragment, you are supposed to set the variable to null in onDestroyView(), as per defined in the documentation.
class FragmentMainPage : Fragment(R.layout.fragment_main_page) {
private var _binding: FragmentMainPageBinding? = null
private val binding get() = _binding!! // non-null variable in order to avoid having safe calls everywhere
// create the view through binding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentMainPageBinding.inflate(layoutInflater, container, false)
return binding.root
}
// view already created, do whatever with it
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.aTextView.setText("Code working")
}
// clear the binding in order to avoid memory leaks
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}

How to get EditText value from xml in fragment?

What I've tried so far:
getString(R.id.editBrand) => this returns false (R.id.editBrand returns a long number)
view.findViewById(R.id.editBrand) => runs to nullreference
Any help would be vm appreciated, thank you!
My whole fragment:
class CreateFragment : Fragment() {
#SuppressLint("ResourceType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val binding = DataBindingUtil.inflate<FragmentCreateBinding>(inflater,
R.layout.fragment_create,container,false)
val application = requireNotNull(this.activity).application
val dataSource = CarDatabase.getInstance(application).carDatabaseDao
val viewModelFactory = CarViewModelFactory(dataSource, application)
val carViewmodel =
ViewModelProvider(
this, viewModelFactory).get(CarViewmodel::class.java)
val adapter = CarAdapter()
binding.submitButton.setOnClickListener { view : View ->
view.findNavController().navigate(R.id.action_createFragment_to_readFragment)
carViewmodel.onCreated(12, view.findViewById<EditText>(R.id.editBrand).editBrand.toString(), "blue")
}
binding.setLifecycleOwner(this)
return binding.root
}
}
Use
binding.editBrand.text.toString()
Since binding is the reference to your layout here.
If you use view.findViewById<EditText>, view refers to the submitButton and calling findViewById on it will look for child views.
getString() take a string resource as a parameter and not a view resource.

How to speedup when change fragment in Android

WHY NOT ANY PEOPLE HELP TO ME???
In my application I used BottomNavBar and NavigationGraph for show some fragments!
In one of my fragments I have many views (fragment layout has 1069 lines xml codes) and when select this fragment from BottomNavBar, after some second show me this fragment.
In the other words show me this fragment with delay!
Fragment codes:
class HomeDashboardFragment : Fragment(), HomeDashboardContracts.View {
#NonNull
private var pageTitle: TextView? = null
#NonNull
private var menuIcon: TextView? = null
private lateinit var token: String
private lateinit var presenter: HomeDashboardPresenterImpl
private var giftExpireSplit: List<String> = emptyList()
private var giftExpireDate: List<String> = emptyList()
private var timeUtils: TimeUtils? = null
#NonNull
private var disposable: Disposable? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home_dashboard, container, false)
}
#SuppressLint("WrongConstant")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Initialize
presenter = HomeDashboardPresenterImpl(requireContext(), this)
//Initialize views from activity
activity?.let { itActivity ->
pageTitle = itActivity.findViewById(R.id.toolbarMain_title)
menuIcon = itActivity.findViewById(R.id.toolbarMain_menuIcon)
//Set title
pageTitle?.let { itTitle ->
itTitle.text = getString(R.string.menuHomeDashboard)
}
//Open menu
menuIcon?.let { itMenu ->
itMenu.setOnClickListener {
itActivity.findViewById<AwesomeDrawerLayout>(R.id.homePage_drawerLayout).openDrawer(Gravity.END)
}
}
//Get token
token = GoodPrefs.getInstance().getString(PrefsKey.USER_JWT_TOKEN.name, "")
//User registered
if (GoodPrefs.getInstance().isKeyExists(PrefsKey.USER_JWT_TOKEN.name)) {
menuIcon?.visibility = View.VISIBLE
}
//Set layout
presenter.checkRegisterUser(token)
//Load profile data
if (!isEmptyString(token)) {
presenter.getProfile(token, USER_NOTIF_ID)
}
}
}
MainActivity codes for set fragments into BottomNavBar with NavigationGraph :
private fun setupNavigation() {
val navController = Navigation.findNavController(this, R.id.homePage_fragmentNavHost)
NavigationUI.setupWithNavController(homePage_bottomNavBar, navController)
}
override fun onSupportNavigateUp() = Navigation.findNavController(this, R.id.homePage_fragmentNavHost).navigateUp()
How can i fix this issue?
You can add a layout dummy consisting of a single viewGroup. Then in the onViewCreated method inflate the real layout. For example:
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
inflater.inflate(R.layout.layout_dummy, container, false);
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Handler().post {
val layout = flContainer
val child = layoutInflater.inflate(R.layout.fragment_real, null)
layout.removeAllViews()
layout.addView(child)
setupToolbar()
setupWebView()
}
}
layout_dummy.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
android:id="#+id/flContainer"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
You issue is almost assuredly caused by your massive XML file. Loading all of those views takes time. You have A LOT of nesting which slows things down.
You have to optimize your layout. Remove things you don't need. Replace as many nested LinearLayouts as you can with ConstraintLayout. Maybe use a RecyclerView if this is intended to be a long, scrolling view.
Hope that helps.

Categories

Resources