2016-11-30 26 views
-1

enter image description here簡單的代碼來讀取圖像視圖 的SD卡,並顯示以下圖像文件的代碼安卓:讀取圖像視圖給錯誤的SD卡和顯示文件

import java.io.File; 

import android.support.v7.app.ActionBarActivity; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.ImageView; 


public class MainActivity extends ActionBarActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     File imgFile = new File("/storage/extSdCard/DCIM/Camera/Test.jpg"); 

     if(imgFile.exists()){ 

      Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); 

      ImageView myImage = (ImageView) findViewById(R.id.imgView); 

      myImage.setImageBitmap(myBitmap); 

     } 
     setContentView(R.layout.activity_main); 
    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.main, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 
} 

我我使用三星S3作爲Android設備。我收到的錯誤是logcat中的「java.Lang.RuntimeException:無法啓動活動組件」。還考慮了所需的許可。 需要使代碼正確工作的建議。 (也應用程序已成功安裝在設備中,但無法正常運行)。

+2

顯示你的logcat請 – cuoka

+0

@cuoka圖像的logcat被添加 – farhan

回答

1

本聲明:

ImageView myImage = (ImageView) findViewById(R.id.imgView); 

不能早於setContentView();

做我想你得到你做到了myImage將是無效的方式,因此NullPointerException

+0

非常感謝它現在工作正常。 – farhan

相關問題