I have an application which allow to download 3 images and show them into a gallery
In order to do this , i use a thread in order to download the images and a handler in order to put the images into the gallery
The problem is that the images are not displayed(imageviews are empty) into the gallery (even if i see 3 imageview for my 3 images)
I do not know if this is because the connection is very slow (I develop on a mobile) or if it's because the ui is displayed before images are downloaded
Thank you very much for your help
public class ChoiceLanguage extends Activity {
private TextView nomLangue;
private ArrayList<Language> listeLangues;
private ArrayList<String> listImages;
private Gallery gallery;
private String URL="******************";
private Drawable mNoImage;
Bitmap bitmap;
ImageView imgView = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choice_language);
listeLangues= getIntent().getParcelableArrayListExtra("listeLangues");
listImages=buildListImages();
gallery = (Gallery) findViewById(R.id.galleryImg);
gallery.setAdapter(new AddImgAdp(this));
gallery.setSpacing(10);
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
System.out.println("URL "+ listImages.get(position) );
}
});
}
private InputStream openHttpConnection(String urlString) throws IOException {
InputStream in = null;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
conn.connect();
in=conn.getInputStream();
return in;
}
private Bitmap downloadImage( ImageView iView, String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedInputStream bis ;
try {
in = openHttpConnection(url);
bis= new BufferedInputStream(in, 8192);
bitmap = BitmapFactory.decodeStream(bis);
bis.close();
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
private ArrayList<String> buildListImages() {
ArrayList<String> listImg = new ArrayList<String>();
for(Language l : listeLangues) {
listImg.add(URL+l.getImagePath());
}
return listImg;
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
}
public int getCount() {
return listImages.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
imgView = new ImageView(cont);
} else {
imgView = (ImageView)convertView;
}
ThreadDownload progressDl= new ThreadDownload(position);
progressDl.start();
imgView.setLayoutParams(new Gallery.LayoutParams(150, 150));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}
private class SetImg extends Handler {
public void handleMessage(Message msg) {
imgView.setImageBitmap(bitmap);
}
}
private class ThreadDownload extends Thread {
SetImg img= new SetImg();
int position ;
public ThreadDownload(int position)
{
super();
this.position=position;
}
public void run() {
bitmap = downloadImage(imgView,listImages.get(position));
img.sendEmptyMessage(0);
}
}
}
You can make use of SmartImageView, it is a drop-in replacement for Android’s standard ImageView which additionally allows images to be loaded from URLs or the user’s contact address book. Images are cached to memory and to disk for super fast loading.
https://github.com/loopj/android-smart-image-view
Related
I want to send image from list view to other activity. I think i've done most of job, but i am continiously getting nullpointerexeptioon. Seems that my bitmap is null. How can i pass image from choosen item as a resourse to bitmap?
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long id) {
ImageView imm_id = ((ImageView) arg1.findViewById(R.id.imagePrev));
imm_id.getId();
RequestDataHolder.request_id = ids.get(position);
Bitmap bitmap=BitmapFactory.decodeResource(getResources(), imm_id.getId());
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] imm=stream.toByteArray();
Intent i = new Intent(getApplicationContext(),ResultViewActivity.class);
i.putExtra("imMap", imm);
startActivity(i);
adapter
public class MediaItemAdapter extends SimpleAdapter {
private int[] colors = new int[] { 0x30FF0000, 0x300000FF };
public static boolean notifyFlag = false;
private Context localContext;
private List<HashMap<String, Object>> locallist;
private static LayoutInflater inflater=null;
private Object rslv;
public ImageView imgV;
public String valueV;
Map cache = new HashMap();
public MediaItemAdapter(Context context,
List<HashMap<String, Object>> items, int resource,
String[] from,
int[] to) {
super(context, items, resource, from, to);
localContext = context;
locallist = items;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public void setViewText(TextView v, String text) {
// метод супер-класса, который вставляет текст
super.setViewText(v, text);
{
v.setText(Html.fromHtml(text));
}
}
#Override
public void setViewImage(ImageView v, String value) {
imgV = v;
valueV = value;
super.setViewImage(v, value);
if (imgV.getId() == R.id.imagePrev) {
if (value == null || value.trim().length() <= 0
|| value.equalsIgnoreCase("null")
|| value.trim().equalsIgnoreCase("")) {
imgV.setImageResource(R.drawable.stub);
// do nothing
} else {
if (cache.get(value) == null
&& !SearchPostActivity.loadingMore) {
notifyFlag = false;
new LazyImageLoader(localContext, value).execute();
} else {
imgV.setImageBitmap((Bitmap) cache.get(value));
}
}
}
}
class LazyImageLoader extends AsyncTask<String, Integer, Bitmap> {
private String URL;
private Context context;
public LazyImageLoader(Context context, String Url) {
URL = Url;
LazyImageLoader.this.context = context;
}
#Override
protected void onPreExecute() {
imgV.setImageResource(R.drawable.home);
}
#Override
protected Bitmap doInBackground(String... params) {
return getImg();
}
#Override
protected void onPostExecute(Bitmap img) {
if (!SearchPostActivity.scrollFlag) {
imgV.setImageBitmap(img);
notifyDataSetChanged();
}
notifyFlag = true;
cache.put(URL, img);
}
public synchronized Bitmap getImg() {
Bitmap bm = null;
try {
URL myurl;
myurl = new URL(URL);
URLConnection conn = myurl.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
bm = BitmapFactory.decodeStream(is);
} catch (Exception e) {
e.printStackTrace();
}
return bm;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_composer, null);
ImageView thumb_image=(ImageView)vi.findViewById( R.id.imagePrev);
return vi;
}
}
try this
yourListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> adapterView, final View view, final int position, final long id) {
final ImageView imageView = (ImageView) view.findViewById(R.id.imageViewXYZ);
final BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView.getDrawable();
final Bitmap yourBitmap = bitmapDrawable.getBitmap();
}
});
it would be better to use debug tool to find out the values of getResources() and imm_id.getId() at
Bitmap bitmap=BitmapFactory.decodeResource(getResources(),imm_id.getId());
i'm working on wallpaper app
i implemented this code in order to load my pictures from assets
loading-images-from-assets-folder
it's working great but i have issue with getting itemid from the list to use the id to display one of these images in fullscreenactivity or setting wallpaper
public long getItemId(int position) {
return position ;
}
here is my code
public class ImageAdapter extends BaseAdapter{
private Context mContext;
private List<String> list;
private AssetManager assetManager;
public ImageAdapter(Context c, List<String> list) {
mContext = c;
this.list = list;
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View view, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
try {
InputStream is = mContext.getAssets().open(list.get(position));
Bitmap bm = BitmapFactory.decodeStream(is);
imageView.setImageBitmap(bm);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(80, 80));
} catch (IOException e) {
e.printStackTrace();
}
// TODO Auto-generated method stub
return imageView;
}
public class Gs3Wallpaper extends Activity {
private ImageButton Gs3Button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView) findViewById(R.id.GridView1);
try {
gridView.setAdapter(new ImageAdapter(this ,getImage()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public List<String> getImage()throws IOException {
AssetManager assetManager = getAssets();
String[] files = assetManager.list("gallary");
List<String> list = new ArrayList<String>();
for (String it : files) {
list.add("gallary"+File.separator + it);
}
return list;
i don't know how to get the id from the list i tried to use list.get(position) but it returns string not int so i can't pass that to setImageResource for example
any suggestions?
What you can do is set the image or a path to the image, depending on how you are doing it, in a HashMap in getView() when you set the list item. Use the position for the key and the image as the value
public class MyClass
{
HashMap<String, Bitmap> imageMap = new HashMap<String, Bitmap>();
...
then set it in your getView()
public View getView(int position, View view, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
try {
InputStream is = mContext.getAssets().open(list.get(position));
Bitmap bm = BitmapFactory.decodeStream(is);
imageView.setImageBitmap(bm);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(80, 80));
String posString = String.valueOf(position);
imageMap.put(posString, bm);
} catch (IOException e) {
....
}
Something like this should work for you. Then just use the position to get that bitmap out of the HashMap
I have been trying to pass bitmap array to another Activity for a week but I still can't do it
public class HomePage extends Activity {
private GridView gridView;
public Bitmap[] mBitArray;
public Bitmap[] mBitArray5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
gridView = (GridView) findViewById(R.id.GridView1);
mBitArray = new Bitmap[7];
try
{
//these images are stored in the root of "assets"
mBitArray[0] = getBitmapFromAsset("Gallary/g1p1.jpg");
mBitArray[1] = getBitmapFromAsset("Gallary/g1p2.jpg");
mBitArray[2] = getBitmapFromAsset("Gallary/g1p3.jpg");
mBitArray[3] = getBitmapFromAsset("Gallary/g1p4.jpg");
mBitArray[4] = getBitmapFromAsset("Gallary/g1p5.jpg");
mBitArray[5] = getBitmapFromAsset("Gallary/g1p6.jpg");
mBitArray[6] = getBitmapFromAsset("Gallary/g2p1.jpg");
mBitArray[7] = getBitmapFromAsset("g2p2.jpg");
mBitArray[8] = getBitmapFromAsset("hd-01.jpg");
mBitArray[9] = getBitmapFromAsset("hd-02.jpg");
mBitArray[10] = getBitmapFromAsset("hd-03.jpg");
mBitArray[11] = getBitmapFromAsset("hd-04.jpg");
}
catch (IOException e)
{
e.printStackTrace();
}
gridView.setAdapter(new ImageAdapter(this, mBitArray));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
startActivity(i);
// TODO Auto-generated method stub
}
});
}
public Bitmap getBitmapFromAsset(String strName) throws IOException {
AssetManager assetManager = getAssets();
InputStream istr = assetManager.open(strName);
Bitmap bitmap = BitmapFactory.decodeStream(istr);
istr.close();
return bitmap;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_home_page, menu);
return true;
}
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private Bitmap[] mImageArray;
public ImageAdapter(Context context, Bitmap[] imgArray)
{
mContext = context;
mImageArray = imgArray;
}
public int getCount() {
return mImageArray.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return mImageArray[position];
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageBitmap(mImageArray[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(153, 150));
return imageView;
}
public Bitmap getView1(int position) throws IOException {
AssetManager am = mContext.getAssets();
String[] list = am.list("Gallary");
BufferedInputStream buf = new BufferedInputStream(am.open(list[position]));
Bitmap bitmap = BitmapFactory.decodeStream(buf);
buf.close();
return bitmap;
}
}
public class FullImageActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fullimage);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
Intent i = getIntent();
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this , null);
//imageView.setImageBitmap(mBitArray[position]);
trying to get mBitarray to fullscreenactivity to display a certain picture from the bitmap array
so I want to pass MbitArray variable to Fullactivity class I tried to do it by Intent but I can't send Bitmap array maybe via constructor or inner class?
Since Bitmap implements Parcelable, and you have an array of Bitmap, you should be able to pass them off:
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("bitmaps", mBitArray);
startActivity(i);
Then retrieve via getParcelableArrayExtra():
Intent i = getIntent();
Bitmap [] bitmaps = (Bitmap[]) i.getParcelableArrayExtra ("bitmaps");
You can also pass off the paths in a String array to FullImageActivity, then just remake them there, much like you did in your first Activity. To save code, if you choose this approach, making the method shared by making it static would be a good idea, just remember to pass off a Context instance so getAssets() can still be used:
public static Bitmap getBitmapFromAsset(Context context, String strName) throws IOException {
AssetManager assetManager = context.getAssets();
InputStream istr = assetManager.open(strName);
Bitmap bitmap = BitmapFactory.decodeStream(istr);
istr.close();
return bitmap;
}
Then to call, from HomePage
mBitArray[0] = getBitmapFromAsset(this,"Gallary/g1p1.jpg");
and from FullImageActivity
otherBitmapArray[0] = HomePage.getBitmapFromAsset(this, bitmapPaths[0]);
This project I've done with image in my drawable but now I want to get image url from JSON by using Asynctask and display it. and I make php that provide a json string like below.
I want to get path of image(url) by using AsyncTask from JSON.
I want to use data from json instead of public mThumbId = {...};
{"count":"28","data":
[{"id":"1",
"first_name":"man",
"last_name":"woman",
"username":"man",
"password":"4f70432e636970de9929bcc6f1b72412",
"email":"man#gmail.com",
"url":"http://vulcan.wr.usgs.gov/Imgs/Jpg/MSH/Images/MSH64_aerial_view_st_helens_from_NE_09-64_med.jpg"},
{"id":"2",
"first_name":"first",
"last_name":"Last Name",
"username":"user",
"password":"1a1dc91c907325c69271ddf0c944bc72",
"email":"first#gmail.com",
"url":"http://www.danheller.com/images/California/Marin/Scenics/bird-view-big.jpg"},
{"id":"3",
"first_name":"first",
"last_name":"Last Name",
"username":"user",
"password":"1a1dc91c907325c69271ddf0c944bc72",
"email":"0",
"url":"http://www.hermes.net.au/bodhi/images/view/large/view_03.jpg"}]}
AndroidGridLayoutActivity
GridView gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
ImageAdapter
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.pic_1, R.drawable.pic_2,
R.drawable.pic_3, R.drawable.pic_4,
R.drawable.pic_5, R.drawable.pic_6,
R.drawable.pic_7, R.drawable.pic_8,
R.drawable.pic_9, R.drawable.pic_10,
R.drawable.pic_11, R.drawable.pic_12,
R.drawable.pic_13, R.drawable.pic_14,
R.drawable.pic_15
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return mThumbIds[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
FullImageActivity
Intent i = getIntent();
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
I think that this simple link will totally answer your question:
https://github.com/novoda/ImageLoader
And my own implementation:
https://github.com/iRail/BeTrains-for-Android/blob/master/src/tof/cv/mpp/adapter/TweetItemAdapter.java
EDIT
What you really need to do:
1) Parse JSON: there are thousands of tutorials on the web, or use the awesome GSON library.
2) Once JSON is parsed, you will get an array of objects.
3) In your Adapter, you will maybe need to extend ArrayAdapter.
4) in the getView() method, analyse my 2 above links and use something like:
imageLoader.DisplayImage(tweet.profile_image_url, activity, holder.image);
You have to first extract the urls from json in a array and then use below code to load image as bitmap dynamically using Async Task.
Bitmap bm[]=new Bitmap[3];
ImageAdapter img;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bm[0]=null;
bm[1]=null;
bm[2]=null;
InputStream is= getDataFromServer();
String asd=getResponseFromStream(is);
try {
JSONObject jsn=new JSONObject(asd);
JSONArray jd=jsn.getJSONArray("data");
for(int i=0;i<jd.length();i++)
{
JSONObject j_object=jd.getJSONObject(i);
String url=j_object.getString("url");
urls.add(url);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
img=new ImageAdapter(this);
GridView gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(img);
new ImageDownloader().execute();
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
}
ProgressDialog prg;
private class ImageDownloader extends AsyncTask<Integer, Integer, String>
{
#Override
public void onPreExecute()
{
prg=ProgressDialog.show(LazyLoadActivity.this, null,
"Loading...");
}
protected void onPostExecute(String result)
{
prg.hide();
}
protected void onProgressUpdate(Integer... progress) {
img.notifyDataSetChanged();
}
protected String doInBackground(Integer... a)
{
for(int i=0;i<3;i++)
{
bm[i]=downloadBitmap(urls[i]);
this.publishProgress(i);
}
return "";
}
}
public Integer[] mThumbIds = {
R.drawable.ic_launcher, R.drawable.ic_launcher,
R.drawable.ic_launcher
};
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return mThumbIds[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
if(bm[position]==null)
imageView.setImageResource(mThumbIds[position]);
else
imageView.setImageBitmap(bm[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
Bitmap downloadBitmap(String url) {
final HttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
inputStream = entity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// Could provide a more explicit error message for IOException or IllegalStateException
getRequest.abort();
Log.e("ImageDownloader", "Error while retrieving bitmap from " + url);
} finally {
if (client != null) {
//client.
}
}
return null;
}
In my application, to populating a ListView i am using custom adapter, because one listitem consists of 3 TextViews and 1 ImageView.
Everytime images are fetched from url.
So when i am launching this activity its taking much time,because its downloading all images then populating the lists.
So i want without images list should populate first having only Textviews and after that only images should come.
How can i do that?
By loading your images with an AsyncTask
example directly from documentation:
public void onClick(View v) {
new DownloadImageTask().execute("http://example.com/image.png");
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}
you have to create a lazy image loader using async task.
by doing that, all your list view will be populated. and when the images are fetched, they are updated into the list views asynchronously.
Here is a link - http://iamvijayakumar.blogspot.com/2011/06/android-lazy-image-loader-example.html
You can use lazy load images like this:
https://github.com/thest1/LazyList
Lazy load of images in ListView
The basic Idea is to have a loading image already within your app.
Then use an asyncTask or a thread to load image.
Some code to start with :
Adapter
public class ImageAdapter extends BaseAdapter {
private static final String TAG = "Image Adapter";
int mGalleryItemBackground;
private Context mContext;
private GridView mView;
/** URL-Strings to some remote images. */
private String[] mRemoteImagesURL ;
private Bitmap[] loadedImages;
public ImageAdapter(Context c,String[] remoteImagesURL,GridView v) {
mContext = c;
TypedArray attr = mContext.obtainStyledAttributes(R.styleable.HelloGallery);
mGalleryItemBackground = attr.getResourceId(R.styleable.HelloGallery_android_galleryItemBackground, 0);
attr.recycle();
mView = v;
mRemoteImagesURL=remoteImagesURL;
loadedImages = new Bitmap[mRemoteImagesURL.length];
}
public int getCount() {
return mRemoteImagesURL.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.gallery_item, null);
}
ImageView imageView = (ImageView) convertView.findViewById(R.id.FrontImageView);
/* when image is already down-loaded then load that image */
if(loadedImages[position]!=null)
imageView.setImageBitmap(loadedImages[position]);
else
imageView.setImageResource(R.drawable.loading);
imageView.setBackgroundResource(mGalleryItemBackground);
return convertView;
}
public void loadImage(int position){
Bitmap bm;
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL(mRemoteImagesURL[position]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
loadedImages[position] =bm;
} catch (Exception e) {
Log.e(TAG, "Remote Image Load Exception"+e);
}
}
public void setLoadedImage(int position)
{
Log.d(TAG, "Position "+position);
View childView= mView.getChildAt(position);
if(loadedImages[position]!=null && childView != null)
{
ImageView imageView= (ImageView) childView.findViewById(R.id.FrontImageView);
imageView.setImageBitmap(loadedImages[position]);
}
}
}
private void updateImagesAsThread() {
Thread t = new Thread()
{
public void run()
{
try {
for(int i=0;i<imageAdapter.getCount();i++)
{
imageAdapter.loadImage(i);
listAdapterHandler.sendEmptyMessage(i);
}
}
catch (Exception e) {
// TODO: handle exception
Log.e(TAG,"UpdateImageAsThread "+e);
}
}
};
t.start();
}
private Handler listAdapterHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case -1:
Log.d(TAG, "here in the handle...");
break;
default:
Log.d(TAG, "here in the handle default...");
imageAdapter.setLoadedImage(msg.what);
//imageAdapter.notifyDataSetChanged();
break;
}
}
};