Have an efficiency issue. Need to pass data between classes - android

So I have a Gridview and and ImageAdapter class. The images all get grab from a folder and then populated into the grid view. I then have another class that displays the full image when clicked. However whenever someone clicks an image ImageAdapter has to get called again and all the images need to be repopulated into my variables and then I just pick out the one I need. This is terribly inefficient but I don't know how to do it otherwise.
Here is my code.
Main Classes (favorites in this case) with the grid view
public class Favorites extends Activity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites);
GridView gridview = (GridView) findViewById(R.id.favgridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,View v, int position, long id){
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
}
}
My ImageAdapter class, you can see that I load all the images as bitmaps into an array.
public class ImageAdapter extends BaseAdapter{
private Context mContext;
private Bitmap[]mis_fotos;
public ImageAdapter(Context c){
mContext = c;
}
public int getCount(){
get_images();
return mis_fotos.length;
}
public Bitmap getItem(int position){
get_images();
return mis_fotos[position];
}
public long getItemId(int position){
return 0;
}
public View getView(int position, View convertView, ViewGroup parent){
ImageView imageView;
if (convertView == null){
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85,85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageBitmap(mis_fotos[position]);
return imageView;
}
private void get_images(){
String dirPath = mContext.getFilesDir().getAbsolutePath() + File.separator + "favorites";
File directory = new File(dirPath);
File[] archivos = directory.listFiles();
mis_fotos = new Bitmap[archivos.length];
for (int cont=0; cont<archivos.length;cont++){
File imgFile = new File(archivos[cont].toString());
mis_fotos[cont] = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
}
}
}
And Finally my Full Image Class
public class FullImageActivity extends Activity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
Intent i = getIntent();
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageBitmap(imageAdapter.getItem(position));
}
}
So you can see that when I use the full image all I can pass is the position integer from the gridview class. I then have to call get_images() again in the ImageAdapter class and repopulate an array all over again.
All I need to to pass a single image from the gridview to the fullimage class when an image is clicked. I know there is an easier and far more efficient way to do this. I hope this makes sense.

Work around required, you are calling get_images() multiple times inside an Adapter class which is a bad way. Better solution is remove it from Adapter class and keep inside the MainActivity and just call it before setting the Adapter like,
GridView gridview = (GridView) findViewById(R.id.gridView);
get_images();
gridview.setAdapter(new ImageAdapter(this));
And then your method for Adapter class should be like,
public int getCount() {
return mis_fotos.length;
}
public Object getItem(int position) {
return mis_fotos[position];
}
Now, I come to your issue that is you want to show an Image as fullscreen to Next Activity. So, why don't you fetch the Bitmap from clicked ListView Item and pass it to Next Activity?. So, how can you do that? Here it is,
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Bitmap bitmap = (Bitmap) parent.getAdapter().getItem(position);
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("bitmap", bitmap);
i.putExtras(bundle);
startActivity(i);
});
So, nothing tricky, just getting the Bitmap using getItem(position); and the sending it to Next Activity using Bundle. Now you can easily get the Bitmap using
Bundle bundle = getIntent().getExtras();
Bitmap bitmap = bundle.getParcelable("bitmap");
// create new Bitmap with any height, width required by you.
Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
and show to ImageView.

Related

Expanding an image from a thumbnail in a GridView

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

why the view pager show the last image of an array each time i select any image of them?

what i am doing that i display a grid view and each time i select an image it should be displayed an a full screen activity .. also i added swipe screen on a view pager functionality so i can switch left and right between images .. so my code works fine but the problem is that each time i select an image it always show the last one in the array of images .. it doesn't show the correct image .. why that is happening ?
here is code for the fragment that contains the grid view :
public class WoodenBlinds extends Fragment {
public Integer[] mThumbIds = {
R.drawable.wod_1, R.drawable.wod_2,
R.drawable.wod_3, R.drawable.wod_4,
R.drawable.wod_5, R.drawable.wod_6,
R.drawable.wod_7, R.drawable.wod_8,
R.drawable.wod_9
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_wooden_blinds, container, false);
GridView gridview = (GridView)view.findViewById(R.id.grid_view);
try{
// Instance of ImageAdapter Class
gridview.setAdapter(new ImageAdapter(getActivity(), mThumbIds));
} catch (OutOfMemoryError E) {
E.printStackTrace();
}
/**
* On Click event for Single Gridview Item
* */
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getActivity(), FullImageActivity2.class);
// passing array index
i.putExtra("id", mThumbIds[position]);
i.putExtra("array", mThumbIds);
Log.d("ID", "" + mThumbIds[position]);
startActivity(i);
}
});
return view;
}
}
and here is the code for the full screen activity:
public class FullImageActivity2 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_image_activity2);
//get intent data
Intent i = getIntent();
Object[] s = (Object[]) getIntent().getSerializableExtra("array");
Integer[] newArray = Arrays.copyOf(s, s.length, Integer[].class);
//Selected image id
// Loop through the ids to create a list of full screen image views
ImageAdapter imageAdapter = new ImageAdapter(this, newArray);
List<ImageView> images = new ArrayList<ImageView>();
for (int i1 = 0; i1 < imageAdapter.getCount(); i1++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(imageAdapter.mThumbIds[i1]);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
//
images.add(imageView);
}
// Finally create the adapter
ImagePagerAdapter imagePagerAdapter = new ImagePagerAdapter(images);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(imagePagerAdapter);
// Set the ViewPager to point to the selected image from the previous activity
// Selected image id
int position = getIntent().getExtras().getInt("id");
viewPager.setCurrentItem(position);
}
}
i guess the problem is with this line of code :
Object[] s = (Object[]) getIntent().getSerializableExtra("array");
Integer[] newArray = Arrays.copyOf(s, s.length, Integer[].class);
because each time it display the last index .. Not the correct one .. any advice's ???
When you read the data in the Intent with this line :
int position = getIntent().getExtras().getInt("id");
You don't read the position, but the image resource id... because you fill the Intent with this :
i.putExtra("id", mThumbIds[position]);
So, you can try to fill the Intent with
i.putExtra("id", position);

Gallery- viewing more than one picture

I have a working Gallery that shows one picture at a time and can be "swiped" to rotate through the images. I want to have the option of the user to view 2 or 3 pictures at a time by using the menu and selecting how many to show. So far Ive tried adjusting the Gallery width, and LinearLayout params and all crash the Activity. any advice would be appreciated.
I declare and initialize the Gallery here and have the onOptionsItemSelected method sekeleton.
public class SpeechAppActivity extends Activity implements OnClickListener{
//Menu Items
// Class variables
Gallery myGallery;
ImageView imageView;
MyDBAdapter db;
Item item1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = new MyDBAdapter(this);
db.insertEntry(item1 = new Item("Bathtub", "Bathroom", "Typical", "Clean", "fill, wash", "Round, deep", "Bathroom", "Toilet, Bathroom", R.drawable.ic_launcher));
Log.i("item", "item: " + item1.toString());
// Bind the gallery defined in the main.xml
// Apply a new (customized) ImageAdapter to it.
myGallery = (Gallery) findViewById(R.id.myGallery);
myGallery.setAdapter(new ImageAdapter(this));
//myGallery.setLayoutParams(new Gallery.LayoutParams(250, 250));
myGallery.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View v,
int position, long id) {
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.settings:
startActivity(new Intent(this, Prefs.class));
return true;
case R.id.show1:
//myGallery.findViewById(R.id.myGallery).setLayoutParams(new Gallery.LayoutParams(500, 250));
return true;
case R.id.show2:
//myGallery.findViewById(R.id.myGallery).setLayoutParams(new Gallery.LayoutParams(500, 250));
return true;
case R.id.show3:
//myGallery.findViewById(R.id.myGallery).setLayoutParams(new Gallery.LayoutParams(500, 250));
return true;
}
return false;
}
This is the Image Adapter class for the Gallery
public class ImageAdapter extends BaseAdapter {
/** The parent context */
private Context myContext;
// Put some images to project-folder: /res/drawable/
// format: jpg, gif, png, bmp, ...
private int[] myImageIds = { R.drawable.apple, R.drawable.orange,
R.drawable.ic_launcher };
/** Simple Constructor saving the 'parent' context. */
public ImageAdapter(Context c) {
this.myContext = c;
}
// inherited abstract methods - must be implemented
// Returns count of images, and individual IDs
public int getCount() {
return this.myImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// Returns a new ImageView to be displayed,
public View getView(int position, View convertView,
ViewGroup parent) {
// Get a View to display image data
ImageView iv = new ImageView(this.myContext);
iv.setImageResource(this.myImageIds[position]);
// Image should be scaled somehow
//iv.setScaleType(ImageView.ScaleType.CENTER);
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
//iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
//iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
//iv.setScaleType(ImageView.ScaleType.FIT_XY);
//iv.setScaleType(ImageView.ScaleType.FIT_END);
//iv.setScaleType(ImageView.ScaleType.FIT_START);
// Set the Width & Height of the individual images
//get scale for finding dip of a set # of pixels
final float scale = parent.getContext().getResources().getDisplayMetrics().density;
iv.setLayoutParams(new Gallery.LayoutParams((int) (300 * scale + 0.5f), (int) (250 * scale + 0.5f)));
return iv;
}
}// ImageAdapter
In your adapter,
Use View object (witn custom view) and put ImageView inside it.
This was you can put more than one images per view.
Best results can be achieved by few layout files based on number of images and using correct one according to user selection.
Let me know if you need more specific code template.

Image setting Gallery view in android

How can we switch the pictures with some information? When we switch the picture then information should also be get switched in Gallery view in android.
public class ImageAdapter extends BaseAdapter {
String[] Merchantname=null,Cardname=null,Points=null,Expirydate=null,status=null;
private Context ctx;
int imageBackground;
Bitmap[] image_data;
public ImageAdapter(Context c, Bitmap []card_image,String [] Merchantname,String [] Cardname,String []points,String[] Expirydate, String []status) {
ctx = c;
image_data = card_image;
TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
ta.recycle();
this.Merchantname=Merchantname;
this.Cardname=Cardname;
this.Points=points;
this.Expirydate=Expirydate;
this.status=status;
}
public int getCount() {
return image_data.length;
}
public Object getItem(int arg0) {
return arg0;
}
public long getItemId(int arg0) {
return arg0;
}
public View getView(int position, View arg1, ViewGroup arg2) {
TextView tv1,tv2,tv3,tv4,tv5;
ImageView i ;//= new ImageView(this.ctx);
if (arg1 == null) {
i = new ImageView(this.ctx);
} else {
i = (ImageView) arg1;
}
tv1=(TextView)findViewById(R.id.Merchantname);
tv2=(TextView)findViewById(R.id.Cardname);
tv3=(TextView)findViewById(R.id.Expirydate);
tv4=(TextView)findViewById(R.id.status);
tv1.setText(Merchantname[position]);
tv2.setText(Cardname[position]);
tv3.setText(Expirydate[position]);
tv4.setText(status[position]);
// ImageView iv = new ImageView(ctx);
// Drawable drawable = new BitmapDrawable(getResources(), image_data[position]);
i.setImageBitmap(image_data[position]);
i.setImageDrawable(new BitmapDrawable(getResources(), image_data[position]));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setLayoutParams(new Gallery.LayoutParams(300,200));
i.setBackgroundResource(imageBackground);
return i;
}
}
You simple need to use an ArrayList whose Index would be linked with the Gallery views individual views, and the lenth of the ArrayList would match the Length of Gallery View, on the setOnItemClickListener use the position variable to change the Content from the Array List matching the same index
// Reference the Gallery view
Gallery g = (Gallery) findViewById(R.id.gallery);
// Set the adapter to our custom adapter (below)
g.setAdapter(new ImageAdapter(this));
// Set a item click listener, and just Toast the clicked position
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Toast.makeText(Gallery1.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
Create layout with ImageView and TextView. Then write your custom adapter for Gallery and there in getView method put to ImageView and TextView your values. Them set this adapter to your Gallery.
The Problem Lies here,
tv1=(TextView)findViewById(R.id.Merchantname);
tv2=(TextView)findViewById(R.id.Cardname);
tv3=(TextView)findViewById(R.id.Expirydate);
tv4=(TextView)findViewById(R.id.status);
You forgot to mention the Parent View before asking for the LayoutFile, add (TextView)arg1.findViewById() for all the TextViews and let us know.
Hope it helps

screen rotation and live update gridview android

i have a big doubt about memory leak and screen rotation. I know that activity is destroy when that happens and new one is started. With my code, with is the best way to show the gridview? (this activity is part of a tab activity so in the main one i get the pictures from web services and put them on the object, using AsyncTask)
i would like to show the pictures at the same time they are saved on the object. Like simulating ajax...is that possible? at the moment, they are all show on the start or resume.
Also, im facing memory leak here?
last question, how can i show photos in the grid
my code:
public class LoteFotosActivity extends Activity {
Sistema sis=Sistema.getInstance();
Lote lote;
GridView gridview;
ImageAdapter iA;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lote_foto_view);
Bundle extras = getIntent().getExtras();
lote=sis.getLoteDetalle(extras.getInt("LoteID"));
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(iA=new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(LoteFotosActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return lote.FOTOS.size();
}
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);
imageView.setLayoutParams(new GridView.LayoutParams(200,200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageBitmap(lote.FOTOS.get(position));
return imageView;
}
}
//test looking
public void onResume() {
super.onResume();
Toast.makeText(this,"ON RESUME",
Toast.LENGTH_SHORT).show();
// gridview.setAdapter(new ImageAdapter(this));
// foto.setImageDrawable(lote.FOTOS.get(0));
}
public void onPause() {
super.onPause();
Toast.makeText(this,"onPause",
Toast.LENGTH_SHORT).show();
iA=null;
gridview.setAdapter(iA=new ImageAdapter(this));
// foto.setImageDrawable(lote.FOTOS.get(0));
}
thx in advance !
I think you should add this to your activity
android:configChanges="orientation"
to avoid the destroying problem when rotating the screen... with this you dont need to save state to restore, there is no need because the activity is not destroyed and recreated everytime the screen rotation changes
For API 13+ the screenSize must also be handled:
android:configChanges="orientation|screenSize"

Categories

Resources