Android 通过Gallery选取图片

来源:互联网 发布:如何分期买手机淘宝 编辑:程序博客网 时间:2024/04/28 01:43
By madpublic class BrowsePicture extends Activity {    //YOU CAN EDIT THIS TO WHATEVER YOU WANT    private static final int SELECT_PICTURE = 1;    private String selectedImagePath;    //ADDED    private String filemanagerstring;    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        ((Button) findViewById(R.id.Button01))        .setOnClickListener(new OnClickListener() {            public void onClick(View arg0) {                // in onCreate or any event where your want the user to                // select a file                Intent intent = new Intent();                intent.setType("image/*");                intent.setAction(Intent.ACTION_GET_CONTENT);                startActivityForResult(Intent.createChooser(intent,                        "Select Picture"), SELECT_PICTURE);            }        });    }    //UPDATED    public void onActivityResult(int requestCode, int resultCode, Intent data) {        if (resultCode == RESULT_OK) {            if (requestCode == SELECT_PICTURE) {                Uri selectedImageUri = data.getData();                //OI FILE Manager                filemanagerstring = selectedImageUri.getPath();                //MEDIA GALLERY                selectedImagePath = getPath(selectedImageUri);                //DEBUG PURPOSE - you can delete this if you want                if(selectedImagePath!=null)                    System.out.println(selectedImagePath);                else System.out.println("selectedImagePath is null");                if(filemanagerstring!=null)                    System.out.println(filemanagerstring);                else System.out.println("filemanagerstring is null");                //NOW WE HAVE OUR WANTED STRING                if(selectedImagePath!=null)                    System.out.println("selectedImagePath is the right one for you!");                else                    System.out.println("filemanagerstring is the right one for you!");            }        }    }    //UPDATED!    public String getPath(Uri uri) {        String[] projection = { MediaStore.Images.Media.DATA };        Cursor cursor = managedQuery(uri, projection, null, null, null);        if(cursor!=null)        {            //HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL            //THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA            int column_index = cursor            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);            cursor.moveToFirst();            return cursor.getString(column_index);        }        else return null;    }
原创粉丝点击