【问题标题】:Null pointer exception on Recycler View with Text Clock as Item使用文本时钟作为项目的回收器视图上的空指针异常
【发布时间】:2019-10-08 21:38:17
【问题描述】:

我正在尝试构建 Recycler View,其中每个项目由 TextClock 和 TextView 组成。

在初始化Recycler View Adapter时,item view的数据会以ArrayList的形式输入。

我发现如果输入的 ArrayList 大小只有一个,则视图将成功构建。如此屏幕截图所示 https://i.ibb.co/MskHGL7/Webp-net-resizeimage.png

当我将 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 适配器

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()
    }
}

项目布局:

<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 错误信息:

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)

【问题讨论】:

    标签: android kotlin android-recyclerview


    【解决方案1】:

    item_layout.xml 中的 android:layout_height="match_parent" 更改为 android:layout_height="wrap_content",它应该可以完成这项工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-14
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      相关资源
      最近更新 更多