Android Gallery View Update Images - android

i have a question about using GalleryView.
At first, i set five "default images" to show from drawable directory.
But after, i want to run an Async Task in which i download the images, save them and show them in the gallery.
For that i created the following Adapter:
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private ArrayList<Integer> mImageIds = new ArrayList<Integer>();
private ArrayList<Drawable> mImageDrawables = new ArrayList<Drawable>();
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
mGalleryItemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
public void setPlaces(int count) {
for (int i = 0; i < count; i++) {
mImageIds.add(R.drawable.tournoimg);
mImageDrawables.add(null);
}
}
public void setDrawable(String resource, int position) {
Drawable image = Drawable.createFromPath(resource);
mImageDrawables.add(position, image);
}
public int getCount() {
return mImageIds.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
if (mImageDrawables.get(position) == null)
i.setImageResource(mImageIds.get(position));
else
i.setImageDrawable(mImageDrawables.get(position));
i.setLayoutParams(new Gallery.LayoutParams(60, 78));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
}
and the following Async Task
private class FillImages extends AsyncTask<ArrayList<Place>, Void, Void> {
protected Void doInBackground(ArrayList<Place>... listplaces) {
ArrayList<Place> places = listplaces[0];
Iterator<Place> it = places.iterator();
int position = 0;
while (it.hasNext()) {
Place p = it.next();
saveImage(p.getImage(), p.getURLImage());
// Gallery g = (Gallery) findViewById(R.id.gallery);
mImageAdapter.setDrawable(p.getImage(), position);
position++;
mImageAdapter.notifyDataSetChanged();
}
return (null);
}
But when i run it i have this error:
Caused by: android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Any idea?
Thanks

You should implement onPostExecute() and move any code that interacts with the UI (perhaps notifyDataSetChange()) to that method. Android requires that interaction with the GUI happen from the UI thread.

For that you have to put this code into onPostExecute() method of Async task :
ArrayList<Place> places = listplaces[0];
Iterator<Place> it = places.iterator();
int position = 0;
while (it.hasNext()) {
Place p = it.next();
saveImage(p.getImage(), p.getURLImage());
// Gallery g = (Gallery) findViewById(R.id.gallery);
mImageAdapter.setDrawable(p.getImage(), position);
position++;
mImageAdapter.notifyDataSetChanged();
}

Related

Android GridView getItem Color

I have a custom GridView populated by array of colors.
Now when I click the item I want to get the color of cell.
I have this code, but when I click the item, get the java.lang.NullPointerException.
public class Colori_picker extends Activity {
private GridView grColori;
private ColorPickerAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.color_picker);
grColori= (GridView) findViewById(R.id.gridViewColors);
grColori.setAdapter(new ColorPickerAdapter(this));
grColori.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object color = mAdapter.getItem(position);
finish();
}
});
}
the adapter
public class ColorPickerAdapter extends BaseAdapter {
private Context context;
// list which holds the colors to be displayed
private List<Integer> colorList = new ArrayList<Integer>();
// width of grid column
int colorGridColumnWidth;
public ColorPickerAdapter(Context context) {
this.context = context;
String colors[][] = {
{ "83334C", "B65775", "E07798", "F7A7C0", "FBC8D9", "FCDEE8" },
{ "000000", "434343", "666666", "999999", "CCCCCC", "EFEFEF" } };
colorList = new ArrayList<Integer>();
// add the color array to the list
for (int i = 0; i < colors.length; i++) {
for (int j = 0; j < colors[i].length; j++) {
colorList.add(Color.parseColor("#" + colors[i][j]));
}
}
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
// set the width of each color square
imageView.setLayoutParams(new GridView.LayoutParams(colorGridColumnWidth, colorGridColumnWidth));
} else {
imageView = (ImageView) convertView;
}
imageView.setBackgroundColor(colorList.get(position));
imageView.setId(position);
return imageView;
}
public int getCount() {
return colorList.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
}
What is happening is that you are declaring the instance variable mAdapter but never instantiating it. All you need to do is change this
grColori.setAdapter(new ColorPickerAdapter(this));
To this
mAdapter = new ColorPickerAdapter(this);
grColori.setAdapter(mAdapter);

AsyncTask to update adapter UI

im pretty new to Android and AsyncTask and was hoping you could help...Im trying to refresh an ImageView adapter so it updates on the UI... i was told to use notifyDataSetChanged() but i just can get it to work...i have setup an asynctask but the only result i get is a NullPointerException...i need the update to happen when a new element is added to my nextColorArray....Please look at my code, i seriously dont even know if im using my asynctask in the right manner or if im even close?!..cheers
public class GameScreen extends Activity{
int yellow = 0xffffff66;
int green = 0xff00EE76;
int red = 0xffff4342;
int blue = 0xff42c3ff;
int purple = 0xff9932CC;
int white = 0xFFFFFFFF;
int total_Count = 0;
int colorPosition = 0;//nextColor position
int colorPickerStart = 0;
ArrayList<Integer>nextColorArray;
ImageView imageView;
ImageAdapter ia;
private static final String TAG = GameScreen.class.getSimpleName();//log
ArrayList<Integer>colorPicker = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_screen);
new upDateNextColor().execute();
}
class upDateNextColor extends AsyncTask<Void, Void, Void> {
GridView gridview2;
#Override
protected Void doInBackground(Void... voids) {
return null;
}
#Override
protected void onPostExecute(Void result) {
nextColorArray.add(blue);
nextColorArray.add(green);
nextColorArray.add(red);
nextColorArray.add(yellow);
nextColorArray.add(purple);
Collections.shuffle(nextColorArray);
}
#Override
protected void onPreExecute() {
nextColorArray = new ArrayList<Integer>(10);
gridview2 = (GridView) findViewById(R.id.colorNext);
ia = new ImageAdapter(nextColorArray);
gridview2.setAdapter(ia);
if(total_count > 10){
nextColorArray.add(0, white);
ia.notifyDataSetChanged();
}
}
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList aL;
public ImageAdapter(Context c, ArrayList<Integer>aL) {
mContext = c;
this.aL = aL;
}
public ImageAdapter(ArrayList<Integer>aL) {
this.aL = aL;
}
public ImageAdapter(Context c){
mContext = c;
}
public int getCount() {
return 10;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(50, 50));
imageView.setBackgroundColor(nextColorArray.get(colorPosition));
if(colorPosition < 9) colorPosition++;
} else {
imageView = (ImageView) convertView;
}
return imageView;
}
}
Logcat
E/AndroidRuntime: FATAL EXCEPTION: main java.lang.NullPointerException
at android.view.ViewConfiguration.get(ViewConfiguration.java:332)
at android.view.View.<init>(View.java:3254)
at android.widget.ImageView.<init>(ImageView.java:105)
you are getting Null Pointer Exception because :
1. mContext is null in ImageAdapter becuase you are using Single parameter Constructor of ImageAdapter for creating object. so pass Activity Context also as:
ia = new ImageAdapter(GameScreen.this,nextColorArray);
2. use
gridview2 = (GridView)GameScreen.this. findViewById(R.id.colorNext);
for initializing GridView in onPreExecute
Edit: I made these changes in the code.
return aL.size(); // change this in getCount()
imageView.setBackgroundColor(nextColorArray.get(position));
FullCode
public class MainActivity extends Activity{
int yellow = 0xffffff66;
int green = 0xff00EE76;
int red = 0xffff4342;
int blue = 0xff42c3ff;
int purple = 0xff9932CC;
int white = 0xFFFFFFFF;
int total_Count = 0;
int colorPosition = 0;//nextColor position
int colorPickerStart = 0;
ArrayList<Integer>nextColorArray;
ImageView imageView;
ImageAdapter ia;
private static final String TAG = MainActivity.class.getSimpleName();//log
ArrayList<Integer>colorPicker = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new upDateNextColor().execute();
}
class upDateNextColor extends AsyncTask<Void, Void, Void> {
GridView gridview2;
#Override
protected Void doInBackground(Void... voids) {
return null;
}
#Override
protected void onPostExecute(Void result) {
nextColorArray.add(blue);
nextColorArray.add(green);
nextColorArray.add(red);
nextColorArray.add(yellow);
nextColorArray.add(purple);
Collections.shuffle(nextColorArray);
}
#Override
protected void onPreExecute() {
nextColorArray = new ArrayList<Integer>(10);
gridview2 = (GridView) findViewById(R.id.gridview);
ia = new ImageAdapter(nextColorArray);
gridview2.setAdapter(ia);
nextColorArray.add(0, white);
ia.notifyDataSetChanged();
}
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList aL;
public ImageAdapter(Context c, ArrayList<Integer>aL) {
mContext = c;
this.aL = aL;
}
public ImageAdapter(ArrayList<Integer>aL) {
this.aL = aL;
}
public ImageAdapter(Context c){
mContext = c;
}
public int getCount() {
//int a = 10;
return aL.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
imageView = new ImageView(MainActivity.this);
imageView.setLayoutParams(new GridView.LayoutParams(50, 50));
imageView.setBackgroundColor(nextColorArray.get(position));
if(colorPosition < 9) colorPosition++;
} else {
imageView = (ImageView) convertView;
}
return imageView;
}
}
}
Snap shot

Android different integer array to display images in gallery

I have different integer array of drawables like this:
Integer[] imagesR = {
R.drawable.albacoretuna, R.drawable.almonds
};
Integer[] imagesACE = {
R.drawable.captopril, R.drawable.lisinopril, R.drawable.vasotec
};
Each integer array should only display which is based on user's click.
Below is what I have tried:
Gallery gallery = (Gallery) findViewById (R.id.gallery3);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("medication");
if( value.equals("Angiotensin II Receptor Blockers") ){
header.setText("Angiotensin II Receptor Blockers");
note.setText(R.string.receptorblockers);
gallery.setAdapter(new ImageAdapter.IMAGE_SET_ONE);
}
else if( value.equals("Angiotensin Converting Enzyme (ACE) Inhibitors") ){
header.setText("Angiotensin Converting Enzyme (ACE) Inhibitors");
note.setText(R.string.aceinhibitorsdescription);
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
Integer[] mImageIds = {
};
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = obtainStyledAttributes(R.styleable.HelloGallery);
// mGalleryItemBackground = a.getResourceId(
// R.styleable.HelloGallery_android_galleryItemBackground, 0);
a.recycle();
}
public ImageAdapter(Context c,Integer gallery[]) {
mContext = c;
mImageIds=gallery;
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static final int IMAGE_SET_ONE = 1;
public static final int IMAGE_SET_TWO = 2;
private int mImageSet;
public void setImageSet(int imageSet) {
mImageSet = imageSet;
}
public View getView(int pos, View convertView, ViewGroup arg2) {
ImageView i;
//= new ImageView(mContext);
if (convertView == null) { // if it's not recycled, initialize some attributes
i = new ImageView(mContext);
i.setLayoutParams(new GridView.LayoutParams(85, 85));
i.setScaleType(ImageView.ScaleType.CENTER_CROP);
i.setPadding(8, 8, 8, 8);
} else {
i = (ImageView) convertView;
}
if(mImageSet == IMAGE_SET_ONE) {
// load the correct image in...
Integer[] imagesACE = {
R.drawable.captopril, R.drawable.lisinopril, R.drawable.vasotec
};
i.setImageResource(imagesACE[pos]);
} else if(mImageSet == IMAGE_SET_TWO) {
// load the correct image in...
Integer[] imagesR = {
R.drawable.albacoretuna, R.drawable.almonds
};
i.setImageResource(imagesR[pos]);
}
//i.setImageResource(mImageIds[arg0]);
return i;
}
}
But I can't seem to figure out how to accomplish this correctly. Has anybody already tried something like this? Can you help me finish this? I'd appreciate your help. Thanks.
1) change the constructor of your ImageAdapter to be like this :
public ImageAdapter(Context c,int imageSet) {
this.mContext = c;
this.mImageSet=imageSet;
}
2) and when you try to set the adapter to your Gallery instance , use this code :
//case to display drawables in array1
gallery.setAdapter(new ImageAdapter(YourActivity.this, ImageAdapter.IMAGE_SET_ONE));
//case to display drawables in array2
gallery.setAdapter(new ImageAdapter(YourActivity.this, ImageAdapter.IMAGE_SET_TWO));

Android: making gallery infinite loop of images

I'm using a gallery in my project in which I have added four images and I want it to be infinite from both right side and left side. How do I accomplish this?
The main idea is that in your getView method, you have to use
position = position % imagesArray.length;
if (position < 0)
position = position + imagesArray.length;
imagesArray is the array that holds the images in your res folder. For example:
public class CircularGallery extends Activity {
/** Called when the activity is first created. */
private Integer[] imagesArray = { R.drawable.picture1, R.drawable.picture2, R.drawable.picture3, R.drawable.picture4, R.drawable.picture5, R.drawable.picture6 , R.drawable.picture7 };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery g = (Gallery) findViewById(R.id.gallery);
g.setAdapter(new ImageAdapter(this));
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
if (position >= imagesArray.length) {
position = position % imagesArray.length;
}
Toast.makeText(CircularGallery.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
mGalleryItemBackground = a.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount() {
return Integer.MAX_VALUE;
}
public Object getItem(int position) {
if (position >= imagesArraylength) {
position = position % mImageIds.length;
}
return position;
}
public long getItemId(int position) {
if (position >= imagesArray.length) {
position = position % imagesArray.length;
}
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
if (position >= imagesArray.length) {
position = position % imagesArray.length;
}
i.setImageResource(imagesArray[position]);
i.setLayoutParams(new Gallery.LayoutParams(80, 80));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
public int checkPosition(int position) {
if (position >= imagesArray.length) {
position = position % imagesArray.length;
}
return position;
}
}}
Also, some developers have done such a functionality and you can find sources on their blogs
http://abhinavasblog.blogspot.com/2011/09/android-infinite-looping-gallery.html
http://blog.blundellapps.com/infinite-scrolling-gallery/
if you want to set image showing on right side, just set g.setSelection(image)
My first guess is to change adapter data, i.e. if you detect that you are on the "right edge", then get your first image and add it to the end, then take second image and so on...

Application that contains gallery with images from sd card crashes onOrientation changed

i have the folowing custom adapter for a Gallery widget. everything works great except when i change screen orientation, the app crashes due to
12-03 12:45:48.897: ERROR/AndroidRuntime(3594): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
i know that the maximum VM budget is 16 mb. but how did i pass it? is there a way to clear the memory that is not used or on orientation change? i know there is a recycle method for bitmaps but how do i use it in my case?
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private Uri[] mUrls;
String[] mFiles=null;
public ImageAdapter(Context c) {
mContext = c;
readImagesFromSd();
TypedArray a = c.obtainStyledAttributes(R.styleable.Gallery1);
mGalleryItemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
public void readImagesFromSd(){
File images = new File(Environment.getExternalStorageDirectory().toString()+CameraView.FOLDER+"/");
images.mkdirs();
File[] imagelist = images.listFiles();
//Toast.makeText(mContext, String.valueOf(imagelist.length), Toast.LENGTH_LONG).show();
/*new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return ((name.endsWith(".jpg")) || (name.endsWith(".png")));
}
});*/
mFiles = new String[imagelist.length];
for (int i = 0; i < imagelist.length; i++) {
mFiles[i] = imagelist[i].getAbsolutePath();
}
mUrls = new Uri[mFiles.length];
for (int i = 0; i < mFiles.length; i++) {
mUrls[i] = Uri.parse(mFiles[i]);
}
}
public int getCount() {
// return mImageIds.length;
return mUrls.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(mImageIds[position]);
i.setImageURI(mUrls[position]);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}

Categories

Resources