0

I have a valid URL, but I cannot parse its content to a string like I do in normal Java. I am pretty new to android. Mostly I convert my normal Java code to android Java and this code works perfectly in Java NetBeans but not in Android Studio.

P.S.There are no errors or even warnings given by compiler / during run-time. It just doesn't work and when I check the String length for "weather" its 0.

String weather="";
            try {
                weather = new Scanner(new URL("http://api.openweathermap.org/data/2.5/forecast?lat="+lat+"&lon="+longi+"&units=metric&mode=xml").openStream(), "UTF-8").useDelimiter("\\A").next();
            } catch (Exception e) {

            }
Scott Barta
  • 79,344
  • 24
  • 180
  • 163
  • 1
    _How_ doesn't it work in Android studio? – Sotirios Delimanolis Mar 08 '14 at 21:45
  • **Never swallow exceptions.** At least do `e.printStackTrace()` inside the `catch`. – Sotirios Delimanolis Mar 08 '14 at 21:48
  • The code does not parse the contents of the URL to the variable "weather". When I check the length for "weather" its 0 –  Mar 08 '14 at 21:48
  • I wrote the e.printStackTrace(); and the LogCat threw a bunch of warnings that were not there before. This is what it shows: 03-08 22:51:50.242 4659-4659/com.pavin.rainguard W/System.err﹕ android.os.NetworkOnMainThreadException 03-08 22:51:50.285 4659-4659/com.pavin.rainguard W/System.err﹕ at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133) –  Mar 08 '14 at 21:54
  • Now that should be easy to look up. – Sotirios Delimanolis Mar 08 '14 at 21:54
  • possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – Sotirios Delimanolis Mar 08 '14 at 21:55

1 Answers1

0

You can use Jsoup. Look at its "cookbook" for tutorials and more information but here is a simple example:

    String WeatherString; //Declare earlier in code - Before "onCreate" method.
@Override
        protected Void doInBackground(Void... unused) {
            org.jsoup.nodes.Document doc = null;
            try {
                doc = Jsoup.connect("http://api.openweathermap.org/data/2.5/forecast").get();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace(); 
        }

            WeatherString = doc.select("dl#weather dt + dd + dt + dd ").first().text(); //Input here where the xml code is that you want to parse to a string

            return null;        
        }

This code is inside of an AsyncTask. Hope this helps. And, again, refer to the "cookbook" on the Jsoup website for more info.

ninge
  • 1,592
  • 1
  • 20
  • 40