Getting itemid from list<string> - android

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

Related

Android download list of images and show images in viewpager with progress dialog

Hi i am trying to show some images in viewPager those need be download before show and also i need to show progress bar while downloading. Can any one please help me sort this out. Also i am trying to all viewpager adapter form list view adapter. is it a good practice. Below is my code
Here is my list adapter
public class adapter extends ArrayAdapter<FriendList> {
private Context context;
private List<FriendList> frndList;
ProgressDialog mProgressDialog;
LinearLayout inHorizontalScrollView;
View view;
public adapter(Context context, int resource, List<FriendList> objects) {
super(context, resource, objects);
this.context = context;
this.frndList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.item_file, parent, false);
FriendList friensList = frndList.get(position);
Log.v("=====================","======111111========"+friensList);
Friend temp = friensList.getFriend();
Log.v("=====================","======temp========"+temp);
//inHorizontalScrollView = (LinearLayout)view.findViewById(R.id.inhorizontalscrollview);
List<String> imageArra = temp.getImageData();
Log.v("=====================","======imageArra========"+imageArra.size());
ViewPager myPager = (ViewPager) view.findViewById(R.id.myfivepanelpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(context);
myPager.setAdapter(adapter);
adapter.change(imageArra);
return view;
}
}
here is my viewpager adapter
public class ViewPagerAdapter extends PagerAdapter {
/* Adapter activity;
int imageArray[];
private Context context;
public ViewPagerAdapter( Context context, int[] imgArra) {
imageArray = imgArra;
//activity = act;
context = context;
}*/
ProgressDialog mProgressDialog;
private List<String> mPaths;
private Context mContext;
public ViewPagerAdapter(Context cx) {
mContext = cx.getApplicationContext();
}
public void change(List<String> paths) {
mPaths = paths;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mPaths.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView iv = new ImageView(mContext);
String path = mPaths.get(position);
Log.v("=====================","======path====11===="+path);
new calc_stanica().execute(path, container, iv);
try {
Bitmap bitmap = Glide.with(mContext).load(path).asBitmap().into(-1, -1).get();
//Bitmap bm = BitmapFactory.decodeFile(mPaths.get(position));
iv.setImageBitmap(bitmap);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
((ViewPager) container).addView(iv, 0);
return iv;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object obj) {
// TODO Auto-generated method stub
return view == (View) obj;
}
private class calc_stanica extends AsyncTask<Object, Void, Bitmap> {
ViewGroup container;
ImageView iv;
/*#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(mContext);
// Set progressdialog title
mProgressDialog.setTitle("Download Image Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}*/
#Override
protected Bitmap doInBackground(Object... params) {
//ArrayList<Bitmap> result = new ArrayList<Bitmap>();
String pass = (String) params[0];
container = (ViewGroup) params[1];
iv = (ImageView) params[2];
//View str = (View) params[1];
//Context ctx = (Context) params[2];
//Log.v("================", "===passed========" + passed);
Bitmap bitmap = null;
try {
// Download Image from URL
//InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = Glide.with(mContext).load(pass).asBitmap().into(-1, -1).get();
} catch (Exception e) {
e.printStackTrace();
}
//int intArray[] = new int[bitmap.getWidth()*bitmap.getHeight()];
//result.add(bitmap);
//Log.v("================", "===result========" + result);
//Some calculations...
return bitmap; //return result
}
//*protected Bitmap doInBackground(String... URL) {
/* String imageURL = URL[0];
Bitmap bitmap = null;
ArrayList<Bitmap> list;
try {
// Download Image from URL
//InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = Glide.with(getApplicationContext()).load(imageURL).asBitmap().into(-1, -1).get();
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;*/
#Override
protected void onPostExecute(Bitmap result) {
if(result != null) {
iv.setImageBitmap(result);
((ViewPager)container).addView(iv, 0);
}
//mProgressDialog.dismiss();
}
}
}
it gives me error in get count and not allow to add progress bar in adapter.
Change your code order from
myPager.setAdapter(adapter);
adapter.change(imageArra);
to
adapter.change(imageArra);
myPager.setAdapter(adapter);
Because when you set adapter, adapter's getCount will be called while you only assign the list after that.
Update
Here is some more notes that I think you should check:
make sure that imageArra is not empty and images path is correct.
You should add a fixed height for myfivepanelpager.
Don't store mContext in ViewPagerAdapter, you don't need that.
In instantiateItem: ImageView iv = new ImageView(mContext); don't use application Context, use container.getContext()
You don't need this new calc_stanica().execute(path, container, iv); because already use Glide
Change Bitmap bitmap = Glide.with(mContext).load(path).asBitmap().into(-1, -1).get();
//Bitmap bm = BitmapFactory.decodeFile(mPaths.get(position));
iv.setImageBitmap(bitmap); to
Glide.with(mContext).load(path).asBitmap().into(iv)
If you have issue that glide load not correct image, read this
((ViewPager) container).addView(iv, 0);, I'm not sure about this but I think it's should be ((ViewPager) container).addView(iv);

Images in gridview get replaced on scrolling

I have coded to display few images in gridview. The images are getting displayed from urls.
The problem i am facing is that the images get replaced when i scroll.. and the order of images keeps on changing once started.. this leads to delay in display of full image if i click on any image in grid..
Please help !
code :
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private TextView txtUrl;
private String response;
public ImageView imageView;
public static String[] mThumbIds;
public ImageAdapter(Context c,String resp) {
mContext = c;
response = resp.trim();
mThumbIds = resp.split(",");
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(95, 95));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(6, 6, 6, 6);
} else {
imageView = (ImageView) convertView;
}
try {
new LoadImageGrid(imageView).execute(mThumbIds[position]);
} catch(Exception e) {
txtUrl.setText("Error: Exception");
}
return imageView;
}
class LoadImageGrid extends AsyncTask<String, Void, Drawable>
{
ImageView imageView;
public LoadImageGrid(ImageView im){
imageView = im;
}
#Override
protected Drawable doInBackground(String... args) {
String url = args[0];
Drawable d = null;
try {
d = Drawable.createFromStream((InputStream) new URL(url).getContent(), "src");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return d;
}
#Override
protected void onPostExecute(Drawable d) {
imageView.setImageDrawable(d);
}
When you scroll your grid view, image views that are not visible returns to getView() as convertView parameter. But your asyncTask doesn't stop, and call
imageView.setImageDrawable(d);
leads to applying downloaded image to the view on wrong position. Because now you reuse the same imageView. Quick fix is not to use convertView. But it'll slow down your app a bit.
This seems to be related to convert view. When you reuse the space for an image using convert view then you should use the Imageview within that scope. I would suggest to find the imageview by its id within your current class code and then popultae it.

how to pass Bitmap array between 2 activities

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]);

fetching multiple image from urls

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

Gridview get image from JSON using AsyncTask

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;
}

Categories

Resources