回收站视图 - 在空对象引用上

Posted

技术标签:

【中文标题】回收站视图 - 在空对象引用上【英文标题】:Recycler view - on a null object reference 【发布时间】:2021-07-12 21:48:31 【问题描述】:

我有底部工作表视图和回收站视图。它是用 Kotlin 编写的。我正在尝试显示 cmets 列表。尝试显示底部工作表并应用回收站视图数据时出现空指针异常。我的错误是 - 尝试在空对象引用上调用虚拟方法 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)'。 其他答案没有帮助。这是我的片段 -

class AudioFragment : Fragment(R.layout.fragment_audio) 

    @Inject
    lateinit var glide: RequestManager

    lateinit var bottomSheetDialog: BottomSheetDialog
    lateinit var bottomSheetView: View

    @Inject
    lateinit var commentAdapter: CommentAdapter

    private lateinit var mainViewModel: MainViewModel
    private val audioViewModel: AudioViewModel by viewModels()

    private var curPlayingAudio: Audio? = null

    private var playbackState: PlaybackStateCompat? = null

    private var shouldUpdateSeekbar = true

    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)

        bottomSheetDialog = BottomSheetDialog(requireContext(), R.style.BottomSheetDialogTheme)

        bottomSheetView = LayoutInflater.from(requireContext()).inflate(R.layout.bottom_sheet_comment, null)
        bottomSheetDialog.setContentView(bottomSheetView)
    

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) 
        super.onViewCreated(view, savedInstanceState)
        mainViewModel = ViewModelProvider(requireActivity()).get(MainViewModel::class.java)
        subscribeToObservers()

        ivPlayPauseDetail.setOnClickListener 
            curPlayingAudio?.let 
                mainViewModel.playOrToggleAudio(it, true)
            
        

        arrowBack.setOnClickListener 
            navHostFragment.findNavController().navigate(
                    R.id.globalActionFromAudioFragmentToHome
            )
        

        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener 
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) 
                if(fromUser) 
                    setCurPlayerTimeToTextView(progress.toLong())
                
            

            override fun onStartTrackingTouch(seekBar: SeekBar?) 
                shouldUpdateSeekbar = false
            

            override fun onStopTrackingTouch(seekBar: SeekBar?) 
                seekBar?.let 
                    mainViewModel.seekTo(it.progress.toLong())
                    shouldUpdateSeekbar = true
                
            
        )

        ivSkipPrevious.setOnClickListener 
            mainViewModel.skipToPreviousAudio()
        

        ivSkip.setOnClickListener 
            mainViewModel.skipToNextAudio()
        

        commentOpen.setOnClickListener 
            bottomSheetDialog.show()

            rvAllComments.apply 
                adapter = commentAdapter
                layoutManager = LinearLayoutManager(requireContext())
            
            curPlayingAudio?._id?.let  it1 ->
                RetrofitService().getComments(it1).enqueue(object: Callback<List<Comment>> 
                    override fun onFailure(call: Call<List<Comment>>, t: Throwable) 
                        Log.d("err", "$t.message")
                        Toast.makeText(requireContext(), t.message, Toast.LENGTH_LONG).show()
                    

                    override fun onResponse(call: Call<List<Comment>>, response: Response<List<Comment>>) 
                        allCommentsProgressBar.visibility = INVISIBLE
                        response.body()?.let  res ->
                            commentAdapter.comments = res
                        
                    
                )
            
        
    

    private fun updateTitleAndAudioImage(audio: Audio) 
        val title = "$audio.title"
        val writer = "$audio.writer.name"
        tvAudioName.text = title
        tvAudioWriter.text = writer
        glide.load(audio.writer.image).into(ivAudioImage)
    

    private fun subscribeToObservers() 
        mainViewModel.mediaItems.observe(viewLifecycleOwner) 
            it.let  result ->
                when(result.status) 
                    SUCCESS -> 
                        result.data?.let  audios ->
                            if(curPlayingAudio == null && audios.isNotEmpty()) 
                                curPlayingAudio = audios[0]
                                updateTitleAndAudioImage(audios[0])
                            
                        
                    
                    else -> Unit
                
            
        
        mainViewModel.curPlayingAudio.observe(viewLifecycleOwner) 
            if(it == null) return@observe
            curPlayingAudio = it.toAudio()
            updateTitleAndAudioImage(curPlayingAudio!!)
        
        mainViewModel.playbackState.observe(viewLifecycleOwner) 
            playbackState = it
            ivPlayPauseDetail.setImageResource(
                if(playbackState?.isPlaying == true) R.drawable.ic_pause else R.drawable.ic_play_arrow
            )
            seekBar.progress = it?.position?.toInt() ?: 0
        
        audioViewModel.curPlayerPosition.observe(viewLifecycleOwner) 
            if(shouldUpdateSeekbar) 
                seekBar.progress = it.toInt()
                setCurPlayerTimeToTextView(it)
            
        
        audioViewModel.curAudioDuration.observe(viewLifecycleOwner) 
            seekBar.max = it.toInt()
            val dateFormat = SimpleDateFormat("mm:ss", Locale.getDefault())
            tvAudioDuration.text = dateFormat.format(it)
        
    

    private fun setCurPlayerTimeToTextView(ms: Long) 
        val dateFormat = SimpleDateFormat("mm:ss", Locale.getDefault())
        tvCurTime.text = dateFormat.format(ms)
    

这是我的底部工作表视图 -

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/bottomSheet"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    android:background="@drawable/bottom_sheet_background"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <TextView
        android:id="@+id/commentsHeader"
        android:layout_
        android:layout_
        android:text="Comments"
        android:padding="10dp"
        android:gravity="center"
        android:textStyle="bold"
        android:textSize="18sp"/>

    <View
        android:id="@+id/commentsHeaderHr"
        android:layout_
        android:layout_
        android:background="#7A7A7A"
        android:layout_marginBottom="10dp" />

    <ProgressBar
        android:id="@+id/allCommentsProgressBar"
        android:layout_
        android:layout_
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvAllComments"
        android:layout_
        android:layout_
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>

【问题讨论】:

rvAllComments 在哪里声明?还是您使用的是 Kotlin 合成绑定? 这能回答你的问题吗? What is a NullPointerException, and how do I fix it? 【参考方案1】:

试试

bottomsheetview.rvAllComments.apply

【讨论】:

是的,这有帮助!

以上是关于回收站视图 - 在空对象引用上的主要内容,如果未能解决你的问题,请参考以下文章

自定义视图上的数据绑定“无法在空引用对象上引用 .setTag”

setAdapter 上的空对象引用错误

无法从列表视图中获取项目位置:尝试在空对象引用上调用虚拟方法...

显示来自sqlite数据库的数据时“尝试在空对象引用上调用虚拟方法”[重复]

android.content.res.Resources.getConfiguration()' 在空对象引用上

NullPointerException:尝试在空对象引用上调用虚拟方法 findViewById(int)'