2017-05-13 63 views
0

圖像爲了的全路徑名的圖像發送到服務器,同時獲取圖片的路徑,將下面的代碼是用來錯誤而獲取Android中

private String getPath(Uri uri){ 
     String path = null; 
     Cursor cursor = null; 
     try { 
      Toast.makeText(this,"Beginning of getPath()", Toast.LENGTH_LONG).show(); 
      cursor=getContentResolver().query(uri,null,null,null,null); 
      cursor.moveToFirst(); 
      String document_id=cursor.getString(0); 
      document_id=document_id.substring(document_id.lastIndexOf(".")+1); 

      cursor=getContentResolver().query(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,null,MediaStore.Images.Media._ID+"=?",new String[]{document_id},null); 
      cursor.moveToFirst(); 
      path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); 
      Toast.makeText(this,"At the end of getPath()", Toast.LENGTH_LONG).show(); 

     } 
     catch(Exception e){ 
      e.printStackTrace(); 
     } finally { 
      cursor.close(); 
     } 


     return path; 
    } 

我設定了兩個麪包方法在這裏檢查控制流程。我在方法的開始處得到第一個吐司消息,但沒有得到下一個......這反映了該代碼部分中的錯誤... 這裏可能出現了什麼問題。 的Android棧跟蹤給出下列」

android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 

在如下因素線

path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); 

回答

1

爲了將圖像發送到服務器,獲得的圖像的路徑,使用了下面的代碼,而

該代碼不適用於任意Uri值。

什麼可能出現了問題這裏

您正在嘗試導出一個Uri文件路徑。

使用ContentResolveropenInputStream()得到Uri標識的內容InputStream。然後,或者:

  • 直接使用InputStream上傳內容,如果你的HTTP客戶端API支持,或

  • 使用InputStreamFileOutputStream(上一些你控制文件,如在getCacheDir())製作一份內容。然後,上傳副本,完成後刪除副本。