I want to set an image on a button in my app, dynamically from a file on the sdcard. I have tried this code but it is not working. I have tried to convert the image to a bitmap object and I set that object to ImageButton, but it isn't showing anything. How can I solve this issue?
My code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File imageFile = new File("/sdcard0/DCIM/camera/jbn.jpg");
Bitmap bmp = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
ImageButton button1 = (ImageButton)findViewById(R.id.imgBtn);
button1.setImageBitmap(bmp);
}
XML
<ImageButton
android:layout_width="200dip"
android:layout_height="200dip"
android:id="@+id/imgBtn"
/>
Algorithm
void loadPic()
{
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String pathName = baseDir + "/DCIM/camera/";
File parentDir=new File(pathName);
File[] files = parentDir.listFiles();
Date lastDate;
String lastFileName;
boolean isFirstFile = true; //just temp variable for being sure that we are on the first file
for (File file : files) {
if(isFirstFile){
lastDate = new Date(file.lastModified());
isFirstFile = false;
}
if(file.getName().endsWith(".jpg") || file.getName().endsWith(".jpeg")){
Date lastModDate = new Date(file.lastModified());
if (lastModDate.after(lastDate)) {
lastDate = lastModDate;
lastFileName = file.getName();
}
}
}
Try with something simple like this for example: