Here I am getting stored picture paths from the database. So that I am showing the images in the gridview with the help of paths. But as it is shown in my code below, I am loading cursoradapter in the asynctask. The problem here is for the first time it is okay that it takes some time until all images are loaded.
But if user adds one more pic to the database, it again takes much time to load all images as I kept the asynctask in onResume() to make the added picture also visible. The same is the case whenever user adds each picture. Can someone suggest me a simple way to get the last added picture visible in the gridview without having to load all the pictures again. Or in the least case can some one help me implementing lazy adapter to the present cursoradapter if that is not possible?
public class ImagesScreen extends Activity {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.images_screen);
gridView = (GridView)findViewById(R.id.gridView1);
String[] from = new String[] { Reminders.MOM_PATHS };
int[] to = new int[] {};
dbCon = new SQLiteConnectClass(ImagesScreen.this);
imageCursorAdapter = new ImageCursorAdapter(ImagesScreen.this, R.layout.griditem, null, from, to);
gridView.setAdapter(imageCursorAdapter);
}
protected void onResume() {
super.onResume();
new GetImages().execute((Object[]) null);
}
private class GetImages extends AsyncTask<Object, Object, Cursor> {
#Override
protected Cursor doInBackground(Object... params) {
return dbCon.getAllImages();
}
#Override
protected void onPostExecute(Cursor result) {
imageAdapter.changeCursor(result);
}
public void addpictures(View view){
// code for adding picture paths to the database by transferring to another activity.
}
}
CustomAdapter class:
public class ImageCursorAdapter extends SimpleCursorAdapter{
private int layout;
private LayoutInflater mLayoutInflater;
private Context mContext;
public ImageAdapter(Context context, int layout, Cursor c,String[] from, int[] to) {
super(context, layout, c, from, to,0);
this.layout = layout;
mLayoutInflater=LayoutInflater.from(context);
mContext = context;
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = mLayoutInflater.inflate(layout, parent, false);
return v;
}
public void bindView(final View v, final Context context, Cursor c) {
final int id = c.getInt(c.getColumnIndex("id"));
final String imagepath = c.getString(c.getColumnIndex("paths"));
ImageView imageview = (ImageView)v.findViewById(R.id.imageView1);
File imgFile = new File(imagepath);
if(imgFile.exists()){
Bitmap imageBitmap = decodeFile(imgFile);
imageview.setImageBitmap(imageBitmap);
}
}
}
use this code
public class Imagegallery extends Activity implements OnItemClickListener,
OnScrollListener, OnTouchListener {
Button btn;
SQLiteDatabase sampleDB = null;
String SAMPLE_DB_NAME = "hic";
int size = 0;
TextView headertext;
Button cartbtn;
ImageView footer1, footer2, footer3, footer4, footer5;
GridView gridView;
boolean larg = false;
String products;
int j = 1;
int ii = 0;
String imagepath[];
String productname[];
int productid[] = new int[1000];
String productids[] = new String[1000];
int integerprodids[] = new int[1000];
final Context context = this;
String filename2[];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.currentspecial);
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "aiwhic/product" + File.separator);
File[] fileName = root.listFiles();
filename2 = new String[fileName.length];
for (int j = 0; j < fileName.length; j++) {
Uri uri = Uri.fromFile(fileName[j]);
filename2[j] = fileName[j].getAbsolutePath();
Log.e("file", filename2[j]);
}
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(new ImageAdapter(this, filename2, filename2));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
int isf = filename2[position].lastIndexOf("/");
int laf = filename2[position].lastIndexOf(".");
String filename = filename2[position].substring(isf + 1, laf);
int pos = Integer.parseInt(filename);
Intent go = new Intent(Imagegallery.this, ItemsPage.class);
Bundle bundle = new Bundle();
bundle.putInt("position", pos);
bundle.putString("whichclass", "imagegallery");
bundle.putInt("catid", 2);
go.putExtras(bundle);
startActivity(go);
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] mobileValues;
private final String[] mobileimages;
public ImageAdapter(Context context, String[] mobileValues, String[] mo) {
this.context = context;
this.mobileValues = mobileValues;
this.mobileimages = mo;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
gridView = inflater.inflate(R.layout.currentspeciallist, null);
TextView textView = (TextView) gridView
.findViewById(R.id.textView1);
textView.setText(mobileValues[position]);
textView.setVisibility(View.INVISIBLE);
ImageView imageView = (ImageView) gridView
.findViewById(R.id.imageView1);
imageView.setTag(mobileimages[position]);
new Loadimage().execute(imageView);
// imageView.setImageBitmap(BitmapFactory
// .decodeFile(mobileimages[position]));
} else {
gridView = (View) convertView;
}
return gridView;
}
public int getCount() {
return mobileimages.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
}
class Loadimage extends AsyncTask<Object, Void, Bitmap> {
private ImageView imv;
private String path;
#Override
protected Bitmap doInBackground(Object... params) {
imv = (ImageView) params[0];
path = imv.getTag().toString();
// Bitmap thumb = BitmapFactory.decodeFile(path);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 2; // for 1/2 the image to be loaded
Bitmap thumb = Bitmap.createScaledBitmap(
BitmapFactory.decodeFile(path, opts), 120, 120, false);
return thumb;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (!imv.getTag().toString().equals(path)) {
/*
* The path is not same. This means that this image view is
* handled by some other async task. We don't do anything and
* return.
*/
return;
}
if (bitmap != null && imv != null) {
imv.setVisibility(View.VISIBLE);
imv.setImageBitmap(bitmap);
} else {
imv.setVisibility(View.GONE);
}
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
then create a xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher" >
</ImageView>
</RelativeLayout>
i am getting file path directly . u just get the name from sqlite and pass the array string
use Android-Universal-Image-Loader
and set
ImageView imageview = (ImageView)v.findViewById(R.id.imageView1);
File imgFile = new File(imagepath);
if(imgFile.exists()){
imageLoader.displayImage(imageUri(ur file path), imageView);
}
Related
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);
}
}
I am able to show images (set by default) in the gridview properly using a custom adapter.
However when I try to change the string[] in ForecastFragment (snippets below), the updateList function is not getting called. I would like the all the views in the grid to be recreated.
ImageAdapter.java :
public class ImageAdapter extends BaseAdapter {
public Context mContext; ImageAdapter(Context c) {
mContext = c;
String LOG_TAG = ImageAdapter.class.getSimpleName();
Log.e(LOG_TAG,"Constructor Context : "+mContext);
}
public int getCount() {
return this.eatFoodyImages.length;
}
public int size1;
public int size2;
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public void updateList(String[] string)
{
this.eatFoodyImages=string;
this.notifyDataSetChanged();
String LOG_TAG = ImageAdapter.class.getSimpleName();
Log.e(LOG_TAG, "\n\nupdatelist : " + this.eatFoodyImages);
}
// create a new ImageView for each item referenced by the Adapter
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);
size1 = (int) this.mContext.getResources().getDimension(R.dimen.image_size1);
size2 = (int) this.mContext.getResources().getDimension(R.dimen.image_size2);
imageView.setLayoutParams(new GridView.LayoutParams(size1,size2));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
String LOG_TAG = ImageAdapter.class.getSimpleName();
Log.e(LOG_TAG, "\n\n\nPosition : " + position + " Strings Array : \n\n" + eatFoodyImages[position].toString());
//System.out.println();
Picasso.with(mContext)
.
load(eatFoodyImages[position])
.
into(imageView);
return imageView;
}
// references to our images
public String[] eatFoodyImages = {
"http://i.imgur.com/rFLNqWI.jpg", //Default Random Data!!!
"http://i.imgur.com/C9pBVt7.jpg",
"http://i.imgur.com/rT5vXE1.jpg",
"http://i.imgur.com/aIy5R2k.jpg",
"http://i.imgur.com/MoJs9pT.jpg",
"http://i.imgur.com/S963yEM.jpg",
"http://i.imgur.com/rLR2cyc.jpg",
"http://i.imgur.com/SEPdUIx.jpg",
"http://i.imgur.com/aC9OjaM.jpg",
"http://i.imgur.com/76Jfv9b.jpg",
"http://i.imgur.com/fUX7EIB.jpg",
"http://i.imgur.com/syELajx.jpg",
"http://i.imgur.com/COzBnru.jpg",
"http://i.imgur.com/Z3QjilA.jpg",
};
}
ForecastFragment.java :
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
GridView gridview = (GridView) rootView.findViewById(R.id.gridview);
movieadapter = new ImageAdapter(this.getActivity());
gridview.setAdapter(movieadapter);
});
return rootView;
}
Calling updateList :
public class FetchWeatherTask extends AsyncTask<String, Void, String[]>
{//Showing only relevant code
IA.updateList(eatFoodyImages); //Here eatFoodyImages contains the new String[] to be used for image loading.
Here it goes, i have a adapter like below
public View getView(int position, View convertView, ViewGroup parent) {
Movie movie = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.movie_tile, parent, false);
}
ImageView imageView = (ImageView) convertView.findViewById(R.id.movie_image);
Picasso.with(this.getContext()).load(Constants.MOVIE_POSTER_PATH_SMALL + movie.getPosterPath()).placeholder(ContextCompat.getDrawable(this.getContext(), R.drawable.movie)).error(ContextCompat.getDrawable(this.getContext(), R.drawable.movie)).into(imageView);
return convertView;
}
which sets a tile in a gridview.
I trigger a asynctask and get the movies from API then notify the dataset which loads the movies and refreshes the view.
So essentially your notifyDataSet() should be in onPostExecute() of AsyncTask.
Here is my Async task code for better understanding.
public class CallMovieDBAPI extends AsyncTask<String, Void, List<Movie>> {
ProgressDialog dialog;
private Activity activity;
private GridView gridView;
public CallMovieDBAPI(Activity activity, GridView gridView) {
this.activity = activity;
this.gridView = gridView;
}
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(getActivity());
dialog.setMessage(activity.getString(R.string.progressDialogText));
dialog.show();
}
#Override
protected List<Movie> doInBackground(String... params) {
InputStream in = null;
String jsonResponse = null;
String apiURL = params[0];
try {
URL url = new URL(apiURL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
jsonResponse = getJsonObject(in);
movieList = JsonParser.parse(jsonResponse);
} catch (Exception e) {
Log.e("CallMovieDBAPI", "Exception occurred in AsyncTask - CallMovieDBAPI", e);
}
return movieList;
}
#Override
protected void onPostExecute(List<Movie> movies) {
Log.d("Popular Movies", "Got data successfully");
if (dialog.isShowing()) {
dialog.dismiss();
}
movieAdapter = new MovieAdapter(activity, movieList);
gridView.setAdapter(movieAdapter);
movieAdapter.notifyDataSetChanged();
if (isTablet) {
((MovieClickedCallback) getActivity()).onMovieClicked(0, movieAdapter);
}
}
Let me know if this solves.
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.
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;
}
}
}
I am trying to add bitmap images in gridview but continuously getting exceptions. when i try to do this in layouts it works fine. I am unable to get it. Here is the code what i am doing is:
public class SampleActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gv=(GridView)this.findViewById(R.id.gv);
Bitmap src = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
ImageView iv= new ImageView(this);
// iv.setId(i);
Bitmap bm=Bitmap.createBitmap(src,j*(src.getWidth()/2),j*(src.getHeight()/3),src.getWidth()/3,src.getHeight()/3);
iv.setImageBitmap(bm);
gv.addView(iv);
}
}
}
Kindly Any help is welcome :))
for adding data in Gridview, you have to set adapter
gridview.setAdapter(adapter);
see example http://developer.android.com/guide/tutorials/views/hello-gridview.html
Here is an idea. You can create a ImageAdapter and add a SetImages function. Then you add your ImageAdapter to the GridView, prepare the images and set the through the ImageAdapter.
For sample:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid);
GridView gridview=(GridView)this.findViewById(R.id.gridView);
Integer[] mThumbIds = {
R.drawable.logo, R.drawable.logo, R.drawable.logo,
R.drawable.logo, R.drawable.logo, R.drawable.logo,
R.drawable.logo, R.drawable.logo, R.drawable.logo,
R.drawable.logo, R.drawable.logo, R.drawable.logo
};
ImageAdapter myAdapter = new ImageAdapter(this);
myAdapter.SetImages(mThumbIds);
gridview.setAdapter(myAdapter);
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private Integer[] pics;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return pics.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) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
//You can set some params here
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(pics[position]);
return imageView;
}
public void SetImages(Integer[] id){
pics = id.clone();
}
}
I don't know if this is the right approach but it works :D
public class ImageAdapter extends BaseAdapter
{
private Context context;
private List<String> path_images = new ArrayList<String>();
public ImageAdapter( Context context, List<String> path_images ){ this.context = context; this.path_images = path_images; }
#Override public int getCount ( ){ return images.size(); }
#Override public Object getItem (int i){ return BitmapFactory.decodeFile( path_images.get(i) ); }
#Override public long getItemId(int i){ return 0; }
#Override public View getView(int i, View convertView, ViewGroup parent)
{
ImageView imageView = new ImageView( context );
imageView.setImageBitmap( BitmapFactory.decodeFile( paht_images.get(i) ) );
imageView.setScaleType( ImageView.ScaleType.CENTER_CROP );
imageView.setLayoutParams(new GridView.LayoutParams( 145, 145 ));
return imageView;
}
}
private void present_all_images()
{
final String FS = File.separator;
final String directory = Environment.getExternalStorageDirectory().toString() + FS + "directory";
List<String> path_images = new ArrayList<String>();
path_images.add( directory + FS + "image01.png" );
path_images.add( directory + FS + "image02.png" );
path_images.add( directory + FS + "image03.png" );
grid_data = (GridView)findViewById(R.id.gallery_grid_data);
grid_data.setAdapter( new ImageAdapter( this, path_images ) );
grid_data.setOnItemClickListener(new OnItemClickListener(){ public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
}});
}