-1

i'm trying to fix the NetworkOnMainThreadException, here is my class located in a library

class CoinProvider(private val context: Context, isTestnet: Boolean) {


     val result = URL("http://mylink.com/file.json").readText()
     val result1 = URL("http://mylink.com/file1.json").readText()
    
    private val filename: String = if (!isTestnet) (result) else (result1)

    fun defaultCoins(): CoinResponse {
        return CoinResponse.parseFile(context, filename)
    }
}

when i try to add this to my class

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 

i got this " expecting member declaration "

the code above can be added to the MainActivity of the project but it doesn't do anything because i want to fix the NetworkOnMainThreadException on the library not in the project.

how can i fix the issue in this kotlin library?

  • 1
    Does this answer your question? [How to fix 'android.os.NetworkOnMainThreadException'?](https://stackoverflow.com/questions/6343166/how-to-fix-android-os-networkonmainthreadexception) – a_local_nobody Apr 23 '21 at 05:03

1 Answers1

0

Oh No. Request network and query database always not calling in Ui thread because it blocks the UI thread (Ui thread always redraws with 16ms time).

Solution thread:

   Thread(Runnable {
         ...// Something Call 
            }).

This way you need to either implement a callback to handle the outgoing data, or use Handler

Solution RxJava:

     Single.fromCallable {
        try {
          /// Something Doing
        } catch (e: IOException) {
            false
        }
    }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())

With RxJava you can easily work with threads and return results in Mainthread, all you need to do is just Observer the output data.

Solution Kotlin-Coroutines

suspend func getJSON(){
//Something Doing....
}

My understanding will probably help you to solve the problem.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
LuongXuanNam
  • 67
  • 1
  • 4
  • Thanks, it works. but now i got another error " Unable to create application java.io.FileNotFoundException " i can see the the json content in the Logcat means that the url is readable now, but seems like can't create the file 'java.lang.RuntimeException: Unable to create application .core.App: java.io.FileNotFoundException: { "version": 3, "coins": [ { "title": "Next Gen Finance", "code": "NXGN", "decimal": 18, "type": "bep20", "address": "0x260A4A7849D65E7d4aEE31Fcf5c917c5a977e985" },' – Kamal Cherkaoui Apr 23 '21 at 03:21
  • I think you get data from json and create new File. – LuongXuanNam Apr 24 '21 at 06:35