Load two images from url to imageviews - android

when I tried to load only one image from url, it is working, but when I tried to load two images, it's just loading the last image.
This is what I've tried so far:
ProgressDialog pd;
private ImageView imgView1, imgView2;
private String strURLJohnA = "sample1.jpg";
private String strURLJohnR = "sample2.jpg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
back = (Button) findViewById (R.id.btBack);
back.setOnClickListener(this);
imgView1 = (ImageView) findViewById(R.id.ivInfo1);
imgView2 = (ImageView) findViewById (R.id.ivInfo2);
// Create an object for subclass of AsyncTask
GetXMLTask task = new GetXMLTask();
// Execute the task
task.execute(new String[] { strURLJohnA, strURLJohnR });
}
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = ProgressDialog.show(Info.this, "Please wait", "Downloading content", false, true);
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
imgView1.setImageBitmap(result);
imgView2.setImageBitmap(result);
pd.dismiss();
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
Any ideas how to resolve the issue? I'd greatly appreciate your help. Thanks.

You a list instead as follows:
private class GetXMLTask extends AsyncTask<String, Void, ArrayList<Bitmap>> {
#Override
protected ArrayList<Bitmap> doInBackground(String... urls) {
ArrayList<Bitmap> map = new ArrayList<Bitmap>();
for (String url : urls) {
map.add(downloadImage(url));
}
return map;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = ProgressDialog.show(Info.this, "Please wait", "Downloading content", false, true);
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(ArrayList<Bitmap> result) {
imgView1.setImageBitmap(result.get(0));
imgView2.setImageBitmap(result.get(1));
pd.dismiss();
}
...
...
...
You need to return a list of Bitmap objects like I have shown in the code above. Then set the imageView to its respective bitmap.

(String... urls) is Var args. You dont need to pass a string array to it. Use as following code:
task.execute( strURLJohnA, strURLJohnR );
private class GetXMLTask extends AsyncTask<String, Void, ArrayList<Bitmap>> {
#Override
protected ArrayList<Bitmap> doInBackground(String... urls) {
ArrayList<Bitmap> map = new ArrayList<Bitmap>();
map.add(downloadImage(urls[0]));// I used as this for you to understand. You can use for each loop
map.add(downloadImage(urls[1]));
return map;
}
#Override
protected void onPostExecute(ArrayList<Bitmap> result) {
imgView1.setImageBitmap(result.get(0));
imgView2.setImageBitmap(result.get(1));
}

ProgressDialog pd;
private ImageView imgView1, imgView2;
//we can store any number of urls in a string array and load them at a time
private String[] str={"http://www.bogotobogo.com/images/rodin.jpg","http://www.bogotobogo.com/images/smalltiger.gif"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView1=(ImageView)findViewById(R.id.imageView1);
imgView2=(ImageView)findViewById(R.id.imageView2);
// Create an object for subclass of AsyncTask
GetXMLTask task = new GetXMLTask ();
// Execute the task
task.execute(str);
}
private class GetXMLTask extends AsyncTask<String, Void, ArrayList<Bitmap>> {
#Override
protected ArrayList<Bitmap> doInBackground(String... urls) {
ArrayList<Bitmap> map = new ArrayList<Bitmap>();
//enhanced for statement, mainly used for arrays
for (String url : urls) {
map.add(downloadImage(url));
}
return map;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd = ProgressDialog.show(Info.this, "Please wait", "Downloading content", false, true);
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(ArrayList<Bitmap> result) {
imgView1.setImageBitmap(result.get(0));
imgView2.setImageBitmap(result.get(1));
pd.dismiss();
}

Related

App force closing when Async tries to get Bitmap from url

I have an Async running to get data from a page I've created. It get's the text just fine, but when I try and get the image from the image src via another class the app force closes. Here is the code that it force closes on:
public class FullReportActivity extends NavigationActivity {
private TextView textView;
private String url = "http://www.backcountryskiers.com/sac/sac-full.html";
private ImageView ivDangerRose;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// tell which region this covers
getSupportActionBar().setSubtitle("...from Sierra Avalanche Center");
setContentView(R.layout.activity_fullreport);
textView = (TextView) findViewById(R.id.todaysReport);
ivDangerRose = (ImageView) findViewById(R.id.dangerRose);
fetcher task = new fetcher();
task.execute();
}
// GET THE IMAGE and RETURN IT
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
class fetcher extends AsyncTask<String, Void, String> {
private ProgressDialog dialog = new ProgressDialog(
FullReportActivity.this);
private Document doc = null;
private Document parse = null;
private String results = null;
private String reportDate = null;
private Bitmap bimage = null;
#Override
protected String doInBackground(String... params) {
try {
doc = Jsoup.connect(url).get();
Log.e("Jsoup", "...is working...");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Exception", e.getMessage());
}
parse = Jsoup.parse(doc.html());
results = doc.select("#fullReport").outerHtml();
Element dangerRoseImg = doc.getElementById("reportRose")
.select("img").first();
String dangerRoseSrc = dangerRoseImg.absUrl("src");
Log.i("Report Rose IMG", dangerRoseSrc);
bimage = getBitmapFromURL(dangerRoseSrc);
ivDangerRose.setImageBitmap(bimage);
return results;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// smooth out the long scrolling...
textView.setMovementMethod(ScrollingMovementMethod.getInstance());
reportDate = parse.select("#reportDate").outerHtml();
textView.setText(Html.fromHtml(reportDate + results));
textView.setPadding(30, 20, 20, 10);
}
#Override
protected void onPreExecute() {
dialog.setMessage("Loading Full Report from the Sierra Avalanche Center...");
dialog.show();
}
}
}
I have run this Async alone to get the image like so without a force close and I don't understand what i am doing different besides calling the method:
public class MainActivity extends Activity {
public String durl = "http://www.sierraavalanchecenter.org/dangerrose.png?a=2955";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadImageTask((ImageView) findViewById(R.id.dangerrose))
.execute(durl);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap drose = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
drose = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return drose;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
This class gets the image src and creates a bitmap and puts it into an ImageView, what is different here than on my first class???
Frustrated.
You can not modify UI from background thread.
move ivDangerRose.setImageBitmap(bimage); in onPostExecute
In the method doInBackground
remove --> ivDangerRose.setImageBitmap(bimage);
as you can't modify UI in background process.
If you still want you can try runOnUiThread Method
In doInBackground() we should not access the content of activity.

How do i return a bitmap from an Asyncronous task

im fetching an image from internet using the below code using an Async task,But the bitmp returns from the function is always null.
private Bitmap asyncTaskFetchImage(final String imgeurl) {
// TODO Auto-generated method stub
new AsyncTask<Object, Object, Object>() {
#Override
protected void onPreExecute() {
progress_Dialog = ProgressDialog.show(this, "", "Loading");
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
try
{
toSendBg=LoadImageFromURL(imgeurl);
System.gc();
return 0;
}
catch (Exception e) {
e.printStackTrace();
}
return 0;
}
#Override
protected void onPostExecute(Object result) {
if (progress_Dialog != null) {
progress_Dialog.dismiss();
}
}
}.execute();
return toSendBg;
}
Is this the exact way to return value from an Asyntask?
Try below code to download image from web using AsyncTask and display in imageview.
public class MainActivity extends Activity {
ImageView mImgView1;
static Bitmap bm;
ProgressDialog pd;
String imageUrl = "https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg";
BitmapFactory.Options bmOptions;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
pd = ProgressDialog.show(MainActivity.this, "Aguarde...",
"Carregando...");
new ImageDownload().execute("");
}
public class ImageDownload extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
loadBitmap(imageUrl, bmOptions);
return imageUrl;
}
protected void onPostExecute(String imageUrl) {
pd.dismiss();
if (!imageUrl.equals("")) {
mImgView1.setImageBitmap(bm);
} else {
Toast.makeText(MainActivity.this,
"Não foi possível obter resultados", Toast.LENGTH_LONG)
.show();
}
}
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bm = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bm;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
}
private Bitmap asyncTaskFetchImage(final String imgeurl) {
Bitmap bmp=null;
new AsyncTask<Object, Object, Object>() {
...
and in your doInBackground method change return to
return toSendBg;
and
#Override
protected void onPostExecute(Object result) {
if (progress_Dialog != null) {
progress_Dialog.dismiss();
bmp=(Bitmap)result;
}
}
}.execute();
return bmp;
Try this..,.

How to display the images from server asynchronously in Android?

I am displaying an image from a server in Android. For that I have gone through the tutorial Android Load Image From URL Example. It is very helpful. But it is taking 5 minutes to display the image from the server. So I want to display the image asynchronously. How can I do that?
The below snippets will help you.
DownloadHelper.java
public interface DownloadHelper
{
public void OnSucess(Bitmap bitmap);
public void OnFailure(String response);
}
MainActivity.java
public class GalleryExample extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
DownloadHelper downloadHelper = new DownloadHelper()
{
#Override
public void OnSucess(Bitmap bitmap)
{
ImageView imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(bitmap);
}
#Override
public void OnFailure(String response)
{
Toast.makeText(context, response, Toast.LENGTH_LONG).show();
}
};
new MyTask(this,downloadHelper).execute("image url");
}
MyTask.java
public class DownloadTask extends AsyncTask<String, Integer, Object>
{
private Context context;
private DownloadHelper downloadHelper;
private ProgressDialog dialog;
public DownloadTask(Context context,DownloadHelper downloadHelper)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
dialog = new ProgressDialog(context);
dialog.setTitle("Please Wait");
dialog.setMessage("Fetching Data!!");
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
#Override
protected Object doInBackground(String... params)
{
URL aURL = new URL(myRemoteImages[position]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
return bm;
}
#Override
protected void onPostExecute(Object result)
{
dialog.dismiss();
if (result != null)
{
downloadHelper.OnSucess((Bitmap)result);
}
else
{
downloadHelper.OnFailure("Error in Downloading Data!!");
}
super.onPostExecute(result);
}
}

Android:progress dialog

I need to implement progress bar in an android project when an intent is passed through one activity another, and some a fair bit of data from the internet is being downloaded in second activity and as such there is a noticeable delay between when the user clicks on an item and when the Activity displays.
I've tried a few different approaches for this but nothing seems to work as desired. I am using the following code for it. And the progress dialog is going inside infinite loop.
public class BackgroundAsyncTask extends AsyncTask<String, Integer, Bitmap> {
int myProgress;
#Override
protected void onPostExecute(Bitmap result) {
iv.setVisibility(View.VISIBLE);
iv.setImageBitmap(result);
dialog.cancel();
dialog.dismiss();
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(ProfileNormalUserPhotos.this, "Loading...", "Please wait...");
}
#Override
protected Bitmap doInBackground(String...paths) {
return DownloadFile(imageUrl);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressBar.setProgress(values[0]);
}
}
public Bitmap DownloadFile(String url){
URL myFileUrl;
Bitmap bitmap=null;
try {
myFileUrl = new URL(imageUrl);
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
bitmap = BitmapFactory.decodeStream((InputStream) new URL(
imageUrl).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap,70 , 70, true);
System.out.println("name of bitmap"+bitmap.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e);
}
return bitmap;
}
And following is my adapter class
public class ImageAdapter extends BaseAdapter {
Context mContext;
private String[] stringOnTextView;
public ImageAdapter(Context c) {
mContext = c;
}
// BitmapManager.INSTANCE. setPlaceholder(BitmapFactory.decodeResource(
// context.getResources(), R.drawable.icon));
public ImageAdapter(Context Context,
String[] stringOnTextView) {
this.mContext=Context;
this.stringOnTextView=stringOnTextView;
}
public int getCount() {
return stringOnTextView.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("**************"+position);
View v = null;
if(convertView==null){
try{
{
System.gc();
// dialog = ProgressDialog.show(ProfileNormalUserPhotos.this, "Loading...", "Please wait...");
imageUrl = "http://ondamove.it/English/images/users/";
imageUrl=imageUrl+stringOnTextView[position];
System.out.println(imageUrl);
LayoutInflater li = getLayoutInflater();
v = li.inflate(R.layout.icon, null);
TextView tv = (TextView)v.findViewById(R.id.text);
tv.setText("Profile Image "+(position+1));
/* URL myFileUrl = new URL(imageUrl);
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
imageUrl).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap, 80, 80, true);*/
// new ImageView(mContext);
iv= (ImageView)v.findViewById(R.id.image);
new BackgroundAsyncTask().execute(imageUrl);
//iv.setImageBitmap(bitmap);
//dialog.cancel();
// System.out.println(bitmap.getHeight());
System.out.println("++++++++"+R.id.image);
}
}catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
else
{
try{
v = convertView;}
catch(Exception e){
System.out.println(e);
}
}
return v;
}
}
Can anyone help me over this?
Try AsyncTask,
private class myAsyncTask extends AsyncTask<String, Void, Void>
{
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(Activity_name.this, "Loading...", "Please wait...");
}
#Override
protected Void doInBackground(String... params) {
String url = params[0];
// you can do download from internet here
return null;
}
#Override
protected void onPostExecute(Void result) {
mProgressDialog.dismiss();
}
}
Android AsyncTask its answer for what you needed. Look here Android - AsyncTask
The trick is to
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
for your progressDialog.

Android : Loading an image from the Web with Asynctask

How do I replace the following lines of code with an Asynctask ?
How do you "get back" the Bitmap from the Asynctask ? Thank you.
ImageView mChart = (ImageView) findViewById(R.id.Chart);
String URL = "http://www...anything ...";
mChart.setImageBitmap(download_Image(URL));
public static Bitmap download_Image(String url) {
//---------------------------------------------------
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//---------------------------------------------------
}
I thought about something like this :
replace :
mChart.setImageBitmap(download_Image(graph_URL));
by something like :
mChart.setImageBitmap(new DownloadImagesTask().execute(graph_URL));
and
public class DownloadImagesTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
return download_Image(urls[0]);
}
#Override
protected void onPostExecute(Bitmap result) {
mChart.setImageBitmap(result); // how do I pass a reference to mChart here ?
}
private Bitmap download_Image(String url) {
//---------------------------------------------------
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
//---------------------------------------------------
}
}
but How do I pass a reference to mChart in onPostExecute(Bitmap result) ???
Do I need to pass it with the URL in some way ?
I would like to replace all my lines of code :
mChart1.setImageBitmap(download_Image(URL_1));
mChart2.setImageBitmap(download_Image(URL_2));
with something similar ... but in Asynctask way !
mChart1.setImageBitmap(new DownloadImagesTask().execute(graph_URL_1));
mChart2.setImageBitmap(new DownloadImagesTask().execute(graph_URL_2));
Is there an easy solution for this ?
Do I get something wrong here ?
If there is no good reason to download the image yourself then I would recommend to use Picasso.
Picasso saves you all the problems with downloading, setting and caching images.
The whole code needed for a simple example is:
Picasso.with(context).load(url).into(imageView);
If you really want to do everything yourself use my older answer below.
If the image is not that big you can just use an anonymous class for the async task.
This would like this:
ImageView mChart = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...anything ...";
mChart.setTag(URL);
new DownloadImageTask.execute(mChart);
The Task class:
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
...
}
Hiding the URL in the tag is a bit tricky but it looks nicer in the calling class if you have a lot of imageviews that you want to fill this way. It also helps if you are using the ImageView inside a ListView and you want to know if the ImageView was recycled during the download of the image.
I wrote if you Image is not that big because this will result in the task having a implicit pointer to the underlying activity causing the garbage collector to hold the whole activity in memory until the task is finished. If the user moves to another screen of your app while the bitmap is downloading the memory can't be freed and it may make your app and the whole system slower.
Try this code:
ImageView myFirstImage = (ImageView) findViewById(R.id.myFirstImage);
ImageView mySecondImage = (ImageView) findViewById(R.id.mySecondImage);
ImageView myThirdImage = (ImageView) findViewById(R.id.myThirdImage);
String URL1 = "http://www.google.com/logos/2013/estonia_independence_day_2013-1057005.3-hp.jpg";
String URL2 = "http://www.google.com/logos/2013/park_su-geuns_birthday-1055005-hp.jpg";
String URL3 = "http://www.google.com/logos/2013/anne_cath_vestlys_93rd_birthday-1035005-hp.jpg";
myFirstImage.setTag(URL1);
mySecondImage.setTag(URL2);
myThirdImage.setTag(URL3);
new DownloadImageTask.execute(myFirstImage);
new DownloadImageTask.execute(mySecondImage);
new DownloadImageTask.execute(myThirdImage);
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
Bitmap bmp =null;
try{
URL ulrn = new URL(url);
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
InputStream is = con.getInputStream();
bmp = BitmapFactory.decodeStream(is);
if (null != bmp)
return bmp;
}catch(Exception e){}
return bmp;
}
}
you can create a class say..BkgProcess which contains an inner class that extends AsyncTask. while instantiating BkgProcess pass the context of your Activity class in BkgProcess constructor. for eg:
public class BkgProcess {
String path;
Context _context;
public Download(Downloader downloader, String path2){
this.path = path2;
_context = downloader;
}
public void callProgressDialog(){
new BkgProcess().execute((Void)null);
}
class Downloads extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(_context);
protected void onPreExecute(){
dialog.setMessage("Downloading image..");
dialog.show();
}
protected void onPostExecute(Boolean success) {
dialog.dismiss();
if(success)
Toast.makeText(_context, "Download complete", Toast.LENGTH_SHORT).show();
}
#Override
protected Boolean doInBackground(Void... params) {
return(startDownload(path));
}
public boolean startDownload(String img_url) {
// download img..
return true;
}
}
}
from your activity class..
BkgProcess dwn = new BkgProcess (Your_Activity_class.this, img_path);
dwn.callProgressDialog();
This will get you images of any size...
if you dont want the progress dialog just comment the codes in onPreExecute();
for(int i = 0 ; i < no_of_files ; i++ )
new FetchFilesTask().execute(image_url[i]);
private class FetchFilesTask extends AsyncTask<String, Void, Bitmap> {
private ProgressDialog dialog = new ProgressDialog(FileExplorer.this);
Bitmap bitmap[];
protected void onPreExecute(){
dialog.setMessage("fetching image from the server");
dialog.show();
}
protected Bitmap doInBackground(String... args) {
bitmap = getBitmapImageFromServer();
return bitmap;
}
protected void onPostExecute(Bitmap m_bitmap) {
dialog.dismiss();
if(m_bitmap != null)
//store the images in an array or do something else with all the images.
}
}
public Bitmap getBitmapImageFromServer(){
// fetch image form the url using the URL and URLConnection class
}

Categories

Resources