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));

        }
    }
T3KBAU5
  • 1,861
  • 20
  • 26
guilloh
  • 31
  • 3
  • 1
    Are you opening the url connection on the main thread? – M4rtini Jun 14 '15 at 15:01
  • @M4rtini yes since its a small learning app, im doing everything there. All tho its in an independent methd – guilloh Jun 14 '15 at 15:06
  • 3
    Androids prevents any networking code to be run in the main thread. http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception – M4rtini Jun 14 '15 at 15:07
  • 1
    Don't do network operation on main thread . Use `Asynctask` instead for network operations – N J Jun 14 '15 at 15:07
  • @M4rtini OHH! thats good to know, thanks guys. so if i implement a new class with that same code it should work? – guilloh Jun 14 '15 at 15:12
  • 1
    @Nilesh thanks man! why is Asynctask better than network operations and sorry for bothering. Thanks! – guilloh Jun 14 '15 at 15:13
  • 1
    see this link http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html – N J Jun 14 '15 at 15:14
  • 2
    [AsynchTask](http://developer.android.com/reference/android/os/AsyncTask.html) is a convenience class for doing processing (like networking) in a second thread, and pushing the result back to the main thread. – M4rtini Jun 14 '15 at 15:17
  • 1
    @Nilesh much appreciated! thanks for your help – guilloh Jun 14 '15 at 15:19
  • 1
    @M4rtini much appreciated! thanks for your help – guilloh Jun 14 '15 at 15:20

1 Answers1

1

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

pavaniiitn
  • 311
  • 1
  • 4
  • 18