Loading image dynamically from drawer crashing the app - android

I am very new to android. I have to load images dynamically in to recycler view row. I am using the following code and application get crashing due to null object.
String uri = "#drawable/menu_howtouse";
int imageResource = this.context.getResources().getIdentifier(uri, null, this.PACKAGE_NAME);
Drawable res = this.context.getResources().getDrawable(imageResource);
holder.iconImageView.setImageDrawable(res);

The crash could be because the context is null.
Try this code,
int imageResource = this.context.getResources().getIdentifier("menu_howtouse", "drawable", this.PACKAGE_NAME);
Make sure you have initialized holder.iconImageView as follows,
holder.iconImageView = (ImageView) convertView.findViewById(R.id.iconImageView);

The second parameter can be null, but you shouldn't need to set that.
You should be able to use this
context.getResources().getIdentifier("menu_howtouse", "drawable", this.PACKAGE_NAME);
If anything there is throwing a nullpointer, it is probably the context because those other methods don't throw any exceptions

Is the same image to be added to every row you can do this:
holder.iconImageView.setImageResource(R.drawable.menu_howtouse);
OR
If multiple images form drawable to be added, then make list of all the Drawables
List<int> imageList = new ArrayList<int>();
imageList.add(R.drawable.iamge1);
imageList.add(R.drawable.iamge2);
imageList.add(R.drawable.iamge3);
pass this to adapter class
Adapter adp = new Adapter(context, imageList);
Then in onBindViewHolder do this
holder.iconImageView.setImageResource(imageList.get(position));
-- OR --
you can try Picasso or glide, they are very simple to integrate

Related

Setting image variable in fragments

Sorry, I'm still a beginner in coding, but how do I make this code work? actor art is a variable I have from an array.
And it's the name of a image I have in my drawable. This line of code works on any activity type but not on fragments. How do I set image from a variable from an array?
int imageId = AppUtil.getImageIdFromDrawable(this, actorart);
ImageView ivCoverArt = view.findViewById(R.id.imgactor);
ivCoverArt.setImageResource(imageId);
The error for this is that this cannot be used.
This also doesn't work:
ImageView imageView= view.findViewById(R.id.imgactor);
imageView.setImageResource(actorart);
The error here is that actorart is a String but setImageResource is an action for an int.
You are correct, setImageResource() takes in an integer, more specifially the ID of the resource.
To get the ID, you can use the following:
int id = getResources().getIdentifier("yourpackagename:drawable/" + actorart, null, null);
this cannot be used cause the instance you are refering with this is a Fragment, and I'm pretty sure you need a Context parameter.
To fix it get a valid Context:
int imageId = AppUtil.getImageIdFromDrawable(getActivity(), actorart);

Setting the resource of an ImageView using a CursorLoader

Sorry for such an open-ended question, but I'm new to Android and I genuinely looked all over for an answer and couldn't find anything. I'm wanting to store some sort of information that references an image in a SQLite table, and then use a SimpleCursorAdapter to move that data to an ImageView. I thought that, if I store an integer (the resource ID) and then have the adapter set to the correct view, the resource of the view would be updated to that ID, but that didn't work. Is there any other way to do what I'm wanting to do?
Thanks in advance :)
Edit 1:
This is what I'm doing right now. I'm storing the drawable's ID in the table and then setting the SimpleCursorAdapter to a View whose resource I want to be the drawable. Here's the code I use to store the info:
ContentValues values = new ContentValues();
values.put(SubwayContract.ROUTE_IMG, R.drawable.red_circle);
values.put(SubwayContract.ROUTE, "R");
values.put(SubwayContract.FINAL_STATION, "Howard-Bound");
values.put(SubwayContract.ARRIVAL_TIME, "5:24:00");
final Uri uri = mContentResolver.insert(SubwayContract.CONTENT_URI, values);
The second line stores the image ID. Here's the code I have that sets the adapter:
private final int URL_LOADER = 0;
private String[] mProjections = {SubwayContract._ID, SubwayContract.ROUTE_IMG, SubwayContract.ROUTE, SubwayContract.FINAL_STATION, SubwayContract.ARRIVAL_TIME};
private int[] mTo = {R.id._id, R.id.arrival_icon, R.id.arrival_letter, R.id.arrival_dest, R.id.arrival_time};
private SimpleCursorAdapter mAdaptor = null;
...
getLoaderManager().initLoader(URL_LOADER, null, ArrivalsFragment.this);
ListView mListView = (ListView) rootView.findViewById(R.id.arrivals_list_view);
mAdaptor = new SimpleCursorAdapter(
rootView.getContext(),
R.layout.arrivals_list_item,
null,
mProjections,
mTo,
0
);
mListView.setAdapter(mAdaptor);
The View's ID is R.id.arrival_icon, which is a View. I know that there's no error in the cursor or the loader, as everything works fine if I take out the View and ID. How can I fix this?
You can save resource Id of the image (which is in drawable folder) into database.
You can try as below:
int resID = mContext.getResources().getIdentifier(image_name, "drawable", mContext.getPackageName());

How to store drawable in an array

I want to download a bunch of images and would like to store it as drawable in an array. So I tried declaring a drawable array.But it returns me nullPointer exception when I access that array.
My question is, how to declare an array type as drawable ?
an array of drawables would be declared like:
int numDrawables = 10;
Drawable[] drawableArray = new Drawable[numDrawables];
to fill the array:
for(int i = 0; i < numDrawables; i++){
// get a drawable from somewhere
Drawable drawable = new Drawable();
drawableArray[i] = drawable;
}
to access the array:
Drawable aDrawable = drawableArray[0];
This is basic java, If you are getting null pointer exceptions, you are doing something wrong.
you can use an hashMap , and put the keys as urls for example , and to value is the drawable that you download :
HashMap<String,Drawable> myDrawables = new HashMap<String,Drawable>();
//before you download the images, you can test if your drawable is already downloaded,
// with looking for his url in the Hashmap ,
.....
myDrawables.put(urlOfYourDrawable, yourDrawable);
If you want to store list of elements(any type) dynamically use the classes in the collection. why because Array size is static.
Example:
ArrayList<Generic> list=new ArrayList<Generic>();
list.add(Generic);

trying to use ArrayList to hold image resources

In my app, I have a bunch of images in my drawable folder which I select at random and display using imageView. I've been told about ArrayList's which can add/remove objects from the list...in order to prevent image repeats, some sample code I used below:
// create an array list
ArrayList imageHolder = new ArrayList();
int remaining = 10;
public void initArrayList(){
// add elements to the array list
imageHolder.add((int)R.drawable.child0);
imageHolder.add((int)R.drawable.child1);
imageHolder.add((int)R.drawable.child2);
imageHolder.add((int)R.drawable.child3);
imageHolder.add((int)R.drawable.child4);
imageHolder.add((int)R.drawable.child5);
imageHolder.add((int)R.drawable.child6);
imageHolder.add((int)R.drawable.child7);
imageHolder.add((int)R.drawable.child8);
imageHolder.add((int)R.drawable.child9);
}
//get random number within the current range
int randInt = new Random().nextInt((remaining-1));
//update the imageView config
ImageView image = (ImageView) findViewById(R.id.shuffleImageView);
image.setImageResource(imageHolder.get(randInt));
Eclipse reports that image.setImageResource cannot use an object argument, which is what is provided by arrayList. The actual argument should be int. Any clue how to get around this??
Thanks in advance!
Use List<Integer> imageHolder = new ArrayList<Integer>();
ArrayList contains Objects, always, never primitive types. When you set ints into it, they are autoboxed to Integer objects, when you get them back, you get Integer objects as well. A short fix will be:
image.setImageResource((int)imageHolder.get(randInt));
Be careful though, unboxing a null pointer will cause a NullPointerException, So make sure your randInt is in the range of the arraylist.
EDIT:
I totally missed that, but You initialize your ArrayList like that:
ArrayList imageHolder = new ArrayList();
Which creates ArrayList of Objects. instead, initialize the ArrayList like the following to create ArrayList of integers:
List<Integer> imageHolder = new ArrayList<Integer>();

Displaying images from a specific folder on the SDCard using a gridview

I'm attempting to create a gridview that is loaded with images from a specific folder that resides on an SDCard. The path to the folder is known, ("/sdcard/pictures") , but in the examples I've seen online I am unsure how or where to specify the path to the pictures folder I want to load images from. I have read through dozens of tutorials, even the HelloGridView tutorial at developer.android.com but those tutorials do not teach me what i am seeking.
Every tutorial I have read so far has either:
A) called the images as a Drawable from the /res folder and put them into an array to be loaded, not using the SDCard at all.
B) Accessed all pictures on the SDCard using the MediaStore but not specifying how to set the path to the folder I want to display images form
or
C) Suggested using BitmapFactory, which I haven't the slightest clue how to use.
If I'm going about this in the wrong way, please let me know and direct me toward the proper method to do what I'm trying to do.
OK, after many iterations of trying, I finally have an example that works and I thought I'd share it. My example queries the images MediaStore, then obtains the thumbnail for each image to display in a view. I am loading my images into a Gallery object, but that is not a requirement for this code to work:
Make sure you have a Cursor and int for the column index defined at the class level so that the Gallery's ImageAdapter has access to them:
private Cursor cursor;
private int columnIndex;
First, obtain a cursor of image IDs located in the folder:
Gallery g = (Gallery) findViewById(R.id.gallery);
// request only the image ID to be returned
String[] projection = {MediaStore.Images.Media._ID};
// Create the cursor pointing to the SDCard
cursor = managedQuery( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
MediaStore.Images.Media.DATA + " like ? ",
new String[] {"%myimagesfolder%"},
null);
// Get the column index of the image ID
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
g.setAdapter(new ImageAdapter(this));
Then, in the ImageAdapter for the Gallery, obtain the thumbnail to display:
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(context);
// Move cursor to current position
cursor.moveToPosition(position);
// Get the current value for the requested column
int imageID = cursor.getInt(columnIndex);
// obtain the image URI
Uri uri = Uri.withAppendedPath( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, Integer.toString(imageID) );
String url = uri.toString();
// Set the content of the image based on the image URI
int originalImageId = Integer.parseInt(url.substring(url.lastIndexOf("/") + 1, url.length()));
Bitmap b = MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(),
originalImageId, MediaStore.Images.Thumbnails.MINI_KIND, null);
i.setImageBitmap(b);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
I guess the most important section of this code is the managedQuery that demonstrates how to use MediaStore queries to filter a list of image files in a specific folder.
You need to do a few more steps than the GridView tutorial on developer.android.com. Using the following tutorial
http://developer.android.com/resources/tutorials/views/hello-gridview.html
You'll want to add a method to create ImageView's of the files from your sd card:
Create/add a Vector to your class variables (to hold a list of ImageViews):
private Vector<ImageView> mySDCardImages;
Initialize the vector:
mySDCardImages = new Vector<ImageView>();
Create a method to load images:
List<Integer> drawablesId = new ArrayList<Integer>();
int picIndex=12345;
File sdDir = new File("/sdcard/pictures");
File[] sdDirFiles = sdDir.listFiles();
for(File singleFile : sdDirFiles)
{
ImageView myImageView = new ImageView(context);
myImageView.setImageDrawable(Drawable.createFromPath(singleFile.getAbsolutePath());
myImageView.setId(picIndex);
picIndex++;
drawablesId.add(myImageView.getId());
mySDCardImages.add(myImageView);
}
mThumbIds = (Integer[])drawablesId.toArray(new Integer[0]);
Then down in your ImageAdapter method, change
imageView.setImageResource(mThumbIds[position]);
to
imageView.setImageDrawable(mySDCardImages.get(position).getDrawable());
Remove from the ImageAdapter the initialization of mThumbIds. (it should be up with the definition of mySDCardImages. Accessible to both class methods.)
(Quick and dirty version) Make sure to test your path, etc and catch any Exceptions.
In your case BitmaFactory might be a good way to go. Example:
File dir = new File( "/sdcard/pictures" );
String[] fileNames = dir.list(new FilenameFilter() {
boolean accept (File dir, String name) {
if (new File(dir,name).isDirectory())
return false;
return name.toLowerCase().endsWith(".png");
}
});
for(string bitmapFileName : fileNames) {
Bitmap bmp = BitmapFactory.decodeFile(dir.getPath() + "/" + bitmapFileName);
// do something with bitmap
}
Not time to test this but should work ;-)
read this link: http://androidsamples.blogspot.com/2009/06/how-to-display-thumbnails-of-images.html
it shows how to use both mediastore and bitmapfactory.
the way you should chose depends on what exactly you need. if you have a static set of images, it's much better idea to put them to drawables, i think, cause this way it's faster and you don't rely on sd card, which can be removed, corrupt or files could be renamed/deleted
if images are dynamic, then use mediastore or bitmap factory. but keep in mind that putting images into array or something it's quite memory consuming, so you can end up having outofmemory exception
Looks like you want custom gallerry, it will take much time for you,
I suggest you get Custom Camera Gallery for your working.
You will get Photos/Videos in Grid View as you want.
for Kotlin code see the answer of this question
the idea is alslo applicable for java (but you need to modify the code)

Categories

Resources