AsyncTask is used to download raw data through a url in form of a string and image in form of bitmap
public static class DownloadImage extends AsyncTask<String, Void, Bitmap>{
@Override
protected Bitmap doInBackground(String... strings) {
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
InputStream in = urlConnection.getInputStream();
Bitmap myBitmap;
myBitmap = BitmapFactory.decodeStream(in);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadImage iTask = new DownloadImage();
Bitmap myBitmap = iTask.execute(celebURL.get(celebIndex)).get();
}
public class MainActivity extends AppCompatActivity {
ImageView imageView;
public static class DownloadTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... source) {
String result = "";
try {
URL url = new URL(source[0]);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1){
char cur = (char)data;
result += cur;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String pageSource;
DownloadTask task = new DownloadTask();
try{
pageSource = task.execute("https://comicvine.gamespot.com/profile/idea/lists/top-100-comic-book-heroes-ign/32884/").get();
Log.i("test run", pageSource);
} catch (Exception e) {
e.printStackTrace();
Log.i("Fail", "Error occured");
}
}
}