1

我需要从 github txt 文件中读取文件中的数据,我尝试了很多但没有成功。我已经包括

<uses-permission android:name=android.permission.INTERNET/>
<uses-permission android:name=android.permission.WRITE_EXTERNAL_STORAGE/>

在我的清单文件中。

我使用此链接接收数据:https ://raw.githubusercontent.com/Tanay360/Sample/main/hello.txt

这是我的 onCreate 方法:

override fun onCreate(savedInstanceState : Bundle?){
 super.onCreate(savedInstanceState)
 setContentView(R.layout.activity_main)
 val thread : Thread = Thread{
        read()
 }
 val button : Button = findViewById(R.id.b1)
 b1.setOnClickListener{
     thread.start()
 }}

这是我的阅读方法:

fun read(){
 val url = URL("https://raw.githubusercontent.com/Tanay360/Sample/main/hello.txt")
 val sc = Scanner(url.openStream())
 var str = ""
 while(sc.hasNextLine()){
       str+=sc.nextLine()+"\n"
  }
 Log.d(TAG, "read : $str")
 val tv : TextView = findViewById(R.id.normalTextView)
 tv.text = str}

每当我运行该应用程序时,都不会引发编译时错误,并且单击按钮时什么也没有发生!

请帮我...

谢谢!

4

1 回答 1

0

什么都没发生你的意思是即使你的日志没有被打印出来?此外,因为您在后台线程上,您无法访问 UI 元素,例如 textView。此外,在此线程中引发的异常不会导致崩溃,但您的线程会停止。放一个 try/catch 并读取堆栈跟踪(我 100% 确定会抛出异常)但我强烈建议在这种情况下使用改造而不是手动处理线程。在@GET 中使用文件的url,它可以工作(我以前做过)

于 2021-03-21T03:28:02.493 回答