问题
I have this code:
String filePath = getActivity().getFileStreamPath("into11.png").getAbsolutePath();
if(Drawable.createFromPath(filePath)!=null){
img.setImageDrawable(Drawable.createFromPath(filePath));
}
else{
Log.d("nulllllllllllllllllllllllllllllllll","yessssssssssssssssssssssssssss");
}
the filepath is getting the right path of the image "data/data/.../intro11.png" but Drawable.createFromPath(filePath) is null so what's the cause of this?
回答1:
Use this code:
File drawableFile = new File(getApplicationContext().getFilesDir().getAbsolutePath()+"/into11.png");
if(Drawable.createFromPath(drawableFile.getAbsolutePath())!=null){
img.setImageDrawable(Drawable.createFromPath(drawableFile.getAbsolutePath()));
}
else{
Log.d("nulllllllllllllllllllllllllllllllll","yessssssssssssssssssssssssssss");
}
I hope this helps and solves your problem.
回答2:
User moh.suhkni posted a comment in the original question that almost completely solved it for me.
He posted:
Uri uri = Uri.fromFile(filePath);
img.setImageURI(uri);
The solution that I ended up needing was:
final Uri uri = Uri.parse(url);
final String path = uri.getPath();
final Drawable drawable = Drawable.createFromPath(path);
img.setImageDrawable(drawable);
Because for some reason this wasn't working:
final Drawable drawable = Drawable.createFromPath(url);
// drawable ended up being null
img.setImageDrawable(drawable);
Android's Drawable.createFromPath() method must not like paths beginning with file://
, as mine did. Using Uri.parse() fixed that issue for me.
Hope that this can help!
回答3:
I had this same problem and for me I was trying to make a Drawable from a file that I had previously saved to internal storage. My problem ended up being that my file was incorrectly saved so it didn't create the drawable. It also threw errors in the debug console.
I hope this helps somebody.
This was my code to save (The bit commented out is what I was missing):
URL url = new URL(remoteFile);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(is);
FileOutputStream fos = mainActivity.openFileOutput(filename,
Context.MODE_PRIVATE);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
// bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
byte[] byteArray = outStream.toByteArray();
fos.write(byteArray);
fos.close();
I'd still like to know to just save files byte by byte so I don't have to open the image and recompress it.
回答4:
Drawable d = getResources().getDrawable(R.drawable.smiley);
To show it in image view
ImageView i = new ImageView(this);
i.setImageResource(R.drawable.smiley);
or in your xml file
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/smiley"/>
来源:https://stackoverflow.com/questions/19130464/drawable-createfrompathfilepath-returning-null-although-the-file-exist