In Android Studio when I use Asynctask
, execute it and try to use get()
in the onCreate
method it freezes my whole UI.
My Asynctask class:
public class HTMLDownload extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return "Failed";
}
}
My onCreate method code:
HTMLDownload task = new HTMLDownload();
try {
String result = task.execute("https://www.telltalesonline.com/26925/popular-celebs/").get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("Result", result);
How can I fix this and log the text once the HTML is downloaded without freezing the UI?
Thanks
As mentioned AsyncTask
is deprecated. You are better off using something like Android Volley
build.gradle:
dependencies {
// ...
implementation 'com.android.volley:volley:1.1.1'
}
AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
Inside your Fragment or class or whatever:
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(getActivity());
String url = "https://www.telltalesonline.com/26925/popular-celebs/";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// TODO handle the response
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO handle error
}
}
);
// Add the request to the RequestQueue.
queue.add(stringRequest);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.