FileNotFoundException using Universal Image Loader - android

This is my first app on Android and I am using the Universal Image Loader Library to load images into a GridView.
The problem I am having is
FileNotFoundException: No entry for content://media/external/images/thumbnails/...(all thumbnails )
The thumbnails are not loaded in the GridView, but when I tap on a gridItem, the Intent is started and an imageId is passed to the next activity.
Here is the code I am using (based on the Sample example at UIL( github)
public class ImageGridFragment extends AbsListViewBaseFragment {
Cursor mCursor;
int[]imageIDs;
String bucket;
ArrayList<String> imageUrls;
int firstImageIndex;
int lastImageIndex;
int columnIndex;
String sender;
DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getActivity().getIntent();
sender = intent.getExtras().getString("sender");
bucket = intent.getExtras().getString("albumName");
imageIDs = getImagesFromBucket();
imageUrls = new ArrayList<>();
for(int i = 0; i < imageIDs.length; i++){
int imageID = imageIDs[i];
Uri imageURI = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
imageUrls.add(imageURI.toString());
}
BitmapFactory.Options resizeOptions = new BitmapFactory.Options();
resizeOptions.inSampleSize = 3; // decrease size 3 times
resizeOptions.inScaled = true;
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.decodingOptions(resizeOptions)
.postProcessor(new BitmapProcessor() {
#Override
public Bitmap process(Bitmap bmp) {
return Bitmap.createScaledBitmap(bmp, 120, 120, false);
}
})
.build();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_gallery_grid_view, container, false);
listView = (GridView) rootView.findViewById(R.id.gridView);
listView.setAdapter(new ImageAdapter());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent returnToSender;
if (sender.equals("First")) {
returnToSender = new Intent(ImageGridFragment.this.getActivity(), FirstImageActivity.class);
firstImageIndex = 0;
returnToSender.putExtra("firstImageIndex", firstImageIndex);
// Move cursor to current position
mCursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = mCursor.getInt(columnIndex);
Uri imageURI = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imageID);
returnToSender.putExtra("imageURI", imageURI);
String comingFrom = "gridView";
returnToSender.putExtra("comingFrom", comingFrom);
mCursor.close();
returnToSender.putExtra("albumName", bucket);
} else {
returnToSender = new Intent(ImageGridFragment.this.getActivity(), LastImageActivity.class);
lastImageIndex = 0;
returnToSender.putExtra("lastImageIndex", lastImageIndex);
}
startActivity(returnToSender);
}
});
return rootView;
}
private int[] getImagesFromBucket()
{
int[] ids = null;
ArrayList<Integer> lstIds = new ArrayList<>();
String searchParams;
if(bucket != null)
{
searchParams = "bucket_display_name = \""+bucket+"\"";
}
else
{
return ids;
}
String[] projection = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DATE_TAKEN};
String orderBy = MediaStore.Images.Media.DATE_TAKEN + " DESC";
mCursor = getActivity().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
searchParams,
null,orderBy);
if(mCursor.moveToFirst())
{
do
{
int id = mCursor.getInt(mCursor.getColumnIndex(MediaStore.Images.Media._ID));
lstIds.add(id);
}
while(mCursor.moveToNext());
}
ids = new int[lstIds.size()];
for(int i=0;i<ids.length;i++)
{
ids[i] = lstIds.get(i);
}
return ids;
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater inflater;
ImageAdapter() {
inflater = LayoutInflater.from(getActivity());
}
#Override
public int getCount() {
return imageUrls.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.item_grid_image, parent, false);
holder = new ViewHolder();
assert view != null;
holder.imageView = (ImageView) view.findViewById(R.id.gridImageView);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
ImageLoader.getInstance()
.displayImage(imageUrls.get(position), holder.imageView, options, new SimpleImageLoadingListener() {
});
return view;
}
}
static class ViewHolder {
ImageView imageView;
}
}
Any help with understanding what I am doing wrong and how to fix it would be greatly appreciated.

SOLVED!
I changed this line
Uri imageURI = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
to
Uri imageURI = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + imageID);

If your path having filename with extension like .png, .jpg or any than it is file path, in such case you have to add string as
"file://"+ filename.
And if your path not having any extension and not web url, so it is content uri, here you have to add
"content://"+filename.
For more click here.

Related

Retrieve all images directories in android

I have tried this to get directories and load images from them but it is very slow to load images and when camera is selected it crashed after some time...
< -------- Code to get directories and images from them ------- >
public static ArrayList<String> getImageBuckets(Context mContext){
ArrayList<String> buckets = new ArrayList<>();
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String [] projection = {MediaStore.Images.Media.BUCKET_DISPLAY_NAME, MediaStore.Images.Media.DATA};
Cursor cursor = mContext.getContentResolver().query(uri, projection, null, null, null);
if(cursor != null){
File file;
while (cursor.moveToNext()){
String bucketPath = cursor.getString(cursor.getColumnIndex(projection[0]));
String fisrtImage = cursor.getString(cursor.getColumnIndex(projection[1]));
file = new File(fisrtImage);
if (file.exists() && !buckets.contains(bucketPath)) {
buckets.add(bucketPath);
}
}
cursor.close();
}
return buckets;
}
public static ArrayList<String> getImagesByBucket(Context mContext , #NonNull String bucketPath){
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String [] projection = {MediaStore.Images.Media.DATA};
String selection = MediaStore.Images.Media.BUCKET_DISPLAY_NAME+" =?";
String orderBy = MediaStore.Images.Media.DATE_ADDED+" DESC";
ArrayList<String> images = new ArrayList<>();
Cursor cursor = mContext.getContentResolver().query(uri, projection, selection,new String[]{bucketPath}, orderBy);
if(cursor != null){
File file;
while (cursor.moveToNext()){
String path = cursor.getString(cursor.getColumnIndex(projection[0]));
file = new File(path);
if (file.exists() && !images.contains(path)) {
images.add(path);
}
}
cursor.close();
}
return images;
}
< ---------- Here is adapter and method to select directory --------->
<--------------------Adapter------------------>
public class GridImageAdapter extends ArrayAdapter<String> {
private Context mContext;
private LayoutInflater mInflater;
private int layoutResource;
private String mAppend;
private ArrayList<String> imgURLs;
public GridImageAdapter(Context context, int layoutResource, String append, ArrayList<String> imgURLs) {
super(context, layoutResource, imgURLs);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mContext = context;
this.layoutResource = layoutResource;
mAppend = append;
this.imgURLs = imgURLs;
}
#Override
public int getCount() {
return imgURLs.size();
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.mProgressBar = (ProgressBar) convertView.findViewById(R.id.gridImageProgressbar);
holder.image = (SquareImageView) convertView.findViewById(R.id.gridImageView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
final String imgURL = getItem(position);
Picasso.with(mContext).load(mAppend + imgURL).error(R.drawable.ic_person).into(holder.image, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
if (holder.mProgressBar != null) {
Picasso.with(mContext).load(mAppend + imgURL).into(holder.image);
holder.mProgressBar.setVisibility(View.GONE);
}
}
#Override
public void onError() {
if (holder.mProgressBar != null) {
Picasso.with(mContext).load(mAppend + imgURL).into(holder.image);
holder.mProgressBar.setVisibility(View.GONE);
}
}
});
return convertView;
}
private static class ViewHolder {
SquareImageView image;
ProgressBar mProgressBar;
}
}
< -------------- Method to set grid view ----------->
private void Directory() {
directories = FileSearch.getImageBuckets(getActivity());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity()
,android.R.layout.simple_spinner_item ,directories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
directorySpinner.setAdapter(adapter);
directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Log.d(TAG, "onItemSelected: selected" + directories.get(position));
setGridView(directories.get(position));
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void setGridView(String selectedDir){
Log.d(TAG, "setGridView: Dir chosen");
final ArrayList<String> imageURL = FileSearch.getImagesByBucket(getActivity() ,selectedDir);
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLOUMN;
gridView.setColumnWidth(imageWidth);
GridImageAdapter adapter = new GridImageAdapter(getActivity() , R.layout.grid_image_layout ,append , imageURL);
gridView.setAdapter(adapter);
}

Slow loading images from sdcard to gridview

I've been trying to create multiple image chooser, everything works fine, but the grid scroll is very lazy and slow, I've been tried to use different libraries for image loading in getView() (Picasso,aquery..)
but its no difference ,even with asynctask, that's my code:
Main:
public class Media extends ActionBarActivity {
private AQuery aq;
GridView myGridView;
MyAdapter mySimpleCursorAdapter;
boolean isOddClicked = true;
static String img=null;
final Uri srcUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
final String srcData = MediaStore.Images.Media.DATA;
final String srcImgId = MediaStore.Images.Media._ID;
final Uri thumbUri = MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI;
final String thumb_DATA = MediaStore.Images.Thumbnails.DATA;
final String thumb_IMAGE_ID = MediaStore.Images.Thumbnails.IMAGE_ID;
ArrayList<String> al = new ArrayList<String>(5);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.media);
//Always show the menu
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception ex) {}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
myGridView = (GridView)findViewById(R.id.gridview);
//
CursorLoader cursorLoader = new CursorLoader(
this,srcUri,null,null,null,MediaStore.Images.Media.DATE_TAKEN+ " DESC");
//
Cursor cursor = cursorLoader.loadInBackground();
//
int[] to = {android.R.id.text1};
String[] from = {MediaStore.MediaColumns.TITLE};
mySimpleCursorAdapter = new MyAdapter(
this,android.R.layout.simple_list_item_1,
cursor,from,to,CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
//
myGridView.setAdapter(mySimpleCursorAdapter);
myGridView.setOnItemClickListener(myOnItemClickListener);
}
OnItemClickListener myOnItemClickListener = new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Cursor cursor = mySimpleCursorAdapter.getCursor();
cursor.moveToPosition(position);
int int_ID = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media._ID));
}
};
private Bitmap getThumbnail(int id){
String[] thumbColumns = {srcData, srcImgId};
CursorLoader thumbCursorLoader = new CursorLoader(
this,srcUri,thumbColumns,srcImgId + "=" + id,null,null);
Cursor thumbCursor = thumbCursorLoader.loadInBackground();
Bitmap thumbBitmap = null;
if(thumbCursor.moveToFirst()){
int thCulumnIndex = thumbCursor.getColumnIndex(srcData);
String thumbPath = thumbCursor.getString(thCulumnIndex);
Toast.makeText(getApplicationContext(),thumbPath,Toast.LENGTH_LONG).show();
thumbBitmap = BitmapFactory.decodeFile(thumbPath);
//Create a Dialog to display the thumbnail
AlertDialog.Builder thumbDialog = new AlertDialog.Builder(Media.this);
ImageView thumbView = new ImageView(Media.this);
thumbView.setImageBitmap(thumbBitmap);
LinearLayout layout = new LinearLayout(Media.this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(thumbView);
thumbDialog.setView(layout);
thumbDialog.show();
}else{
Toast.makeText(getApplicationContext(),"NO Thumbnail!",Toast.LENGTH_LONG).show();
}
return thumbBitmap;
}
public class MyAdapter extends SimpleCursorAdapter{
Cursor myCursor;
Context myContext;
public MyAdapter(Context context, int layout, Cursor c, String[] from,int[] to, int flags) {
super(context, layout, c, from, to, flags);
myCursor = c;
myContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater=getLayoutInflater();
convertView =inflater.inflate(R.layout.media_row, parent, false);
holder = new ViewHolder();
holder.thumbnail = (ImageView)convertView.findViewById(R.id.thumb);
holder.title = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
myCursor.moveToPosition(position);
final int myID = myCursor.getInt(myCursor.getColumnIndex(MediaStore.Images.Media._ID));
final String[] thumbColumns = {srcData ,srcImgId};
CursorLoader thumbCursorLoader = new CursorLoader(
myContext,srcUri,thumbColumns,srcImgId + "=" + myID,null,null);
Cursor thumbCursor = thumbCursorLoader.loadInBackground();
if(thumbCursor.moveToFirst()){
final int thCulumnIndex = thumbCursor.getColumnIndex(thumb_DATA);
final String thumbPath = thumbCursor.getString(thCulumnIndex);
Bitmap o = MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), myID, Images.Thumbnails.MICRO_KIND, null);
//holder.thumbnail.setImageBitmap(o);
//Phase II:
String uri = null;
Cursor cursor = MediaStore.Images.Thumbnails.queryMiniThumbnail(
getContentResolver(), myID,
MediaStore.Images.Thumbnails.MINI_KIND,null );
if( cursor != null && cursor.getCount() > 0 ) {
cursor.moveToFirst();//**EDIT**
uri = cursor.getString( cursor.getColumnIndex( MediaStore.Images.Thumbnails.DATA ) );
}
MediaAsync loadAsync = new MediaAsync(getApplicationContext(), holder.thumbnail);
loadAsync.onPostExecute(thumbPath);
/*
holder.thumbnail.setOnClickListener(new OnClickListener(){
public void onClick(View v){
img = thumbPath;
al.add(thumbPath);
if (holder.title.isChecked()) {
holder.title.setChecked(false);
holder.thumbnail.setBackgroundResource(0);
}else{
holder.title.setChecked(true);
holder.thumbnail.setBackgroundResource(R.drawable.media_row_border);
}
}
});
*/
}
return convertView ;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.media, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
}
else if (id == R.id.done) {
Intent main = new Intent(this, Main.class);
main.putStringArrayListExtra("media_lst", al);
startActivity(main);
}
return super.onOptionsItemSelected(item);
}
private static class ViewHolder {
ImageView thumbnail;
CheckBox title;
}
}
mediaAsynce :
public class MediaAsync extends AsyncTask<String,String, String>{
private ImageView mImageView;
private Context mContext;
public MediaAsync(Context context,ImageView imageView) {
mImageView = imageView;
mContext = context;
}
#Override
protected String doInBackground(String... params) {
String url = params[0].toString();
return url;
}
#Override
protected void onPostExecute(String result) {
Uri uri = Uri.fromFile(new File(result));
Picasso.with(mContext)
.load(uri)
//.resize(100, mWidth)
.into(mImageView);
// AQuery aq = new AQuery(mContext);
// aq.id(mImageView).image(result, true, true, 0, R.drawable.ic_launcher);
}
}
As you said you have tried picasso library it should work
Just try once again using picassso like this Async task and all is not required
Just create a simple adapter and load images.
public class GridViewDynamicAdapter extends BaseDynamicGridAdapter {
ImageDetails details;
public static List<ImageDetails> list;
public GridViewDynamicAdapter(Context context, List<ImageDetails> items,
int columnCount) {
super(context, items, columnCount);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
CheeseViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.item_grid, null);
holder = new CheeseViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (CheeseViewHolder) convertView.getTag();
}
if (position == getCount() - 1) {
ImageApplication.fromRecorderPaths = (List<ImageDetails>) getItems();
}
details = (ImageDetails) getItem(position);
// Log.d("Setting=", details.path);
holder.build(getContext(), details.path);
return convertView;
}
private class CheeseViewHolder {
private ImageView image;
private CheeseViewHolder(View view) {
image = (ImageView) view.findViewById(R.id.item_img);
}
void build(final Context context, String title) {
Picasso.with(context).load(new File(title)).centerCrop()
.resize(150, 150).error(R.drawable.ic_launcher).into(image);
}
}
}
OR
Try this example

How to show all video thumbnails stored in a specific folder in sd card

I am getting bitmaps from MediaStore like this
public class VideoStoredInSDCard extends Activity
{
private Cursor videoCursor;
private int videoColumnIndex;
ListView videolist;
int count;
String thumbPath;
String[] thumbColumns = { MediaStore.Video.Thumbnails.DATA,MediaStore.Video.Thumbnails.VIDEO_ID };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initialization();
}
private void initialization()
{
System.gc();
String[] videoProjection = { MediaStore.Video.Media._ID,MediaStore.Video.Media.DATA,
MediaStore.Video.Media.DISPLAY_NAME,MediaStore.Video.Media.SIZE };
videoCursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,videoProjection, null, null, null);
count = videoCursor.getCount();
videolist = (ListView) findViewById(R.id.PhoneVideoList);
videolist.setAdapter(new VideoListAdapter(this.getApplicationContext()));
videolist.setOnItemClickListener(videogridlistener);
}
private OnItemClickListener videogridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,long id)
{
System.gc();
videoColumnIndex = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
videoCursor.moveToPosition(position);
String filename = videoCursor.getString(videoColumnIndex);
Log.i("FileName: ", filename);
//Intent intent = new Intent(VideoActivity.this, ViewVideo.class);
//intent.putExtra("videofilename", filename);
//startActivity(intent);
}};
public class VideoListAdapter extends BaseAdapter
{
private Context vContext;
int layoutResourceId;
public VideoListAdapter(Context c)
{
vContext = c;
}
public int getCount()
{
return videoCursor.getCount();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View listItemRow = null;
listItemRow = LayoutInflater.from(vContext).inflate(R.layout.listitem, parent, false);
TextView txtTitle = (TextView)listItemRow.findViewById(R.id.txtTitle);
TextView txtSize = (TextView)listItemRow.findViewById(R.id.txtSize);
ImageView thumbImage = (ImageView)listItemRow.findViewById(R.id.imgIcon);
videoColumnIndex = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videoCursor.moveToPosition(position);
txtTitle.setText(videoCursor.getString(videoColumnIndex));
videoColumnIndex = videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
videoCursor.moveToPosition(position);
txtSize.setText(" Size(KB):" + videoCursor.getString(videoColumnIndex));
int videoId = videoCursor.getInt(videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
Cursor videoThumbnailCursor = managedQuery(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
thumbColumns, MediaStore.Video.Thumbnails.VIDEO_ID+ "=" + videoId, null, null);
if (videoThumbnailCursor.moveToFirst())
{
thumbPath = videoThumbnailCursor.getString(videoThumbnailCursor.getColumnIndex(MediaStore.Video.Thumbna ils.DATA));
Log.i("ThumbPath: ",thumbPath);
}
thumbImage.setImageURI(Uri.parse(thumbPath));
return listItemRow;
}
}
}
How to get thumbnails from a specific folder in sd card. I am using this tutorial http://gypsynight.wordpress.com/2012/02/17/how-to-show-all-video-file-stored-in-your-sd-card-in-a-listview/
It can be done easily this way:
int videoId = videoCursor.getInt(videoCursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
ContentResolver cr = getContentResolver();
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(cr, videoId, MediaStore.Video.Thumbnails.MICRO_KIND, options);
thumbImage.setImageBitmap(curThumb);

Dynamically refresh gridview when image replaced. notifyDataSetChanged() not working

I have a GridView that loads images from SD card (if present) otherwise some default images. Once images are loaded, the user can select any image cell and take a new picture. When default pictures are loaded in GridView and user takes a picture, the GridView updates and shows the image - but if user clicks the cell again and takes a new picture, then GridView is not updated. Only when I kill the app and restart it, then the new picture appears.
I have tried notifyDataSetChanged() but it doesn't work when image is refreshed.
Here is the code:
public class Fragment1 extends SherlockFragment {
...
private Integer[] mThumbIds = { R.drawable.fr, R.drawable.siderelaxed3,
R.drawable.br, R.drawable.fdbth, R.drawable.bdb, R.drawable.bls,
R.drawable.fls, R.drawable.mm };
private ImageAdapter imageAdapter;
ArrayList<String> f = new ArrayList<String>();// list of file paths
File[] listFile;
ImageLoader imageLoader;
Context context;
boolean needToRefresh = true;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getActivity();
date = util.getCurrentDate();
Bundle bundle = this.getArguments();
date = bundle.getString(MyCommons.SELECTED_DATE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mainView = inflater.inflate(R.layout.picturerecord, container,
false);
getFromSdcard();
Grid = (GridView) mainView
.findViewById(R.id.pictureRecordGrid);
imageAdapter = new ImageAdapter();
Grid.setAdapter(imageAdapter);
imageLoader = new ImageLoader(context, 4);
try {
ourClass = Class
.forName("cameraOpen");
ourIntent = new Intent(context, ourClass);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
poseGrid.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
startActivityForResult(ourIntent, CAMERA_REQUEST);
poseSelected = position;
}
});
return mainView;
}
public void getFromSdcard() {
f.clear();
for (int i = 0; i < MyCommons.POSES_TO_LOAD.length; i++) {
String pose = MyCommons.pose_names[i];
String path = MyCommons.rootPath + File.separator + pose
+ File.separator + date;
File imgFile = new File(path);
if (imgFile.exists()) {
f.add(path);
Log.d(TAG, "image is present at:" + path);
} else {
f.add("loaddefault");
}
}
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ImageAdapter() {
mInflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return f.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (needToRefresh == true) {
convertView = null;
Log.d(TAG, "NEEDED REFRESH");
needToRefresh = false;
}
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.picturerecorddata,
null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.pictureRecordImage);
holder.textview = (TextView) convertView.findViewById(R.id.pictureRecordText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (f.get(position).equals("loaddefault")) {
DefaultImageLoader defaultImages = new DefaultImageLoader(holder.imageview);
defaultImages.execute(position);
} else {
imageLoader.DisplayImage(f.get(position), holder.imageview, mThumbIds[position], position);
}
holder.textview.setText(MyCommons.pose_names[position]);
return convertView;
}
}
class ViewHolder {
ImageView imageview;
TextView textview;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
if (resultCode == Activity.RESULT_OK) {
Bitmap photo = BitmapFactory.decodeByteArray(
data.getByteArrayExtra("BitmapImage"), 0,
data.getByteArrayExtra("BitmapImage").length);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File root = new File(MyCommons.rootPath);
if (!root.exists()) {
root.mkdirs();
Log.d(TAG, "Created Progress pics directory.");
}
String poseName = MyCommons.pose_names[poseSelected];
File pose_dir = new File(root + File.separator + poseName);
if (!pose_dir.exists()) {
pose_dir.mkdirs();
Log.d(TAG, "Created" + pose_dir + " pics directory.");
}
String tempFileName = root + File.separator + poseName + File.separator + date;
File tempFile = new File(tempFileName);
if (tempFile.exists()) {
Log.d(TAG, "File already exist. deleteing it and will write new file:" + tempFileName);
tempFile.delete();
}
util.saveImage(bytes, pose_dir, date);
Log.d(TAG, "image saved. Reloading adapter:\n" + tempFileName);
f.remove(tempFileName);
getFromSdcard();
f.add(poseSelected, tempFileName);
//f.clear();
//f.addAll(f);
imageAdapter.notifyDataSetChanged();
Grid.invalidateViews();
Grid.setAdapter(imageAdapter);
}
}
}
...
}
you need to replace an image in list f with new picture and then call notify, adapter using only items in f for diplaying

How to dynamically update an image gallery upon the photos taken from the native camera in android?

Here is my image gallery code. So far, for testing purpose I directly used some manually stored images,
public class Photo_Gallery extends Activity
{
//---the images to display---
Integer[] imageIDs = {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.e,
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.displayview);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent, View v, int position, long id)
{
//---display the images selected---
ImageView imageView = (ImageView) findViewById(R.id.image1);
imageView.setImageResource(imageIDs[position]);
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
private int itemBackground;
public ImageAdapter(Context c)
{
context = c;
//---setting the style---
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
itemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
//---returns the number of images---
public int getCount() {
return imageIDs.length;
}
//---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 = new ImageView(context);
imageView.setImageResource(imageIDs[position]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(75, 60));
imageView.setBackgroundResource(itemBackground);
return imageView;
}
}
}
And here is the code I used to capture images.
case R.id.takeSnapBtn:
try {
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, imageData);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Following is the onActivityResult(),
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
imageView.setImageBitmap(bmp);
}
}
I would be glad if some one provide me an example of how to dynamically update the gallery with images taken from the camera.
Store the images captured from app and read those images from sd card to gallery..
File sdDir = new File("/sdcard/Pictures/YOUR_DIR");
sdDirFiles = sdDir.listFiles();
for (i = 0; i < sdDirFiles.length; i++) {
//ADD to gallery HERE..
}
If u get all images under the sdcard of perticular Bucket(folder) then use this code...
public class SubGalleryView extends Activity {
private ArrayList<Integer> ImageIds = new ArrayList<Integer>();
private GridView subGalleryView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sub_gallery_view);
//Provide Bucket_Name/Folder_Name Using Bundle.
Bundle bundle = getIntent().getExtras();
Toast.makeText(this, bundle.getString("Bucket_Name"),
Toast.LENGTH_SHORT).show();
//Using Projection We get all images of all folder.
String[] projection = new String[] { MediaStore.Images.Media._ID,
MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME };
Cursor cursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
null, null);
cursor.moveToFirst();
if (cursor.getCount() > 0) {
//using this do{}while(); we get all image_id under perticular bucket. and strored in ArrayList of ImagesIds.
do {
int columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME);
if (cursor.getString(columnIndex).equalsIgnoreCase(
bundle.getString("Bucket_Name"))) {
columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
int imageID = cursor.getInt(columnIndex);
ImageIds.add(imageID);
} else if (bundle.getString("Bucket_Name").equalsIgnoreCase(
"All Pictures")) {
columnIndex = cursor
.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
int imageID = cursor.getInt(columnIndex);
ImageIds.add(imageID);
}
} while (cursor.moveToNext());
}
//Pass ImageIds arrayList to Adapter.
subGalleryAdapter imageAdapter = new subGalleryAdapter(
SubGalleryView.this, R.layout.sub_gallery_view_item, ImageIds);
subGalleryView = (GridView) findViewById(R.id.subGallery);
subGalleryView.setAdapter(imageAdapter);
}
public class subGalleryAdapter extends ArrayAdapter<Integer> {
private Context contex;
private int resourceId;
private LayoutInflater layoutInflater = null;
private ArrayList<Integer> mlist;
public subGalleryAdapter(Activity context, int resourceId,
ArrayList<Integer> list) {
super(context, resourceId, list);
this.mlist = list;
this.contex = context;
this.resourceId = resourceId;
this.layoutInflater = context.getLayoutInflater();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView viewHolder;
if (convertView == null) {
viewHolder = new ImageView(contex);
convertView = layoutInflater.inflate(resourceId, parent, false);
viewHolder = (ImageView) convertView
.findViewById(R.id.imageView1);
} else {
viewHolder = (ImageView) convertView
.findViewById(R.id.imageView1);
}
viewHolder.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
"" + mlist.get(position)));
return convertView;
}
}
}
Using this code u get all images from perticular folder passing bucket display name in bundle. and if u get all images of all bucket(folder) form sdcard then use this code
public class SubGalleryViewy extends Activity {
private Cursor cursor;
private int columnIndex;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sdcard);
// Set up an array of the Thumbnail Image ID column we want
String[] projection = {MediaStore.Images.Thumbnails._ID};
// Create the cursor pointing to the SDCard
cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
MediaStore.Images.Thumbnails.IMAGE_ID);
// Get the column index of the Thumbnails Image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
GridView sdcardImages = (GridView) findViewById(R.id.sdcard);
sdcardImages.setAdapter(new ImageAdapter(this));
// Set up a click listener
sdcardImages.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
// Get the data location of the image
String[] projection = {MediaStore.Images.Media.DATA};
cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, // Which columns to return
null, // Return all rows
null,
null);
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToPosition(position);
// Get image filename
String imagePath = cursor.getString(columnIndex);
// Use this path to do further processing, i.e. full screen display
}
});
}
/**
* Adapter for our image files.
*/
private class ImageAdapter extends BaseAdapter {
private Context context;
public ImageAdapter(Context localContext) {
context = localContext;
}
public int getCount() {
return cursor.getCount();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView picturesView;
if (convertView == null) {
picturesView = new ImageView(context);
// Move cursor to current position
cursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = cursor.getInt(columnIndex);
// Set the content of the image based on the provided URI
picturesView.setImageURI(Uri.withAppendedPath(
MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID));
picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
picturesView.setPadding(8, 8, 8, 8);
picturesView.setLayoutParams(new GridView.LayoutParams(100, 100));
}
else {
picturesView = (ImageView)convertView;
}
return picturesView;
}
}
}

Categories

Resources