How to acces view properties from coroutines result

Multi tool use
Multi tool use












0














I am trying to do simple request to backend with coroutines



    uiScope.launch {
try {
result = URL("https://httpbin.org/get").readText()
text.text = result
} catch (error: Error) {
text.text = error.message
} finally {
log(this@MainActivity,result)

}
}


but this exeption is thrown:




android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.




How to solve it?










share|improve this question





























    0














    I am trying to do simple request to backend with coroutines



        uiScope.launch {
    try {
    result = URL("https://httpbin.org/get").readText()
    text.text = result
    } catch (error: Error) {
    text.text = error.message
    } finally {
    log(this@MainActivity,result)

    }
    }


    but this exeption is thrown:




    android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.




    How to solve it?










    share|improve this question



























      0












      0








      0


      0





      I am trying to do simple request to backend with coroutines



          uiScope.launch {
      try {
      result = URL("https://httpbin.org/get").readText()
      text.text = result
      } catch (error: Error) {
      text.text = error.message
      } finally {
      log(this@MainActivity,result)

      }
      }


      but this exeption is thrown:




      android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.




      How to solve it?










      share|improve this question















      I am trying to do simple request to backend with coroutines



          uiScope.launch {
      try {
      result = URL("https://httpbin.org/get").readText()
      text.text = result
      } catch (error: Error) {
      text.text = error.message
      } finally {
      log(this@MainActivity,result)

      }
      }


      but this exeption is thrown:




      android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.




      How to solve it?







      kotlin kotlinx.coroutines






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 12:10









      Marko Topolnik

      145k19196323




      145k19196323










      asked Nov 21 '18 at 8:23









      NurseyitNurseyit

      12




      12
























          2 Answers
          2






          active

          oldest

          votes


















          0














          Your uiScope isn't set up correctly, apparently its dispatcher is not Dispatchers.Main. So the first thing to fix is your implementation of the coroutineContext property, which should be



          override val coroutineContext = Dispatchers.Main + SupervisorJob()


          Once you fix that, your code will be making a blocking call on the UI thread. To make the blocking call on a background thread, but still keep the rest of the coroutine on the UI thread, write



          uiScope.launch {
          try {
          text.text = withContext(Dispatchers.IO) {
          URL("https://httpbin.org/get").readText()
          }
          } catch (e: Exception) {
          text.text = e.message
          } finally {
          log(this@MainActivity, result)
          }
          }





          share|improve this answer























          • again "android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views." thrown
            – Nurseyit
            Nov 21 '18 at 11:52










          • This indicates that you didn't set up uiScope to actually be a UI-based coroutine scope. Its coroutineContext must return Dispatchers.Main + job.
            – Marko Topolnik
            Nov 21 '18 at 11:55










          • but Dispatchers.Main throws: android.os.NetworkOnMainThreadException
            – Nurseyit
            Nov 21 '18 at 12:09










          • It doesn't with the code as in my answer.
            – Marko Topolnik
            Nov 21 '18 at 12:09



















          0














          I found solution. I can not access UI component from another thread, at the same time I can not make internet request on the main thread. So I should chouse one of them. Solution was to use ViewModel components and update it's value which subsequently will chane the UI



              var viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
          viewModel.selected.observe(this, Observer{ users ->

          text.text = users
          })
          uiScope.launch {
          try {
          result = URL("http://jsonplaceholder.typicode.com/posts").readText()
          viewModel.selected.postValue(result)
          } catch (error: Error) {
          viewModel.selected.postValue(error.toString())
          }

          }
          log(this@MainActivity,result)





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53407838%2fhow-to-acces-view-properties-from-coroutines-result%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            Your uiScope isn't set up correctly, apparently its dispatcher is not Dispatchers.Main. So the first thing to fix is your implementation of the coroutineContext property, which should be



            override val coroutineContext = Dispatchers.Main + SupervisorJob()


            Once you fix that, your code will be making a blocking call on the UI thread. To make the blocking call on a background thread, but still keep the rest of the coroutine on the UI thread, write



            uiScope.launch {
            try {
            text.text = withContext(Dispatchers.IO) {
            URL("https://httpbin.org/get").readText()
            }
            } catch (e: Exception) {
            text.text = e.message
            } finally {
            log(this@MainActivity, result)
            }
            }





            share|improve this answer























            • again "android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views." thrown
              – Nurseyit
              Nov 21 '18 at 11:52










            • This indicates that you didn't set up uiScope to actually be a UI-based coroutine scope. Its coroutineContext must return Dispatchers.Main + job.
              – Marko Topolnik
              Nov 21 '18 at 11:55










            • but Dispatchers.Main throws: android.os.NetworkOnMainThreadException
              – Nurseyit
              Nov 21 '18 at 12:09










            • It doesn't with the code as in my answer.
              – Marko Topolnik
              Nov 21 '18 at 12:09
















            0














            Your uiScope isn't set up correctly, apparently its dispatcher is not Dispatchers.Main. So the first thing to fix is your implementation of the coroutineContext property, which should be



            override val coroutineContext = Dispatchers.Main + SupervisorJob()


            Once you fix that, your code will be making a blocking call on the UI thread. To make the blocking call on a background thread, but still keep the rest of the coroutine on the UI thread, write



            uiScope.launch {
            try {
            text.text = withContext(Dispatchers.IO) {
            URL("https://httpbin.org/get").readText()
            }
            } catch (e: Exception) {
            text.text = e.message
            } finally {
            log(this@MainActivity, result)
            }
            }





            share|improve this answer























            • again "android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views." thrown
              – Nurseyit
              Nov 21 '18 at 11:52










            • This indicates that you didn't set up uiScope to actually be a UI-based coroutine scope. Its coroutineContext must return Dispatchers.Main + job.
              – Marko Topolnik
              Nov 21 '18 at 11:55










            • but Dispatchers.Main throws: android.os.NetworkOnMainThreadException
              – Nurseyit
              Nov 21 '18 at 12:09










            • It doesn't with the code as in my answer.
              – Marko Topolnik
              Nov 21 '18 at 12:09














            0












            0








            0






            Your uiScope isn't set up correctly, apparently its dispatcher is not Dispatchers.Main. So the first thing to fix is your implementation of the coroutineContext property, which should be



            override val coroutineContext = Dispatchers.Main + SupervisorJob()


            Once you fix that, your code will be making a blocking call on the UI thread. To make the blocking call on a background thread, but still keep the rest of the coroutine on the UI thread, write



            uiScope.launch {
            try {
            text.text = withContext(Dispatchers.IO) {
            URL("https://httpbin.org/get").readText()
            }
            } catch (e: Exception) {
            text.text = e.message
            } finally {
            log(this@MainActivity, result)
            }
            }





            share|improve this answer














            Your uiScope isn't set up correctly, apparently its dispatcher is not Dispatchers.Main. So the first thing to fix is your implementation of the coroutineContext property, which should be



            override val coroutineContext = Dispatchers.Main + SupervisorJob()


            Once you fix that, your code will be making a blocking call on the UI thread. To make the blocking call on a background thread, but still keep the rest of the coroutine on the UI thread, write



            uiScope.launch {
            try {
            text.text = withContext(Dispatchers.IO) {
            URL("https://httpbin.org/get").readText()
            }
            } catch (e: Exception) {
            text.text = e.message
            } finally {
            log(this@MainActivity, result)
            }
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 21 '18 at 12:46

























            answered Nov 21 '18 at 11:41









            Marko TopolnikMarko Topolnik

            145k19196323




            145k19196323












            • again "android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views." thrown
              – Nurseyit
              Nov 21 '18 at 11:52










            • This indicates that you didn't set up uiScope to actually be a UI-based coroutine scope. Its coroutineContext must return Dispatchers.Main + job.
              – Marko Topolnik
              Nov 21 '18 at 11:55










            • but Dispatchers.Main throws: android.os.NetworkOnMainThreadException
              – Nurseyit
              Nov 21 '18 at 12:09










            • It doesn't with the code as in my answer.
              – Marko Topolnik
              Nov 21 '18 at 12:09


















            • again "android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views." thrown
              – Nurseyit
              Nov 21 '18 at 11:52










            • This indicates that you didn't set up uiScope to actually be a UI-based coroutine scope. Its coroutineContext must return Dispatchers.Main + job.
              – Marko Topolnik
              Nov 21 '18 at 11:55










            • but Dispatchers.Main throws: android.os.NetworkOnMainThreadException
              – Nurseyit
              Nov 21 '18 at 12:09










            • It doesn't with the code as in my answer.
              – Marko Topolnik
              Nov 21 '18 at 12:09
















            again "android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views." thrown
            – Nurseyit
            Nov 21 '18 at 11:52




            again "android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views." thrown
            – Nurseyit
            Nov 21 '18 at 11:52












            This indicates that you didn't set up uiScope to actually be a UI-based coroutine scope. Its coroutineContext must return Dispatchers.Main + job.
            – Marko Topolnik
            Nov 21 '18 at 11:55




            This indicates that you didn't set up uiScope to actually be a UI-based coroutine scope. Its coroutineContext must return Dispatchers.Main + job.
            – Marko Topolnik
            Nov 21 '18 at 11:55












            but Dispatchers.Main throws: android.os.NetworkOnMainThreadException
            – Nurseyit
            Nov 21 '18 at 12:09




            but Dispatchers.Main throws: android.os.NetworkOnMainThreadException
            – Nurseyit
            Nov 21 '18 at 12:09












            It doesn't with the code as in my answer.
            – Marko Topolnik
            Nov 21 '18 at 12:09




            It doesn't with the code as in my answer.
            – Marko Topolnik
            Nov 21 '18 at 12:09













            0














            I found solution. I can not access UI component from another thread, at the same time I can not make internet request on the main thread. So I should chouse one of them. Solution was to use ViewModel components and update it's value which subsequently will chane the UI



                var viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
            viewModel.selected.observe(this, Observer{ users ->

            text.text = users
            })
            uiScope.launch {
            try {
            result = URL("http://jsonplaceholder.typicode.com/posts").readText()
            viewModel.selected.postValue(result)
            } catch (error: Error) {
            viewModel.selected.postValue(error.toString())
            }

            }
            log(this@MainActivity,result)





            share|improve this answer


























              0














              I found solution. I can not access UI component from another thread, at the same time I can not make internet request on the main thread. So I should chouse one of them. Solution was to use ViewModel components and update it's value which subsequently will chane the UI



                  var viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
              viewModel.selected.observe(this, Observer{ users ->

              text.text = users
              })
              uiScope.launch {
              try {
              result = URL("http://jsonplaceholder.typicode.com/posts").readText()
              viewModel.selected.postValue(result)
              } catch (error: Error) {
              viewModel.selected.postValue(error.toString())
              }

              }
              log(this@MainActivity,result)





              share|improve this answer
























                0












                0








                0






                I found solution. I can not access UI component from another thread, at the same time I can not make internet request on the main thread. So I should chouse one of them. Solution was to use ViewModel components and update it's value which subsequently will chane the UI



                    var viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
                viewModel.selected.observe(this, Observer{ users ->

                text.text = users
                })
                uiScope.launch {
                try {
                result = URL("http://jsonplaceholder.typicode.com/posts").readText()
                viewModel.selected.postValue(result)
                } catch (error: Error) {
                viewModel.selected.postValue(error.toString())
                }

                }
                log(this@MainActivity,result)





                share|improve this answer












                I found solution. I can not access UI component from another thread, at the same time I can not make internet request on the main thread. So I should chouse one of them. Solution was to use ViewModel components and update it's value which subsequently will chane the UI



                    var viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
                viewModel.selected.observe(this, Observer{ users ->

                text.text = users
                })
                uiScope.launch {
                try {
                result = URL("http://jsonplaceholder.typicode.com/posts").readText()
                viewModel.selected.postValue(result)
                } catch (error: Error) {
                viewModel.selected.postValue(error.toString())
                }

                }
                log(this@MainActivity,result)






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 21 '18 at 14:54









                NurseyitNurseyit

                12




                12






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53407838%2fhow-to-acces-view-properties-from-coroutines-result%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    I1QSgMlyhTo,6iGGIJpsqaky7OvmhEQ,xvi K 6LHR,XXNb rO1ln H9uwQgKag,Jf,9o7 BIqoXEYW8,TimVztdtc89yeGrY5V3zk41A
                    i1 y9KlI61ewf4lqB eNhPWEUE8hThs8B7x7 3

                    Popular posts from this blog

                    Costa Masnaga

                    Fotorealismo

                    Sidney Franklin