问题
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
回答1:
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
回答2:
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).
来源:https://stackoverflow.com/questions/13882095/using-a-handler-asynctask-or-similar-to-run-a-networking-task