GridView only lists first image in directory - android

I am trying to display all images in a certain directory in a GridView, but only the first image is being displayed. Here is what I'm using:
In onCreate:
iconGrid = (GridView) findViewById(R.id.iconGrid);
getImageFiles();
iconGrid.setAdapter(new ImageAdapter(this));
getImageFiles():
public void getImageFiles() {
File dir = new File(Environment.getExternalStorageDirectory(), "img");
if (dir.isDirectory())
for (File f : dir.listFiles())
for (String ext : IMAGE_EXTENSIONS)
if (f.getName().toLowerCase().endsWith(ext)) {
Log.d(f.toString(), "Adding file");
files.add(f.getAbsolutePath());
}
}
imageAdapter()
public class ImageAdapter extends BaseAdapter {
private Context context;
public ImageAdapter(Context context) {
this.context = context;
}
public int getCount () {
return files.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("", "Getting image " + files.get(position).toString());
ImageView c;
if (convertView == null) {
c = new ImageView(context);
c.setLayoutParams(new GridView.LayoutParams(160, 160));
c.setScaleType(ImageView.ScaleType.CENTER_CROP);
c.setPadding(8,8,8,8);
} else {
c = (ImageView) convertView;
}
Bitmap myBitmap = BitmapFactory.decodeFile(files.get(position));
c.setImageBitmap(myBitmap);
return c;
}
}
With the logging in place, it seems that getView() is never called for positions that aren't 0, and each file is being added to the list, with the list size being the correct number of files. Why is this occurring?

Everything was being added to GridView, it just wasn't visible without scrolling down and changing the number of columns.

Related

Gridview of image from sdcard directory

I want show image in gridview from sdcard directory.i use this code.But when i load image by type : bitmap.getView in gridview adapter need Integer[] array.how i can fix it?
public class LoadPic extends Activity {
Integer[] imageIDs = {
R.drawable.user,
R.drawable.user,
R.drawable.user,
R.drawable.user,
R.drawable.user,
R.drawable.user,
R.drawable.user
};
int numberOfImages=0;
Bitmap[] m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.load_pic);
Intent gett = getIntent();
String _area = gett.getStringExtra("area");
String _domain = gett.getStringExtra("domain");
String _block = gett.getStringExtra("block");
String _melk = gett.getStringExtra("melk");
String _build = gett.getStringExtra("build");
String _apar = gett.getStringExtra("apar");
String _senfi = gett.getStringExtra("senfi");
File dir = new File(Environment.getExternalStorageDirectory()
+ "/momayezi/"+_area+"-"+_domain+"-"+_block+"-"+_melk+"-"+_build+"-"+_apar+"-"+_senfi);
File[] files = dir.listFiles();
numberOfImages=files.length;
for (int i=1;i<=numberOfImages;i++)
{
File img = new File("/sdcard/momayezi/"+_area+"-"+_domain+"-"+_block+"-"+_melk+"-"+_build+"-"+_apar+"-"+_senfi+"/pic"+i+".png");
if(img.exists())
{
Bitmap bit = BitmapFactory.decodeFile(img.getAbsolutePath());
}
}
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View v, int position, long id) {
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected",
Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
context = c;
}
//---returns the number of images---
public int getCount() {
return numberOfImages;
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(185, 185));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(7, 7, 7, 7);
} else {
imageView = (ImageView) convertView;
}
/**/
imageView.setImageResource(imageIDs[position]);
/**/
return imageView;
}
}
}
please help how i can use image in this class(adapter).
If you want to show images from sdcard into your grid view use any imageloader library
Universal Image Loader
https://github.com/nostra13/Android-Universal-Image-Loader
then you need to create a string array or a model class instead of that integer array.
Please refer the below tutorials.
http://wptrafficanalyzer.in/blog/loading-thumbnail-images-in-a-gridview-and-opening-original-images-in-alertdialog-using-media-content-providers/
replace
public int getCount() {
return numberOfImages;
}
with
public int getCount() {
return imageIDs.length();
}
First properly explain what do want to set Drawable or Bitmap?
If Bitmap then this is how you should set bitmap(make a list of bitmaps and then):
imageView.setImageBitmap(bitmaps[position]);
if Drawable then(make list of drawable id's)
imageview.setImageResource(drawables[position]);
This is how make bitmap list:
ArrayList<Bitmap> bitmaps = new ArrayList<Bitmap>();
File dir = new File(Environment.getExternalStorageDirectory()
+ "/momayezi/"+_area+"-"+_domain+"-"+_block+"-"+_melk+"-"+_build+"-"+_apar+"-"+_senfi);
File[] files = dir.listFiles();
numberOfImages=files.length;
for (int i=1;i<=numberOfImages;i++)
{
File f = new File("/sdcard/momayezi/"+_area+"-"+_domain+"-"+_block+"-"+_melk+"-"+_build+"-"+_apar+"-"+_senfi+"/pic"+i+".png");
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
if(bmp!=null){
bitmaps.add(bmp);
}
}

Unable to refresh the gridview in android using notify dataset changed

I am creating an android application in which there is a scenario where i have to add new items to the grid i am using an layout inflater to add new items to the grid the items gets added to the database sucessfully but the grid view is not refreshed once the item is added i have used notify dataset changed but it is not working can anyone tell me what i have to change in the existing code
Activity for the gridview:
listet = databaseHandlerOtherchgs.getAllproducttitle();
listet.add(new OtherChargesType("Plucking", bitMapData));
listet.add(new OtherChargesType("Loading", bitMaploading));
listet.add(new OtherChargesType("Add New", bitMapaddnew));
listcharges = new ArrayList<CustomizedCharge>());
adapter = new OtherChargesGridAdpater(SinglePageTransaction.this, listet);
gv.setAdapter(adapter);
gv.setExpanded(true);
GridAdapter:
public class OtherChargesGridAdpater extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<OtherChargesType> otherchargestypes;
DatabaseHandlerOtherChgs databaseHandlerOtherchgs;
public OtherChargesGridAdpater(Activity activity, List<OtherChargesType> otherchargestypes) {
this.activity = activity;
this.otherchargestypes = otherchargestypes;
}
#Override
public int getCount() {
return otherchargestypes.size();
}
#Override
public Object getItem(int i) {
return otherchargestypes.get(i);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertview, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertview == null) {
convertview = inflater.inflate(R.layout.row_othercharges_griditem, null);
}
OtherChargesType m = otherchargestypes.get(position);
byte[] outImage = m.getImage();
ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
final Bitmap theImage = BitmapFactory.decodeStream(imageStream);
ImageView otherimages = (ImageView) convertview.findViewById(R.id.imageView1);
final TextView typename = (TextView) convertview.findViewById(R.id.textView1);
databaseHandlerOtherchgs=new DatabaseHandlerOtherChgs(activity);
// getting movie data for the row
typename.setText(m.getTypename());
otherimages.setImageBitmap(theImage);
notifyDataSetChanged();
return convertview;
}
public void updatedata(){
DatabaseHandlerOtherChgs databaseHandlerOtherChgs =new DatabaseHandlerOtherChgs(activity);
databaseHandlerOtherChgs.getAllproducttitle();
this.notifyDataSetChanged();
}
}
Use This code in Activity.. This code store your data.
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("MSG", "This is my message to be reloaded");
super.onSaveInstanceState(outState);
}
In Oncreate Method put this code
if (savedInstanceState != null) {
String str= savedInstanceState.getString("MSG");
Toast.makeText(this, str, Toast.LENGTH_LONG).show();
}
And for refresh your activity use follow code
finish();
startActivity(getIntent());
Make Changes as per your requirement.

Show Image in listview, if file specific file is downloaded internal storage

I am working on a project. In my project when user clicks on a list item, it downloads a file from some source and saves it into internal storage.
I want to show an image in list items of listview if file is already download.
The code below is working fine but it is also showing image for the list items whose file is yet not downloaded.
Here is my adapter class code.
package life.quran.com.quranlife;
public class SurahBaseSearchAdapter extends BaseAdapter {
Context mContext;
LayoutInflater mInflator;
private List<Surah> surahList = null;
private ArrayList<Surah> arrayList;
Surah surah;
ArrayList<String> imgfileLocation = null;
String searchhighlightString = "";
public SurahBaseSearchAdapter(Context context, List<Surah> list) {
mContext = context;
surahList = list;
mInflator = LayoutInflater.from(context);
arrayList = new ArrayList<Surah>();
arrayList.addAll(surahList);
}
public class ViewHolder {
TextView sname;
TextView sno;
ImageView dlimg;
}
#Override
public int getCount() {
return surahList.size();
}
#Override
public Object getItem(int position) {
return surahList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
imgfileLocation = new ArrayList<>();
surah = surahList.get(position);
File f = mContext.getFilesDir();
String filepath = f.getAbsolutePath();
File _file = new File(filepath+"/surah_"+surah.getSurah_id()+".json");
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflator.inflate(R.layout.item_template,null);
holder.sname = (TextView) convertView.findViewById(R.id.txt_surahName);
holder.sno = (TextView) convertView.findViewById(R.id.txtsuraNo);
holder.dlimg = convertView.findViewById(R.id.dlimg);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.sname.setText(surah.getSurah_name());
holder.sno.setText(surah.getSurah_no());
if (_file.exists()) {
holder.dlimg.setImageResource(R.drawable.newdlimg);
}
String hSurahName = surah.getSurah_name().toLowerCase(Locale.getDefault());
if(hSurahName.contains(searchhighlightString)) {
int startpos = hSurahName.indexOf(searchhighlightString);
int endpos = startpos + searchhighlightString.length();
Spannable spanText = Spannable.Factory.getInstance().newSpannable(holder.sname.getText());
spanText.setSpan(new ForegroundColorSpan(Color.BLUE),startpos,endpos,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.sname.setText(spanText,TextView.BufferType.SPANNABLE);
}
return convertView;
}
public void filter(String charText) {
searchhighlightString = charText;
charText = charText.toLowerCase(Locale.getDefault());
surahList.clear();
if(charText.length() == 0) {
surahList.addAll(arrayList);
} else {
for(Surah surah : arrayList) {
if(surah.getSurah_name().toLowerCase(Locale.getDefault()).contains(charText)) {
surahList.add(surah);
}
}
}
notifyDataSetChanged();
}
}
Let me know if anything is unclear
You require to set default drawable if file not exist condition. Add else part to this if condition like
if (_file.exists()) {
holder.dlimg.setImageResource(R.drawable.newdlimg);
}else{
holder.dlimg.setImageResource(R.drawable.<default_image>);
}
You should clear image in ViewHolder after previous usage. Just change your code to something like this:
if (_file.exists()) {
holder.dlimg.setImageResource(R.drawable.newdlimg);
} else {
//clear image from previous usage
//do not sure is it legal to set null. You need to check it.
holder.dlimg.setImageResource(null)
}

Delete item from gridview

I know that here are many answers how to delete items, but I can't make it work. It show errors. Can you look? I added in adapter remove(position), but I think it works wrongly.
So I want after using onItemLongClickListener to delete file and its thumbnail too.
Main:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final GridView grid = (GridView) findViewById(R.id.gridview);
final ThumbnailAdapter thumbnails = new ThumbnailAdapter(this);
grid.setAdapter(thumbnails);
grid.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View v, int position,
long id) {
final String imgPath = thumbnails.getImagePath(position);
File file = new File(imgPath);
file.delete();
thumbnails.remove(position);
thumbnails.notifyDataSetChanged();
grid.invalidateViews();
grid.setAdapter(thumbnails);
return true;
}
});
Adapter:
public class ThumbnailAdapter extends BaseAdapter {
// Context required for performing queries
private final Context mContext;
// Cursor for thumbnails
private final Cursor cursor;
private final int imgId;
private final int imgData;
private final int count;
public ThumbnailAdapter(Context c) {
this.mContext = c;
// Get list of all images, sorted by last taken first
final String[] projection = {
MediaStore.Images.Media._ID,
MediaStore.Images.Media.DATA
};
cursor = mContext.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
MediaStore.Images.Media.DATE_TAKEN + " DESC"
);
imgId = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
imgData = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
count = cursor.getCount();
Log.d("ThumbnailAdapter", count + " images found");
}
#Override
public int getCount() {
return count;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
} else {
imageView = (ImageView) convertView;
}
cursor.moveToPosition(position);
final Bitmap thumbnail = MediaStore.Images.Thumbnails.getThumbnail(
mContext.getContentResolver(),
cursor.getInt(imgId),
MediaStore.Images.Thumbnails.MICRO_KIND,
null
);
imageView.setImageBitmap(thumbnail);
Log.d("ThumbnailAdapter", "render: " + cursor.getString(imgData));
return imageView;
}
public String getImagePath(int position) {
cursor.moveToPosition(position);
return cursor.getString(imgData);
}
public void remove(int position) {
remove(position);
notifyDataSetChanged();
}
}
I guess its stack overflow. your remove method in the adapter is recursive forever.
Instead of deleting file youself ask content resolver to remove it. and the reload data.
you dont have to call grid.setAdapter(thumbnails) again in the click listner
Check this line please though :
file.delete();
thumbnails.remove(position);
You are deleting your file first and then removing it from adapter. It should be other way around. You reset your adapter then delete the actual file. Your thumbnail is deleted while still being attached to the adapter.

how to display video thumbnails?

i am trying to show my arraylist value in my tablayout. now i am successfully passed two values in my two tabhost it's working. i have three tabhost 2tab host working fine. so i am trying show my stored path value video thumb. how to show my stored path value to video thumb nail? i am trying to show but i am getting error
error is:
The type of the expression must be an array type but it resolved to ArrayList<String>
line:
imgVw.setImageBitmap(getImage(tabview.videoList[position]));
full source code:
public class video extends Activity {
//set constants for MediaStore to query, and show videos
//flag for which one is used for images selection
private Gallery _gallery;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mavideo);
//set GridView for gallery
_gallery = (Gallery) findViewById(R.id.videoGrdVw);
//set gallery adapter
setGalleryAdapter();
}
private void setGalleryAdapter() {
_gallery.setAdapter(new VideoGalleryAdapter(this));
}
//
private class VideoGalleryAdapter extends BaseAdapter
{private Context mContext;
public VideoGalleryAdapter(Context c)
{
mContext = c;
}
public int getCount()
{
return tabview.videoList.size();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imgVw= new ImageView(mContext);;
try
{
if(convertView!=null)
{
imgVw= (ImageView) convertView;
}
imgVw.setImageBitmap(getImage(tabview.videoList[position]));
imgVw.setLayoutParams(new Gallery.LayoutParams(96, 96));
imgVw.setPadding(8, 8, 8, 8);
}
catch(Exception ex)
{
System.out.println("StartActivity:getView()-135: ex " + ex.getClass() +", "+ ex.getMessage());
}
return imgVw;
}
// Create the thumbnail on the fly
private Bitmap getImage(int id) {
Bitmap thumb = MediaStore.Video.Thumbnails.getThumbnail(
getContentResolver(),
id, MediaStore.Video.Thumbnails.MICRO_KIND, null);
return thumb;
}
}
}
note:
parxmlactivity.java this is my main class here i am passing my value using below code:
sdcardImages.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Intent intent = new Intent(ParxmlActivity.this, tabview.class);
intent.putExtra("spec",model_List.get(position).spec);
intent.putStringArrayListExtra("imageList", model_List.get(position).imageList);
intent.putStringArrayListExtra("videoList", model_List.get(position).videoList);
startActivity(intent);
}
});
and i am getting this passed value in below code in tabview.java class file:
tab_intent=tabview.this.getIntent().getExtras();
spec=tab_intent.getString("spec");
imageList = tab_intent.getStringArrayList("imageList");
videoList = tab_intent.getStringArrayList("videoList");

Categories

Resources