0

I'm using openstreetmap I can only see the inputstream inside the while loop

Here's my code inside the initialize of the javafx Controller:

try {
    URL myurl;
    myurl = new URL("https://nominatim.openstreetmap.org/search?q=The+White+House,+Washington+DC&format=json&addressdetails=1");
    URLConnection yc = myurl.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null)
                response.append(inputLine);

} catch (IOException ex) {
    Logger.getLogger(WeatherUpdateController.class.getName()).log(Level.SEVERE, null, ex);
}

I am trying to get the StringBuffer inside a string variable so I can search it.

MPhil
  • 861
  • 1
  • 12
  • 23
Megumin
  • 131
  • 1
  • 11
  • `final String asString = response.toString();` – BeUndead Feb 26 '19 at 15:36
  • @user2478398 the final string only contains a value inside the while loop and i can't get it outside of it – Megumin Feb 26 '19 at 16:10
  • Make the `StringBuffer` global and try `StringBuilder`. – Sedrick Feb 26 '19 at 16:21
  • That can't be correct. `StringBuffer` won't clear itself just because an implied scope ends, and `String`s are immutable and won't _ever_ clear themselves. Are you sure you've not just declared your `String` in the _scope_ of the `while` block and just can't access it from outside? If that's the case, just close the while block and _then_ to `response.toString()`. – BeUndead Feb 26 '19 at 16:22
  • https://stackoverflow.com/questions/4646577/global-variables-in-java – Sedrick Feb 26 '19 at 16:22

1 Answers1

0

Use StringBuffer#toString() like so:

String str = response.toString();

Please note that you can use StringBuilder instead if you don't need synchronization. Source here

devgianlu
  • 1,484
  • 10
  • 21