Dynamically add images to Android WheelView - android

I have been working on this issue for days now. I am using the kankan Android wheel example/library, but am wanting to dynamically add images to the wheel when a button is pressed. The image added depends on the button's text. It seems like a fairly easy task, but perhaps I am missing something. I tried calling the adapter's notifyDataChangedEvent() after passing and adding the selected image to the adapter's list of cached images. Debugging has showed that the images were being added to the list of images, but they are not showing up on the wheel. If someone could please help me out with this problem I would appreciate it!
Code:
public void addItem(String text) {
for(Item c: Item.values()){
if(c.getName().equals(text)) {
slotMachineAdapter.addImage(c.getImage());
break;
}
}
slotMachineAdapter.notifyDataChangedEvent();
}
Adapter
private class SlotMachineAdapter extends AbstractWheelAdapter {
// Image size
final int IMAGE_WIDTH = 700;
final int IMAGE_HEIGHT = 150;
// Slot machine symbols
private final int items[] = new int[] {
R.mipmap.ic_flipper
};
// Cached images
private List<SoftReference<Bitmap>> images;
// Layout inflater
private Context context;
/**
* Constructor
*/
public SlotMachineAdapter(Context context) {
this.context = context;
images = new ArrayList<SoftReference<Bitmap>>();
for (int id : items) {
images.add(new SoftReference<Bitmap>(loadImage(id)));
}
}
/**
* Loads image from resources
*/
private Bitmap loadImage(int id) {
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), id);
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, IMAGE_WIDTH, IMAGE_HEIGHT, true);
bitmap.recycle();
return scaled;
}
#Override
public int getItemsCount() {
return items.length;
}
// Layout params for image view
final ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT);
#Override
public View getItem(int index, View cachedView, ViewGroup parent) {
ImageView img;
if (cachedView != null) {
img = (ImageView) cachedView;
} else {
img = new ImageView(context);
}
img.setLayoutParams(params);
SoftReference<Bitmap> bitmapRef = images.get(index);
Bitmap bitmap = bitmapRef.get();
if (bitmap == null) {
bitmap = loadImage(items[index]);
images.set(index, new SoftReference<Bitmap>(bitmap));
}
img.setImageBitmap(bitmap);
return img;
}
//Adds image to list of images
public void addImage(int img){
images.add(new SoftReference<Bitmap>(loadImage(img)));
}
}

Because the count you return referenced to items variable, But addImage function did not change items size. Try to change your code like below and test it again:
#Override
public int getItemsCount() {
return images.size();
}

Related

how to change image in Recycler View in android (like a radio button)?

I am having Recycler View. It's like a grid view. A total of 9 images in grid layout. If I click a image in any one of the above, that image have to change to an another image. If I click another image. Last one want to reset. Then the clicked image alone will change to highlighted image.
Here is my code...
holder.mLayout.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
//for (int i = 0; i < data_collection.size(); i++) {
holder.mLayout.setVisibility(View.VISIBLE);
holder.mHighLighted.setVisibility(View.GONE);
if (position == i) {
}
//}
holder.mLayout.setVisibility(View.GONE);
holder.mHighLighted.setVisibility(View.VISIBLE);
mHighLight.onHighLight(position, view);
}
});
Remove what you dont need.
#Override
public void onBindViewHolder(final SimpleViewHolder holder, final int position) {
holder.textView.setText(elements.get(position).getName());
holder.textView.setTypeface(typeface1);
CircularImageView circularImageView = (CircularImageView) holder.linearLayout.findViewById(R.id.personazhe_layout_grid_item_image);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// circularImageView.setBackground(elements.get(position).getPhoto());
// }
circularImageView.setImageDrawable(elements.get(position).getProfileImage());
//Picasso.with(context).load(elements.get(position).getProfileImage()).into(circularImageView);
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pos != position){
c.setImageDrawable(elements.get(position).getProfileImage());
t.setText(elements.get(position).getName());
seekBar.setProgress(0);
pos = position;
}
//image = elements.get(position).getProfileImage();
// textviews
// trajneri = elements.get(position).getTrajneri();
// mosha = elements.get(position).getMosha();
// vendbanimi = elements.get(position).getVendbanimi();
// vendlindja = elements.get(position).getVendlindja();
// arsimi = elements.get(position).getArsimi();
// name = elements.get(position).getName();
// surname = elements.get(position).getSurname();
// pos = elements.get(position).number();
// posi = position;
// button.performClick();
}
});
}
The ViewHolder pattern is something that Android pushed developers to use for a long time, and then (rightfully) forced on them with RecyclerViews. The idea, opposed to a simple ListView, is that you reuse as much of the view as possible when scrolling to reduce inflation and resource identification. The ViewHolder should be managed as something that is changed/not created within the RecyclerView.
Because of that, storing information in a ViewHolder that must be persistent will not work. For that, there are a plethora of other options. Let's go with an inner class that will manage holding onto the currently selected view position and its relative images.
Let's say we have a custom ViewHolder like below:
public class ImageViewHolder extends RecyclerView.ViewHolder{
private ImageView iv;
public ImageViewHolder(View v){
iv = (ImageView) v.findViewById(R.id.iv);
}
public ImageVie getImageView(){
return iv;
}
}
And utilizing that view holder is an adapter DemoAdapter, we can modify it to look something like this:
public class DemoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
public interface SelectionListener{
void onImageSelected(Bitmap bmp);
}
private static class SelectionHolder{
protected int position;
protected Bitmap originalBmp, newBmp;
public SelectionHolder(int position, Bitmap originalBmp,
Bitmap newBmp){
this.position = position;
this.originalBmp = originalBmp;
this.newBmp = newBmp
}
}
private SelectionHolder selectionHolder;
private SelectionListener selectionListener;
/*
Pre-existing Adapter functionality
*/
public void setSelectionListener(SelectionListener listener){
selectionListener = listener;
}
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
/*
Pre-existing onBindViewHolder code
*/
ImageView iv = holder.getImageView();
if(selectionHolder != null && selectionHolder.position == position)
iv.setImageBitmap(selectionHolder.newBmp);
else{
//set the image however you are doing it now
}
iv.setOnClickListener(
new new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageView iv = (ImageView) v;
// Get the IV's current bmp
Bitmap originalBmp = getBitmapFromImageView(iv);
// Get the currently selected image's "new" image
// if it is null, set it to the original bmp
// this will initialize our "highlighting"
Bitmap newBmp = selectionHolder == null || selectionHolder.newBmp == null?
originalBmp: selectoinHolder.newBmp;
// set the selection holder
selectionHolder = new SelectionHolder(position, originalBmp, newBmp);
// notify our listener
if(selectionListener != null)
selectionListener.onImageSelected(bmp);
// refresh the adapter
DemoAdapter.this.notifyDataSetChanged();
}
});
}
private Bitmap getBitmapFromImageView(ImageView iv){
return ((BitmapDrawable)(iv.getDrawable()).getBitmap()
}
}
Then if we have an activity that needs the selected image, perhaps to display it in an ImageView it hosts
recyclerAdapter = new DemoAdapter(...);
recyclerAdapter.setSelectionListener(new SelectionListener(){
#Override
public void onImageSelected(Bitmap bmp){
// set the bmp to your image view or whatever you want
}
}

Android Loading cached images into RecyclerView rearranges grid

I'm using Recycler View on my project. I'm generating pinterestlike multicolumn grid. Everything works fine. My application loads data from externalstorage (images too). When loading was in UI thread, scrolling performance was really poor. So I've decided to create AsyncTask to load images from path and this is warking grate while scrolling down. When I'm scrolling up again I have problem because recreating cells are messing with grid layout. It is rearranging and it can be poor for users. Caching images in memory (lot's of them) is not good Idea i think, są maybe it is an option to store information about ImageView sizes for every cell and keep it for reuse?
My RecyclerView Layout adapter looks like this:
public class MainGridAdapter extends RecyclerView.Adapter<ArticleViewHolder> {
private List<Article> articleList;
private Context context;
public MainGridAdapter(Context context, List<Article> articleList) {
this.articleList = articleList;
this.context = context;
}
#Override
public ArticleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.article_cell, null);
ArticleViewHolder avc = new ArticleViewHolder(layoutView);
return avc;
}
#Override
public void onBindViewHolder(ArticleViewHolder holder, final int position) {
Typeface StagMedium = Typeface.createFromAsset(context.getAssets(), "fonts/Stag-Medium.otf");
holder.articleTitle.setText(articleList.get(position).getTitle());
holder.articleTitle.setTypeface(StagMedium);
//Wczytuję obrazek
Log.v("DDD", articleList.get(position).getTitle());
Log.v("DDD", String.valueOf(articleList.get(position).getId()));
//TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, articleList.get(position).getCover_height());
//holder.container.setLayoutParams(params);
BitmapWorkerTask task = new BitmapWorkerTask(holder.articleImage);
task.execute(articleList.get(position).getCover_local_path());
/*
File file = new File(articleList.get(position).getCover_local_path());
if(file.exists()) {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), bmOptions);
holder.articleImage.setImageBitmap(bitmap);
}
*/
//Jeżeli materiał to video to pokazuję ikonkę
Log.v("DDD", "Type: " + articleList.get(position).getType());
if(articleList.get(position).getType().equals("article")) {
Log.v("DDD", "Article");
holder.articleVideoIcon.setImageResource(android.R.color.transparent);
} else {
Log.v("DDD", "Video");
holder.articleVideoIcon.setImageResource(R.drawable.play);
}
holder.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("DDD", "Klikłem sobie na pozycję: " + String.valueOf(position));
Intent intent= new Intent(context,SingleArticle.class);
Log.v("DDD", String.valueOf(articleList.get(position).getId()));
intent.putExtra("articleId", articleList.get(position).getId());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return articleList.size();
}
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private String path = "";
public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
}
// Decode image in background.
#Override
protected Bitmap doInBackground(String... params) {
path = params[0];
File file = new File(path);
if (file.exists()) {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(),bmOptions);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
//Bitmap resized_bitmap = Bitmap.createScaledBitmap(bitmap, Math.round(width / 2), Math.round(height / 2), false);
//return resized_bitmap;
return bitmap;
} else {
return null;
}
}
// Once complete, see if ImageView is still around and set bitmap.
#Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
}
Ok I've solved my problem. The thing is that API, and datastructure are also my code, so I've started to store in SQLite thimbs sizes. In this way I can set cell size in "OnBindViewHolder" like this:
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, articleList.get(position).getCover_height());
holder.container.setLayoutParams(params);
You can also download Bitmap, and store height in List or array and do the same. Ofcourse height of the container should be converted to dp but it is working like a charm. The problem with floating items is solved. Thx for help :)

Expanding an image from a thumbnail in a GridView

So I have a simple application in which I am taking an image with the camera and then loading the images into a GridView, when I click on the GridView it must open a bigger version of that image. I cannot get the image to open bigger.
The problem is that I have no reference to that image when passing it to the Activity which makes the image bigger. Code is below.
MainActivity.java
protected static final String EXTRA_RES_ID = "POS";
private ArrayList<String> mThumbIdsSelfies = new ArrayList<String>();
if(populateArrayList())
{
GridView gridview = (GridView) findViewById(R.id.gridview);
// Create a new ImageAdapter and set it as the Adapter for this GridView
gridview.setAdapter(new ImageAdapter(this, mThumbIdsSelfies));
// Set an setOnItemClickListener on the GridView
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v,
int position, long id)
{
//Create an Intent to start the ImageViewActivity
Intent intent = new Intent(MainActivity.this, ImageViewActivity.class);
// Add the ID of the thumbnail to display as an Intent Extra
intent.putExtra(EXTRA_RES_ID, (int) id);
// Start the ImageViewActivity
startActivity(intent);
}
});
}
private boolean populateArrayList()
{
File dir = getAlbumDir();
//Bitmap myBitmap;
if (dir.isDirectory())
{
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++)
{
//myBitmap = BitmapFactory.decodeFile(files[i].toString());
mThumbIdsSelfies.add(files[i].toString());
}
}
return true;
}
ImageViewActivity.java - This is the one that makes the image bigger
public class ImageViewActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Get the Intent used to start this Activity
Intent intent = getIntent();
// Make a new ImageView
ImageView imageView = new ImageView(getApplicationContext());
// Get the ID of the image to display and set it as the image for this ImageView
imageView.setImageResource(intent.getIntExtra(MainActivity.EXTRA_RES_ID, 0));
setContentView(imageView);
}
}
ImageAdapter.java
public class ImageAdapter extends BaseAdapter
{
private static final int PADDING = 8;
private static final int WIDTH = 250;
private static final int HEIGHT = 250;
private Context mContext;
private List<String> mThumbIds;
// Store the list of image IDs
public ImageAdapter(Context c, List<String> ids)
{
mContext = c;
this.mThumbIds = ids;
}
// Return the number of items in the Adapter
#Override
public int getCount()
{
return mThumbIds.size();
}
// Return the data item at position
#Override
public Object getItem(int position)
{
return mThumbIds.get(position);
}
// Will get called to provide the ID that
// is passed to OnItemClickListener.onItemClick()
#Override
public long getItemId(int position)
{
return mThumbIds.indexOf(position);
}
// Return an ImageView for each item referenced by the Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView = (ImageView) convertView;
// if convertView's not recycled, initialize some attributes
if (imageView == null)
{
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(WIDTH, HEIGHT));
imageView.setPadding(PADDING, PADDING, PADDING, PADDING);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
//imageView.setImageResource(mThumbIds.get(position));
Bitmap b = BitmapFactory.decodeFile(mThumbIds.get(position));
imageView.setImageBitmap(b);
return imageView;
}
}
So the problem with the above function is that I cannot use getItemId as it does not return a long, rather it returns a string and I have no way of getting something useful from it.
The other thing I have tried is passing the bitmap image as an extra in my bundle and reading it on the other side, still I have no luck in getting the actual image to display.
I finally figured this out, so here is what I did.
MainActivity.java - Changed the following line
intent.putExtra(EXTRA_RES_ID, mThumbIdsSelfies.get(position)/*(int) id*/);
ImageViewActivity.java
String s = intent.getStringExtra(MainActivity.EXTRA_RES_ID);
Bitmap bitmap = BitmapFactory.decodeFile(s);
imageView.setImageBitmap(bitmap);
So those changes finally helped me, all I had to do was pass a string reference to the file location of the thumbnail I just clicked on. Then in the Activity that enlarges that image, I had to get that string reference and generate a bitmap out of it and then set that bitmap to the imageView.
Assuming that mThumbIdsSelfies is an ArrayList of the image paths you can use this:
Intent intent = new Intent(MainActivity.this, ImageViewActivity.class);
intent.putExtra(EXTRA_RES_ID, mThumbIdsSelfies[position]);
startActivity(intent);
Then retrieve it in your Activity(ImageViewActivity) and use it as you do in your adapter's getView() method.

Android Gridview not obeying vertical spacing

My code produces gridview with only horizontal spacing but no vertical spacing. Can't find the problem even after searching google. I only get the vertical spacing if i add padding to the imageview, but it doesn't give me the required spacing. Here is my code, i use universal image loader:
public PhotoGridFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get the individual image size in the grid and the grid image spacing
mImageThumbSize = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);
mImageThumbSpacing = getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.empty_photo)
.showImageForEmptyUri(R.drawable.empty_photo)
.showImageOnFail(R.drawable.empty_photo)
.cacheInMemory(true)
.cacheOnDisk(true)
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
mAdapter = new ImageAdapter(getActivity());
if(((MainActivity)getActivity()).isRunningFirstTime) {
}
}
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.photo_grid_fragment, container, false);
final GridView mGridView = (GridView) v.findViewById(R.id.gridview);
mGridView.setAdapter(mAdapter);
mGridView.setOnItemClickListener(this);
mGridView.setOnScrollListener(new PauseOnScrollListener(ImageLoader.getInstance(), false, true));
// This listener is used to get the final width of the GridView and then calculate the
// number of columns and the width of each column. The width of each column is variable
// as the GridView has stretchMode=columnWidth. The column width is used to set the height
// of each view so we get nice square thumbnails.
mGridView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#SuppressWarnings("deprecation")
#TargetApi(VERSION_CODES.JELLY_BEAN)
#Override
public void onGlobalLayout() {
if (mAdapter.getNumColumns() == 0) {
final int numColumns = (int) Math.floor(
mGridView.getWidth() / (mImageThumbSize + mImageThumbSpacing));
if (numColumns > 0) {
final int columnWidth =
(mGridView.getWidth() / numColumns) - mImageThumbSpacing;
columnNum = numColumns;
mAdapter.setNumColumns(numColumns);
mAdapter.setItemHeight(columnWidth);
if (Utils.hasJellyBean()) {
mGridView.getViewTreeObserver()
.removeOnGlobalLayoutListener(this);
} else {
mGridView.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
}
}
}
});
return v;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#TargetApi(VERSION_CODES.JELLY_BEAN)
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
final Intent i = new Intent(getActivity(), PhotoDetailActivity.class);
i.putExtra(PhotoDetailActivity.EXTRA_IMAGE, (photoIds[position - columnNum]));
if (Utils.hasJellyBean()) {
// makeThumbnailScaleUpAnimation() looks kind of ugly here as the loading spinner may
// show plus the thumbnail image in GridView is cropped. so using
// makeScaleUpAnimation() instead.
ActivityOptions options =
ActivityOptions.makeScaleUpAnimation(v, 0, 0, v.getWidth(), v.getHeight());
getActivity().startActivity(i, options.toBundle());
} else {
startActivity(i);
}
}
public int getCurTab() {
return getArguments().getInt(CURRENT_TAB);
}
public static PhotoGridFragment newInstance(int position, int curTab) {
PhotoGridFragment photoGrid = new PhotoGridFragment();
Bundle categoryId = new Bundle();
categoryId.putInt(CATEGORY_ID, position);
categoryId.putInt(CURRENT_TAB, curTab);
photoGrid.setArguments(categoryId);
return photoGrid;
}
/**
* The main adapter that backs the GridView. This is fairly standard except the number of
* columns in the GridView is used to create a fake top row of empty views as we use a
* transparent ActionBar and don't want the real top row of images to start off covered by it.
*/
private class ImageAdapter extends BaseAdapter {
private final Context mContext;
private int mItemHeight = 0;
private int mNumColumns = 0;
private GridView.LayoutParams mImageViewLayoutParams;
public ImageAdapter(Context context) {
super();
mContext = context;
mImageViewLayoutParams = new GridView.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
}
#Override
public int getCount() {
// If columns have yet to be determined, return no items
if (getNumColumns() == 0) {
return 0;
}
// Size + number of columns for top empty row
return photoIds.length;
}
#Override
public Object getItem(int position) {
return photoIds[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return 1;
}
#Override
public View getView(int position, View convertView, ViewGroup container) {
// Now handle the main ImageView thumbnails
ImageView imageView;
if (convertView == null) { // if it's not recycled, instantiate and initialize
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(mImageViewLayoutParams);
} else { // Otherwise re-use the converted view
imageView = (ImageView) convertView;
}
if ((imageView.getLayoutParams().height != mItemHeight)
|| (imageView.getLayoutParams().width != mItemHeight))
{
imageView.setLayoutParams(mImageViewLayoutParams);
}
// Finally load the image asynchronously into the ImageView, this also takes care of
// setting a placeholder image while the background thread runs
ImageLoader.getInstance()
.displayImage(photoIds[position], imageView, options);
return imageView;
//END_INCLUDE(load_gridview_item)
}
/**
* Sets the item height. Useful for when we know the column width so the height can be set
* to match.
*
* #param height
*/
public void setItemHeight(int height) {
if (height == mItemHeight) {
return;
}
mItemHeight = height;
mImageViewLayoutParams =
new GridView.LayoutParams(mItemHeight, mItemHeight);
notifyDataSetChanged();
}
public void setNumColumns(int numColumns) {
mNumColumns = numColumns;
}
public int getNumColumns() {
return mNumColumns;
}
}
}
Gridview xml:
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="#dimen/image_thumbnail_size"
android:horizontalSpacing="#dimen/image_thumbnail_spacing"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="#dimen/image_thumbnail_spacing"
android:drawSelectorOnTop="true"
android:listSelector="#drawable/photogrid_list_selector" />
Spent 6 hours trying to find the problem. Now i have the solution. The problem was the 1dp spacing was not showing on ldpi devices but was showing on mdpi, xhdpi, etc. I just created a "values-ldpi" folder and create a dimens.xml folder then added the dimension image_thumbnail_spacing and assigned it to 2dp and its working now. Thanks

Android - Images from Assets folder in a GridView

I have been working on creating a Grid View of images, with images being present in the Assets folder. Opening a File from assets folder in android link helped me with using the bitmap to read it. The code am currently having is:
public View getView(final int position, View convertView, ViewGroup parent)
{
try
{
AssetManager am = mContext.getAssets();
String list[] = am.list("");
int count_files = imagelist.length;
for(int i= 0;i<=count_files; i++)
{
BufferedInputStream buf = new BufferedInputStream(am.open(list[i]));
Bitmap bitmap = BitmapFactory.decodeStream(buf);
imageView.setImageBitmap(bitmap);
buf.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
My application does read the image from the Assets folder, but it is not iterating through the cells in the grid view. All the cells of the grid view have a same image picked from the set of images. Can anyone tell me how to iterate through the cells and still have different images ?
I have the above code in an ImageAdapter Class which extends the BaseAdapter class, and in my main class I am linking that with my gridview by:
GridView gv =(GridView)findViewById(R.id.gridview);
gv.setAdapter(new ImageAdapter(this, assetlist));
Thanks a lot for any help in advance,
Saran
Saran, below is what I use to show images in the assets folder with the gallery. I imagine it's the same deal with a gridview:
public class myActivitye extends Activity
{
private Gallery mGallery;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mGallery = (Gallery) findViewById(R.id.mygalleryinxml);
//load images into memory
mBitArray = new Bitmap[4];
try
{
//these images are stored in the root of "assets"
mBitArray[0] = getBitmapFromAsset("pic1.png");
mBitArray[1] = getBitmapFromAsset("pic2.png");
mBitArray[2] = getBitmapFromAsset("pic3.png");
mBitArray[3] = getBitmapFromAsset("pic4.png");
}
catch (IOException e)
{
e.printStackTrace();
}
mGallery.setAdapter(new GalleryAdapter(this, mBitArray));
}
public class GalleryAdapter extends BaseAdapter
{
//member variables
private Context mContext;
private Bitmap[] mImageArray;
//constructor
public GalleryAdapter(Context context, Bitmap[] imgArray)
{
mContext = context;
mImageArray = imgArray;
}
public int getCount()
{
return mImageArray.length;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
//returns the individual images to the widget as it requires them
public View getView(int position, View convertView, ViewGroup parent)
{
final ImageView imgView = new ImageView(mContext);
imgView.setImageBitmap(mImageArray[position]);
//put black borders around the image
final RelativeLayout borderImg = new RelativeLayout(mContext);
borderImg.setPadding(20, 20, 20, 20);
borderImg.setBackgroundColor(0xff000000);//black
borderImg.addView(imgView);
return borderImg;
}
}//end of: class GalleryAdapter
/**
* Helper Functions
* #throws IOException
*/
private Bitmap getBitmapFromAsset(String strName) throws IOException
{
AssetManager assetManager = getAssets();
InputStream istr = assetManager.open(strName);
Bitmap bitmap = BitmapFactory.decodeStream(istr);
istr.close();
return bitmap;
}
}
No need to read all the items every time. Read only the item at the position given in getView method call. And display only that item that time.
BufferedInputStream buf = new BufferedInputStream(am.open(list[position]));

Categories

Resources