3

I have some Java knowledge but its very fresh. Yesterday I started learning some Java for Android and encountered a problem. Specifically I want to retrieve a decimal number from a website API for some in-app calculations. I have code that works perfectly in normal Java, but when I insert it into Android Studio it compiles but the app crashes at start. Any help would be appreciated.

Here's the number retrieval code :

        URL url = new URL("api.example.com");

    URLConnection con = url.openConnection();
    InputStream is =con.getInputStream();

    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    String line = null;
    int cont=0;

    while ((line = br.readLine()) != null) {
        cont++;
        if(cont==28){
            Dol = Double.parseDouble(line.substring(25, 31));

        }
    }
8
  • 1
    Are you opening the url connection on the main thread? Commented Jun 14, 2015 at 15:01
  • 3
    Androids prevents any networking code to be run in the main thread. stackoverflow.com/questions/6343166/… Commented Jun 14, 2015 at 15:07
  • 1
    Don't do network operation on main thread . Use Asynctask instead for network operations Commented Jun 14, 2015 at 15:07
  • 1
    @Nilesh thanks man! why is Asynctask better than network operations and sorry for bothering. Thanks! Commented Jun 14, 2015 at 15:13
  • 2
    AsynchTask is a convenience class for doing processing (like networking) in a second thread, and pushing the result back to the main thread. Commented Jun 14, 2015 at 15:17

1 Answer 1

1

anything related to networking tasks you need to perform in AsyncTask only
try it in AsyncTask

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.