Read text file via HTTP

0

I'm creating an Android app with Android Studio and am having trouble reading a text file that is hosted on the Internet. Whenever I try to execute the checkVersion () method it returns the following error:

Themessageisemptybecausenet.getMessage()isreturningnull

iPoema.java

publicintgetVersion(){intversao=0;Stringlinha="0";
    BufferedReader in = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        URI website = new URI("http://www.xadees.xpg.com.br/iPoema.txt");
        request.setURI(website);
        HttpResponse response = httpclient.execute(request);
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String sb;
        while ((sb = in.readLine()) != null) {
            linha += sb;
        }
        in.close();
        versao = Integer.parseInt(linha);
    } catch (NetworkOnMainThreadException net) {
        showMessage(net.getClass().getName(), net.getMessage());
    } catch (IOException io) {
        showMessage(io.getClass().getName(), io.getMessage());
    } catch (URISyntaxException use) {
        showMessage(use.getClass().getName(), use.getMessage());
    }
    return versao;
}
    
asked by anonymous 09.03.2014 / 02:01

1 answer

3

Network operations on Android must be asynchronous, ie they can not be run on the main thread so as not to risk freezing the user's screen during the operation. Use AsyncTask to run your code outside of the main thread.

Here's the simplest example:

AsyncTask<Void, Void, String> MinhaTask = new AsyncTask<Void, Void, String>(){
    @Override
    protected String doInBackground(Void... params) {
        //Qualquer código aqui é executado fora da thread principal (Views não podem ser atualizadas)
        return "qualquer coisa";
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        //Após o return do método doInBackground, qualquer código aqui estará novamente na main thread (Views podem ser atualizadas)
    }
};

MinhaTask.execute();
    
09.03.2014 / 02:10