File not added to gallery android

user2429689 picture user2429689 · Jul 8, 2013 · Viewed 8.5k times · Source

This app i am making is taking pictures and saving it to sdcard but the images are not being shown in gallery...Is there something wrong with my code

public void takepicture(View view){
     try{
           String state = Environment.getExternalStorageState();
             if (Environment.MEDIA_MOUNTED.equals(state)) {
                    //To store public files
                File directory=new File(Environment.getExternalStorageDirectory()
                        , "Myapp Pictures");                        
                    if(!directory.exists())
                        directory.mkdir();
                // Create an image file name
                    String timeStamp = 
                        new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                    String imageFileName = "Img" + timeStamp + ".jpg";
                        file=new File(directory, imageFileName);
                   if(!file.exists())
                       file.createNewFile();                    
             }
    }catch(Exception e){
    e.getCause();   
    }
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    mImageUri=Uri.fromFile(file);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
    startActivityForResult(takePictureIntent, actioncode);          
    }
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {                             
            if(requestCode == actioncode){                  
                    if((file.length())==0){
                        file.delete();
                    }                   
            try{
                if(resultCode==Activity.RESULT_OK){ 


                         Bitmap photo = (Bitmap) data.getExtras().get("data");
                         imageView.setImageBitmap(photo);   
                    }

                    galleryAddPic(file.toString()); 
                }
            }catch(Exception e){
                e.getCause();
            }
        }
    }

The image is being shown in the imageview as well as saved to the desired directory but now shown in gallery And finally this is the code for adding to gallery

public void galleryAddPic(String file) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(file);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

Answer

aehs29 picture aehs29 · Jul 8, 2013

Try this:

public void galleryAddPic(String file) {
    File f = new File(file);
    Uri contentUri = Uri.fromFile(f);
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,contentUri);
    sendBroadcast(mediaScanIntent);
}