0

i am aware that the error is occurring because im trying to put a network call on the main thread so i need to use a handler or asynctask

however i dont seem to be able to get it right

this is the code im trying to get to work

 try {
                // Create a URL for the desired page
                URL url = new URL("http://darkliteempire.gaming.multiplay.co.uk/testdownload.txt");


                // Read all the text returned by the server
                BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                String str;
                while ((str = in.readLine()) != null) {
                    // str is one line of text; readLine() strips the newline character(s)

                    eventText.setText(str);
                    eventText.setText(in.readLine());
                }
                in.close();
            } catch (MalformedURLException e) {
                Toast.makeText(getBaseContext(), "MalformedURLException", Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                Toast.makeText(getBaseContext(), "IOException", Toast.LENGTH_LONG).show();
            }

and i want to call it when this button is clicked

public void onClick(View v) {

if (v.getId() == R.id.update) {
}
}

is anyone able to show me what i should wrap the first bit in and how to call it from the onClick

codeMagic
  • 44,549
  • 13
  • 77
  • 93
Master Zangetsu
  • 262
  • 7
  • 20

2 Answers2

2

Something like

public class TalkToServer extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

    }

    @Override
    protected String doInBackground(String... params) {
    //do your work here
        return something;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
           // do something with data here-display it or send to mainactivity
}

Do all heavy-lifting in doInBackground() and you can update the UI in the other 3 methods.

Here is the documentation on AsyncTask

codeMagic
  • 44,549
  • 13
  • 77
  • 93
0

Create and instantiate the AsyncTask in the onClick method. Put the call (and the wait) for the url call in the doOnBackground method and do whatever you want with the response in the onPostExecute (which happens in the main thread again).

palako
  • 3,342
  • 2
  • 23
  • 33