I am using the following to code make an image gallery, but I would like to use images from the web instead of from the SD card. Is there a way to do this? Currently the code requires and integer value for the image. Or do I have to download the images to the SD first?
public class viewimages extends Activity {
private Gallery gallery;
private ImageView imgView;
private Integer[] Imgid = {
R.drawable.a_1, R.drawable.a_2, R.drawable.a_3, R.drawable.a_4
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.viewimages);
imgView = (ImageView)findViewById(R.id.ImageView01);
imgView.setImageResource(Imgid[0]);
gallery = (Gallery) findViewById(R.id.examplegallery);
gallery.setAdapter(new AddImgAdp(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
imgView.setImageResource(Imgid[position]);
}
});
}
public class AddImgAdp extends BaseAdapter {
int GalItemBg;
private Context cont;
public AddImgAdp(Context c) {
cont = c;
TypedArray typArray = obtainStyledAttributes(R.styleable.GalleryTheme);
GalItemBg = typArray.getResourceId(R.styleable.GalleryTheme_android_galleryItemBackground, 0);
typArray.recycle();
}
public int getCount() {
return Imgid.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgView = new ImageView(cont);
imgView.setImageResource(Imgid[position]);
imgView.setLayoutParams(new Gallery.LayoutParams(80, 70));
imgView.setScaleType(ImageView.ScaleType.FIT_XY);
imgView.setBackgroundResource(GalItemBg);
return imgView;
}
}
}
You can do something like this:
URL url = new URL("http://www.website.com/image.jpg");
Bimtap bmp = BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
Then you'll need to change where you're doing "setImageResource" to "setImageBitmap" and supply the 'bmp' object once it has been downloaded and loaded up.
[Edit]
It's also important to make sure your android manifest has internet permissions.
<uses-permission android:name="android.permission.INTERNET" />
[Edit for comment question]
If you want to do this for multiple images, and the images aren't based on an id_number (basically if the images aren't something like 0001.jpg, 0002.jpg, etc.) create a string ArrayList that will hold the names of all the items, and then iterate through it. E.g.,
List<String> imageNames = new ArrayList<String>();
imageNames.add("image.jpg");
imageNames.add("thisPhoto.jpg");
//etc. until you've added all images
for (int i = 0; i < imageNames.size(); i++){
URL url = new URL("http://www.website.com/" + imageNames.get(i));
Bimtap bmp = BitmapFactory.decodeStream(url.openConnection()
.getInputStream());
}
Hope that helps
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 have been goin through various posts to find a way to open a image from my res folder,
i have a button named share,i used the following code to do the same
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri=Uri.parse("file:///android_asset/a.jpg");
tried fetching from aseets but image not loaded.
Uri imgUri = Uri.parse("android.resource://"+getPackageName()+"/" +"drawable/a");
the app force closes when i use this uri.
intent.setDataAndType(Uri.parse("android.resource://com.example.hny_wallpaperset/" + R.drawable.a), "image/*");
app force closes
intent.setDataAndType(uri, "image/*");
startActivity(intent);
a is my image name,i also tried using my package name com.example.HNY_wallpaperset instead of getpackagename(),still same error.
any advice?
Found the answer here --
How to open an image in drawable folder using android imageview applications?
here is quick sample of one gallery activity if that is what you need anyway.
public class ImageGalleryExample extends Activity implements
AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
mSwitcher.setImageResource(mImageIds[position]);
}
public void onNothingSelected(AdapterView<?> parent) {
}
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
return i;
}
private ImageSwitcher mSwitcher;
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mThumbIds[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(R.drawable.picture_frame);
return i;
}
private Context mContext;
}
private Integer[] mThumbIds = {
R.drawable.sample_thumb_0, R.drawable.sample_thumb_1,
R.drawable.sample_thumb_2, R.drawable.sample_thumb_3};
private Integer[] mImageIds = {
R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2,
R.drawable.sample_3};
}
but if you just want to set src to image view then use simple:
myImgView.setImageResource(R.drawable.sample_1);
btw, android itslef is choosing betwen drawable-?dpi folders
I have an issue with showing the preview of image selected in the gallery view. I have a gallery of images from sd card, on clicking an image its preview should be shown below the gallery view(Not in seperate activity via intent). I am able to show the gallery with images but nothing is happening on clicking image.
public class NewActivity extends Activity {
GalleryBaseAdapter myGalleryBaseAdapter;
Gallery myPhotoGallery;
int[] mFiles = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myPhotoGallery = (Gallery)findViewById(R.id.photogallery);
myGalleryBaseAdapter = new GalleryBaseAdapter(this);
String ExternalStorageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath();
String path = ExternalStorageDirectoryPath;
String files;
File folder = new File (path);
final File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
System .out.println(files);
}
}
for (File file : listOfFiles) {
myGalleryBaseAdapter.add(file.getPath());
}
myPhotoGallery.setAdapter(myGalleryBaseAdapter);
myPhotoGallery.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View v, int position, long id) {
mFiles = new int[listOfFiles.length];
ImageView imageview = (ImageView)findViewById(R.id.imageView1);
Bitmap bitmapImage = BitmapFactory.decodeFile("/sdcard/" + mFiles[position]);
imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageview.setImageBitmap(bitmapImage);
}
});
}
public class GalleryBaseAdapter extends BaseAdapter {
ArrayList<String> GalleryFileList;
Context context;
GalleryBaseAdapter(Context cont){
context = cont;
GalleryFileList = new ArrayList<String>();
}
#Override
public int getCount() {
return GalleryFileList.size();
}
#Override
public Object getItem(int position) {
return GalleryFileList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Bitmap bm = BitmapFactory.decodeFile(GalleryFileList.get(position));
LinearLayout layout = new LinearLayout(context);
layout.setLayoutParams(new Gallery.LayoutParams(150, 150));
layout.setGravity(Gravity.CENTER);
ImageView imageView = new ImageView(context);
imageView.setLayoutParams(new Gallery.LayoutParams(200, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(bm);
layout.addView(imageView);
return layout;
}
public void add(String newitem){
GalleryFileList.add(newitem);
}
}
}
Can anybody please tell me what is the mistake in my code. Thanks in advance.
Wait but.... your mFiles variable in onItemClick is an array of int empty !?! You are trying to decode a path which is a concatenation between "/sdcard" and a mFiles'row, but... where are you populating that array ? I think you have to specify file path like "listOfFiles[position].getPath()"
This question already has answers here:
Displaying images from specific folder in sd card in grid view
(4 answers)
Closed 3 years ago.
I had developed an application where I want to display images inside grid view from specific folder of sd card. The application is working but only 1st image from folder is appearing in every grid, while I want all images should display. I am not getting where I went wrong.
Below, I am posting my code:
Album Activity:
public class Album3Activity extends Activity {
static File [] mediaFiles;
static File imageDir;
GridView gridView;
ImageAdapter adapter;
Intent in;
public static final String TAG = "Album3Activity";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid);
prepareList();
adapter = new ImageAdapter(this, mediaFiles);
gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
in = new Intent(getApplicationContext(), FullScreen.class);
in.putExtra("id", position);
startActivity(in);
}
});
}//onCreate
public static Bitmap prepareList() {
imageDir = new File(Environment.getExternalStorageDirectory().toString()+
"/diplomat");
mediaFiles = imageDir.listFiles();
Bitmap bmp = null;
for(File imagePath:mediaFiles){
try{
bmp = BitmapFactory.decodeStream(imagePath.toURL().openStream());
}catch(Exception e){
Log.d(TAG, "Exception: "+e.toString());
}//catch
}//for
Log.d(TAG, "prepareList() called");
return bmp;
}//prepareList
}//class
Image Adapter:
public class ImageAdapter extends BaseAdapter{
Activity act;
File[] mFiles;
public static final String TAG = "ImageAdapter";
public ImageAdapter(Activity act, File[] mFiles){
super();
this.act = act;
this.mFiles = mFiles;
}//ImageAdapter
public int getCount() {
return mFiles.length;
}//getCount
public Object getItem(int postion) {
return mFiles[postion];
}//getItem
public long getItemId(int position) {
return 0;
}//getItemId
public static class ViewHolder{
ImageView iv;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view;
LayoutInflater li = act.getLayoutInflater();
if(convertView == null){
view = new ViewHolder();
convertView = li.inflate(R.layout.gridview_row, null);
view.iv = (ImageView)convertView.findViewById(R.id.imageView1);
convertView.setTag(view);
}//if
else{
view = (ViewHolder)convertView.getTag();
}//else
Bitmap bmp = Album3Activity.prepareList();
view.iv.setImageBitmap(bmp);
Log.d(TAG, "getView called");
return convertView;
}//getView
}//ImageAdapter
Note prepareList method, it is not returning bitmap according to the position or index of the imageview, so it would return same image all the time, change it to accept an index parameter, and return bitmap accordingly, as:
public static Bitmap prepareList(int index) {
imageDir = new File(Environment.getExternalStorageDirectory().toString()+
"/diplomat");
mediaFiles = imageDir.listFiles();
File imagePath=imageDir[index];
Bitmap bmp = null;
try{
bmp = BitmapFactory.decodeStream(imagePath.toURL().openStream());
}catch(Exception e){
Log.d(TAG, "Exception: "+e.toString());
}//catch
Log.d(TAG, "prepareList() called");
return bmp;
}//prepareList
In getView everytime your are calling album3Activity.prepareList() so it will return single image for all the grid. Try with the passing the particular imagepath in mFiles[position] each time and get the bitmap or get all the bitmap at once and store it in arrayList and pass the arraylist to adapter and use it in getView.
Try this..it may help you..
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)
{
}});
}