Reputation: 105499
I need to request data from webservice. I've implemented the following AsyncTask to do that:
class LoadTagsTask extends AsyncTask<Void, Void, String> {
private String url = "http://webservice.com/rest/tagsManager/search";
ProgressBar loader;
@Override
protected void onPreExecute() {
loader = (ProgressBar) TextsListActivity.this.findViewById(R.id.textLoadingProgressBar);
loader.setVisibility(TextView.VISIBLE);
}
@Override
protected String doInBackground(Void... params) {
HttpURLConnection c = null;
try {
c = (HttpURLConnection) new URL(url).openConnection();
InputStream in = c.getInputStream();
StringBuilder stringBuffer = new StringBuilder();
final char[] charBuffer = new char[8 * 1024];
BufferedReader reader = new BufferedReader(new InputStreamReader(in), charBuffer.length);
int read;
while ((read = reader.read(charBuffer)) != -1) {
stringBuffer.append(charBuffer, 0, read);
}
reader.close();
return stringBuffer.toString();
} catch (Exception e) {
return "";
} finally {
if (c != null) {
c.disconnect();
}
}
}
@Override
protected void onPostExecute(String tags) {
loader.setVisibility(TextView.GONE);
TextsListActivity.this.showTagsSelectorActivity(tags);
}
}
Does it make sense to replace it with AsyncTaskLoader
? I've read that they can be used interchangeably, but AsyncTaskLoader
does a bit better job. Is is applicable in my this case?
Upvotes: 0
Views: 1054
Reputation: 24991
I think you should replace AsyncTask
with Retrofit.
It encapsulates low-level logic like managing threads and http conection.
Using Retrofit makes your code cleaner and allow you to focus only on the data which the backend serves.
Retrofit supports:
Upvotes: 4