2016-03-31 52 views
0

我是(初學者android)試圖獲取用戶從圖庫中選擇的圖像的真實路徑(例如:image_name.jpg等)。從圖庫中選擇圖像後,從android URI獲得真實路徑

if (requestCode == SELECT_FILE) { 
     Uri selectedImage = data.getData(); 
     Bitmap bitmapImage; 
     try { 
       bitmapImage =decodeBitmap(selectedImage); 
       photoImage = (ImageView) findViewById(R.id.photoImage); 
       photoImage.setImageBitmap(bitmapImage); 
       photoName = (TextView) findViewById(R.id.designPhoto); 
       File thePath = new File(getRealPathFromURI(selectedImage)); 
       photoName.setText(getRealPathFromURI(selectedImage)); 
     } catch (Exception e) { 
       e.printStackTrace(); 
     } 
} 


private String getRealPathFromURI(Uri contentURI) { 

    String thePath = "no-path-found"; 
    String[] filePathColumn = {MediaStore.Images.Media.DATA}; 
    Cursor cursor = getContentResolver().query(contentURI, filePathColumn, null, null, null); 
    if(cursor.moveToFirst()){ 
     int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
     thePath = cursor.getString(columnIndex); 
    } 
    cursor.close(); 
    return thePath; 
} 

,但我沒有收到在photoName TextView的東西也試過很多代碼和導遊,但沒有sucess。

但是當我

photoName.setText(selectedImage.getPath()); 

嘗試過我正

/document/image:n (where n=any numbers) ex:/document/image:147 

,但我希望有一個正確的文件名或路徑例如:​​或/path/image_name.png

從去年3嘗試它幾個小時,如果有人能幫助我,這將是非常棒的。謙虛感謝提前。

+1

爲什麼你認爲它有「真實路徑」?你爲什麼不使用'MediaStore.Images.Media.DISPLAY_NAME'? – Selvin

+0

因爲我是新的android編碼,浪費3小時後我雖然我必須問問題在哪裏,爲什麼我做錯了 –

+0

@Selvin先生謝謝了很多'MediaStore.Images.Media.DISPLAY_NAME'的作品像魅力... –

回答

1

我得到它的工作使用

MediaStore.Images.Media.DISPLAY_NAME 

更新和工作代碼可能會幫助別人:

private String getRealPathFromURI(Uri contentURI) { 

    String thePath = "no-path-found"; 
    String[] filePathColumn = {MediaStore.Images.Media.DISPLAY_NAME}; 
    Cursor cursor = getContentResolver().query(contentURI, filePathColumn, null, null, null); 
    if(cursor.moveToFirst()){ 
     int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
     thePath = cursor.getString(columnIndex); 
    } 
    cursor.close(); 
    return thePath; 
} 
相關問題