简体   繁体   English

Null 指针异常在 Recycler 视图中以文本时钟为项目

[英]Null pointer exception on Recycler View with Text Clock as Item

I am trying to build Recycler View where each item consist of TextClock and TextView.我正在尝试构建 Recycler View,其中每个项目由 TextClock 和 TextView 组成。

The data for item view will be input as ArrayList when initialize the Recycler View Adapter.初始化 Recycler View Adapter 时,item view 的数据将输入为 ArrayList。

I found that if the input ArrayList size only one the view will be built successfully.我发现如果输入 ArrayList 大小只有 1 则视图将构建成功。 As this screenshot shown https://i.ibb.co/MskHGL7/Webp-net-resizeimage.png如此屏幕截图所示https://i.ibb.co/MskHGL7/Webp-net-resizeimage.png

When I increase the ArrayList data to 2, it will create error as I copied bellow.当我将 ArrayList 数据增加到 2 时,它会在我复制下面产生错误。

class ClockFragment : Fragment() {

    val sharedPref = activity?.getSharedPreferences(
        Constants().PREF_KEY_MANUAL_CLOCK,
        Context.MODE_PRIVATE
    )
    val isAnalogshow = sharedPref?.getBoolean(Constants().PREF_KEY_MANUAL_CLOCK, false)

    lateinit var view: ViewGroup

    private lateinit var recyclerView: RecyclerView
    private lateinit var viewAdapter: ClockRecyclerViewAdapter
    private lateinit var viewManager: RecyclerView.LayoutManager


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        view = inflater.inflate(R.layout.fragment_clock, container, false) as ViewGroup

        viewManager = LinearLayoutManager(this.context)
        viewAdapter = ClockRecyclerViewAdapter(getData())

        recyclerView = view.findViewById<RecyclerView>(R.id.clock_rv).apply {
            setHasFixedSize(true)
            layoutManager = viewManager
            adapter = viewAdapter
        }

        view.clock_switch.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                sharedPref?.edit {
                    putBoolean(Constants().PREF_KEY_MANUAL_CLOCK, true)
                    commit()
                }
            } else {
                sharedPref?.edit {
                    putBoolean(Constants().PREF_KEY_MANUAL_CLOCK, false)
                    commit()
                }
            }
        }
        return view
    }

    override fun onResume() {
        super.onResume()
        getData()
    }


    fun getData(): ArrayList<Clock> {
        val clockList = arrayListOf<Clock>()
        clockList.add(Clock(Calendar.getInstance()))
        clockList.add(Clock(Calendar.getInstance()))
        return clockList
    }
}

RecyclerView Adapter RecyclerView 适配器

class ClockRecyclerViewAdapter(private var clockList: ArrayList<Clock>?) : RecyclerView.Adapter<ClockRecyclerViewAdapter.ClockViewHolder>() {

    class ClockViewHolder(val itemview: View) : RecyclerView.ViewHolder(itemview)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ClockViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_clock, parent, false)
        return ClockViewHolder(view)
    }

    override fun onBindViewHolder(holder: ClockViewHolder, position: Int) {
        val formattedDate = SimpleDateFormat("EEEE, d MMMM")
        var calendar = clockList!!.get(position)!!.timezoneCalendar
        holder.itemview.date_tv.text = formattedDate.format(calendar.time)
    }

    override fun getItemCount(): Int = clockList?.size ?: 0

    fun setData(data: ArrayList<Clock>) {
        clockList = data
        notifyDataSetChanged()
    }
}

item layout:项目布局:

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">

<FrameLayout
    android:id="@+id/clock_frame"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <TextClock
        android:id="@+id/digital_clock_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:format12Hour="hh:mm:ss a"
        android:textSize="56sp"/>

    <com.arbelkilani.clock.Clock
        android:id="@+id/analog_clock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="24dp"
        android:visibility="gone"
        app:center_inner_color="#000000"
        app:clock_value_disposition="regular"
        app:clock_value_step="full"
        app:show_center="true"
        app:show_hours_values="true"
        app:show_seconds_needle="true" />
</FrameLayout>


<TextView
    android:id="@+id/date_tv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:textAppearance="?android:textAppearanceLarge"
    app:layout_constraintEnd_toEndOf="@+id/clock_frame"
    app:layout_constraintStart_toStartOf="@+id/clock_frame"
    app:layout_constraintTop_toBottomOf="@+id/clock_frame"/>

Logcat Error Message: Logcat 错误消息:

Process: com.andreasgift.myclock, PID: 17909
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.os.Handler.postAtTime(java.lang.Runnable, long)' on a null object reference
        at android.widget.TextClock$2.run(TextClock.java:191)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

Change the android:layout_height="match_parent" to android:layout_height="wrap_content" inside the item_layout.xml and it should do the job.将 item_layout.xml 中的android:layout_height="match_parent"更改为android android:layout_height="wrap_content" ,它应该可以完成这项工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM