How can I read data from a public raw text file from github in my android app?

Viewed 291

I need to read data from a file from a github txt file, I tried a lot but was unsuccessful. I had included

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

in my manifest file.

I used this link for receiving data: https://raw.githubusercontent.com/Tanay360/Sample/main/hello.txt

This was my onCreate method :

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

This is my read method :

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}

Whenever, I run the app, no compile-time errors are thrown, and on clicking the button nothing happens!

Please help me...

Thank you!

1 Answers

By nothing happens you mean even your log is not printed? Also because you're on a background thread you cannot access UI elements such as your textView. Also exceptions thrown in this thread won't cause a crash but your thread would stop. Put a try/catch and read the stack trace (I'm a 100% sure that a exception will be thrown) But I highly recommend to use retrofit instead of manually dealing with threads in this case. Use the file's url inside @GET and it works (I've done it before)

Related