问题
I already have some pictures on my drawable folder from android project.
I create some objects (Agents) and then I need to set the imageView
with this picture I saved on database.
So, I am saving the picture as String photoPath
:
Uri path1 = Uri.parse("android.resource://"+BuildConfig.APPLICATION_ID+"/" + R.drawable.agent1);
String photoAg1 = path1.getPath();
ag1.setPhotoPath(photoAg1);
(I have already tried path1.toString.)
Ok, no problems until there.
This object is shown at a listView
with ImageView
.
To show it there, I am doing:
ImageView photo = (ImageView) view.findViewById(R.id.list_cell_photo);
System.out.println(agent.getPhotoPath());
Bitmap bitmap = BitmapFactory.decodeFile(agent.getPhotoPath());
Bitmap lowdefbitmap = Bitmap.createScaledBitmap(bitmap,300,300,true);
photo.setImageBitmap(lowdefbitmap);
The problem is on the createScaledBitmap
.
Error above:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:714)
Return from the System.out.println
: /2131099732
If I put path1.toString
the return is: android.resource://com.aa.xlambton/2131099732
Ive already took a look at: Create a Bitmap/Drawable from file path
Android get image path from drawable as string
Get absolute path of android drawable image
BitmapFactory: Unable to decode stream: java.io.FileNotFoundException even when file IS actually there
I think I am saving this path wrong, because Bitmap
cannot decode the file, so it is going empty to createdScaledBitmap
.
Can someone help me please?
回答1:
You can save Reference Id R.drawable.img_name
as integer rather than saving path.
When you need to manipulate this drawable you can use that id instead of R.drawable.img_name
.
If you need a bitmap from this drawable follow this
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
saved_id);
回答2:
You can try to use this method:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.id.youResourceId);
回答3:
try like this
public int getImage(String imageName) {
int drawableResourceId = context.getResources().getIdentifier(imageName, "drawable", context.getPackageName());
return drawableResourceId;
}
回答4:
In my project, I want to get some images from project folder. So there is a way to get your images in java class, however it is simple in .xml file. it is clearly done by assets Manger in android.
Follow this link
Notice: AssetManager assetManager = getAssets();
must be in youractvity.java file.
来源:https://stackoverflow.com/questions/47788215/how-to-get-path-from-image-on-drawable-folder-and-set-as-image-view-bitmap