隐式意图 - java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法

Implicit Intent - java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference

当我尝试以隐含意图打开 link 时出现此错误。我通过 ImageView 上的 setOnClcikListener 从它的适配器 class SettingsAdapter.ktSettings.kt activity 中调用 openUrl(url: String)

SettingsAdapter.kt Class

private val settings = Settings()
youtubeLink.setOnClickListener {
            val url = "https://www.youtube.com/watch?v=i-0FtaAadeM"
            settings.openUrl(url)
        }

Settings.kt Activity

fun openUrl(url: String) {
        val intent = Intent(Intent.ACTION_VIEW,Uri.parse(url))
        startActivity(intent)
    }

您采用了错误的方法。您可以通过两种方式执行此操作。

  1. 您可以直接在您的适配器中调用代码片段

      youtubeLink.setOnClickListener {
         val url = "https://www.youtube.com/watch?v=i-0FtaAadeM"
         val intent = Intent(Intent.ACTION_VIEW,Uri.parse(url))
         context.startActivity(intent)
     }
    
  2. 您可以在适配器中创建回调并在 activity

    中实施
     private OnSettingsListener listener;
    
    void setOnSttingListener(OnSettingsListener listener){
      this.listener = listener;
    }
    
    youtubeLink.setOnClickListener {
         val url = "https://www.youtube.com/watch?v=i-0FtaAadeM"
         listener.onSettingClick(url);
     }
    
    interface OnSettingsListener {  
      void onSettingClick(String url);     
    }
    

    在您的 activity 中,实施此侦听器

     Settings implements SettingsAdapter.OnSettingsListener {
    
     @Override
     public void onSettingClick(String url) {
      openUrl(url)
    }
    }