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

当我尝试以隐式意图打开链接时出现此错误。我正在通过ImageView 上的适配器类调用活动openUrl(url: String)Settings.ktSettingsAdapter.ktsetOnClcikListener

SettingsAdapter.kt

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

Settings.kt活动

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

1 回答 1

0

您正在遵循错误的方法。您可以通过两种方式做到这一点。

  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. 您可以在适配器中创建回调并在您的活动中实现

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

    在您的活动中,实现此侦听器

     Settings implements SettingsAdapter.OnSettingsListener {
    
     @Override
     public void onSettingClick(String url) {
      openUrl(url)
    }
    }
    
于 2020-10-28T05:51:37.937 回答