我正在編寫一個代碼,使用戶可以從圖庫中選擇個人資料圖片。到目前爲止,代碼如下。 (1)在活動下的字段中,我聲明瞭一個按鈕,一個imageview和一個靜態整數。從圖庫中選擇一個圖片Android
private Button btnChooseProfile;
private ImageView ivProfile;
private static final int RESULT_LOAD_IMAGE = 1;
(2)現在,我通過onCreate方法在屏幕上看到它們。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate();
setContentView(R.layout.activity_register);
btnChooseProfile = (Button) findViewById(R.id.btnChooseProfile);
ivProfile = (ImageView) findViewById(R.id.ivProfile);
btnChooseProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
};
(3)最後,我推翻了onActivityResult方法來定義一下btnChooseProfile按鈕後,會發生什麼。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imagePath = cursor.getString(columnIndex);
cursor.close();
ivProfile.setImageBitmap(BitmapFactory.decodeFile(imagePath));
}
}
當我運行代碼時,我設法訪問該庫。選擇圖像後,我會希望imageview包含一張選定的圖片,但不知何故應用程序會結束。
我已經閱讀了很多在網站上提出的解決方案,而且代碼片段本身似乎沒有問題。如果我錯過了一些東西,請給我一些建議,這將非常感激。
謝謝。
編輯這裏的logcat。 (日誌級別:調試)
07-13 15:15:25.961 28110-28110/com.marshall.gruppo E/﹕ Device driver API match
Device driver API version: 29
User space API version: 29
07-13 15:15:25.961 28110-28110/com.marshall.gruppo E/﹕ mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Tue Jul 22 19:59:34 KST 2014
07-13 15:15:26.051 28110-28110/com.marshall.gruppo D/OpenGLRenderer﹕ Enabling debug mode 0
07-13 15:15:28.726 28110-28110/com.marshall.gruppo D/dalvikvm﹕ GC_FOR_ALLOC freed 153K, 6% free 14269K/15064K, paused 9ms, total 9ms
07-13 15:15:28.751 28110-28110/com.marshall.gruppo D/AbsListView﹕ Get MotionRecognitionManager
07-13 15:15:28.831 28110-28110/com.marshall.gruppo D/dalvikvm﹕ GC_FOR_ALLOC freed 115K, 6% free 14329K/15088K, paused 12ms, total 12ms
07-13 15:15:28.861 28110-28110/com.marshall.gruppo I/dalvikvm-heap﹕ Grow heap (frag case) to 33.649MB for 19955728-byte allocation
07-13 15:15:28.876 28110-28119/com.marshall.gruppo D/dalvikvm﹕ GC_FOR_ALLOC freed 1K, 3% free 33816K/34580K, paused 13ms, total 13ms
07-13 15:15:33.401 28110-28110/com.marshall.gruppo W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
07-13 15:15:37.681 28110-28110/com.marshall.gruppo D/AbsListView﹕ onDetachedFromWindow
的logcat登錄請。 –
@AnandSingh編輯。但logcat似乎並沒有太多顯示。 – MarshallLee