Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

kotlin

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()  }}
like image 488
Ramesh Avatar asked Sep 26 '17 06:09

Ramesh


2 Answers

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
    }

}
like image 70
Kiran Benny Joseph Avatar answered Sep 21 '22 11:09

Kiran Benny Joseph


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:

  1. Do null check with safe call - ?., Eg. nullableVariable?.method()
  2. Use non-null object using ?.let{ }, Eg. nullableVariable?.let { it.method() }
  3. Supplying a backup value for the nullable variable using elvis operator - ?:, Eg. nullableVariable ?: <backupValue>.

Read more about Null Safety in Kotlin.

like image 37
krishh Avatar answered Sep 22 '22 11:09

krishh