Read text file via HTTP

Asked

Viewed 1,009 times

0

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

android.os.NetworkOnMainThreadException The message is empty because net.getMessage() is returning null

iPoema.java

public int getVersion() {
    int versao = 0;
    String linha = "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;
}
  • Depending on the system used and the HTTP version, you may not be giving the required minimum information (I don’t know Java very well).

1 answer

3

Network operations on Android must be asynchronous, IE, They can not be performed on the main thread not to run the risk of freezing the user screen during operation. Use a Asynctask to run your code outside the main thread (main thread).

Here are the simplest examples:

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();
  • Could you help me put this code in my project? Link: http://pastebin.com/6PmsitYy (cropped code, method used to check version and update application)

  • @iXaDe simply copy all content from getVersion into the doInBackground. The parameter s of onPostExecute will be your version.

  • I tried it here and it worked correctly, BUT it can only be run once per run, and one might want to check the version more than once.

  • But my app will also download an XML for reading the data and display it, so I will use Asynctask for this and the person can keep checking if they have new post, hence the need for it to run more than once. Anything, my Asynctask app update code is here: http://pastebin.com/0X2x2g79

  • @iXaDe What do you mean by só pode ser executado uma única vez por execução? There is no restriction for using Asynctask, you are getting some error message?

  • Yes, but it is not displayed, only the app that closes alone. It performs from downloading the iPoema.xml, but can’t do the reading. Do I need 4 Asynctask? 1 - iPoema.txt; 2 - iPoema.xml; 3 - iPoema.apk; 4 - Leitura do XML

  • Today I wanted to test the execution of the XML download and it worked. Then I tested the reading of it and the application ends up closing. What would be the right way to use JDOM2 with Asynctask? ( Pastebin: http://pastebin.com/rTNtEFyu )

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.