1

I want to pull the text from this URL: http://www.weather.noaa.gov/pub/data/observations/metar/stations/KORD.txt, save it to a string, then print that string in a TextView.

I am a complete newbie to android, what is the most efficient way to do this?

Amrit A
  • 11
  • 1
  • 2
  • Reference [this link](https://stackoverflow.com/questions/14418021/get-text-from-web-page-to-string) ReadWebpageAsyncTask will do the trick. – Toe Nov 25 '17 at 17:05

2 Answers2

0

Reference this link.

DownloadWebPageTask class will do the trick and don't forget to add

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

to AndroidManifest.xml to permit the use of the Internet.

Toe
  • 564
  • 4
  • 11
0

URL is invalid, or my country is blocked

put this BEFORE onCreate():

private TextView outtext;
private String HTML;

And add lines between comments into onCreate like this:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /*FROM HERE*/
        outtext= (TextView) findViewById(R.id.textview1); //change id if needed!!!

            try { 
            getHTML();
        } catch (Exception e) {
            e.printStackTrace();
        }       
        outtext.setText("" + HTML);
        /*TO HERE*/
    }

now this is the method you will use to download content:

 private void getHTML() throws throws ClientProtocolException, IOException 

        {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpGet httpGet = new HttpGet("http://www.weather.noaa.gov/pub/data/observations/metar/stations/KORD.txt"); //URL!
            HttpResponse response = httpClient.execute(httpGet, localContext);
            String result = "";

            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            String line = null;
            while ((line = reader.readLine()) != null) {
                result += line + "\n";
                HTML = result;
            }

        }

You also need to set permission in AndroidManifest.xml to use internet:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Also this is NOT the best way to do this. When you open your app it will freeze until it loads from website, so you should use AsyncTask to help you out there.

Bojan Kogoj
  • 5,321
  • 3
  • 35
  • 57