File not added to gallery android

邮差的信 提交于 2019-11-28 02:06:53

问题


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);
    }

回答1:


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);
}


来源:https://stackoverflow.com/questions/17534853/file-not-added-to-gallery-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!