2014-02-16 46 views
0

我想從我的目錄中加載一個特定的圖像到我的應用程序的ImageView,但它不工作。整個事情變得空白。有人可以看一看,看看我的代碼出錯了嗎?謝謝!我的圖像無法加載到我的ImageView中。什麼地方出了錯?

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_image_viewer); 

    ImageView imageView = (ImageView) findViewById(R.id.iv); 

    try { 
     //this toast below appears 
     Toast.makeText(getApplicationContext(), "try", Toast.LENGTH_LONG).show(); 

     //below is the path for the image 
     Uri uri = Uri.parse("file://sdcard/myFoodDiary/snaps/default.jpg"); 

     System.out.println("Image URI: " + uri.toString()); 
     imageView.setImageURI(uri); 

    } catch (Exception e) { 
     // TODO: handle exception 
     Toast.makeText(getApplicationContext(), "oops", Toast.LENGTH_LONG).show(); 
    } 

} 
+0

將圖像放到其他地方 - 您以前成功訪問過的地方 - 然後看看它是否有效。無論結果如果它有效或無效 - 你都會收集一些信息。 – Obversity

+0

您是否添加了讀取SDCard的權限? –

+0

@Obversity,它應該工作,雖然我從來沒有試過在別處訪問它。 – altern4te

回答

2

我覺得這不是一個有效的路徑:

Uri.parse("file://sdcard/myFoodDiary/snaps/default.jpg"); 

嘗試

Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/myFoodDiary/snaps/default.jpg"); 

可是我最好還是做一些像

File file = new File (Environment.getExternalStorageDirectory() + "/myFoodDiary/snaps/default.jpg"); 
ImageView imageView = (ImageView) findViewById(R.id.iv); 
imageView.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath())); 
+0

嗯,它沒有工作......仍然是空白。 – altern4te

+0

我編輯了我的回答 –

+1

錯過了myFoodDiary前面的「/」,但是否則真棒!謝謝! – altern4te

0

任何有興趣,正確的代碼爲Artoo Detoo指出:

File file = new File (Environment.getExternalStorageDirectory() + "/myFoodDiary/snaps/default.jpg"); 
ImageView imageView = (ImageView) findViewById(R.id.icon); 
imageView.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath())); 
相關問題