2016-03-08 172 views
0

我發現了這段代碼,並試圖在我的應用程序中實現,它打開畫廊,讓我選擇一張照片,然後應用程序停止工作並關閉。從照片庫中檢索照片

這是我第一次嘗試上傳圖像到mysql,我一開始就卡住了。

buttonChoose.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) 
      { 
       showFileChooser(); 
      } 
     }); 

private void showFileChooser() { 
     Intent intent = new Intent(); 
     intent.setType("image/*"); 
     intent.setAction(Intent.ACTION_GET_CONTENT); 
     startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST); 
    } 




@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) 
    { 
     Uri filePath = data.getData(); 

     try 
     { 
      bitmap = MediaStore.Images.Media.getBitmap(MainActivity.this.getContentResolver(), filePath); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     imageView.setImageBitmap(bitmap); 
    } 
} 

回答

1
Uri filePath = data.getData(); 

這將是毫無意義的大多數Uri值。

Uri填充ImageView的最佳解決方案是使用a third-party image loading library,如Picasso

如果你堅持說,這樣做你自己,你將需要fork一個後臺線程,使用ContentResolveropenInputStream()獲得由Uri支持內容的InputStream,使用BitmapFactorydecodeStream()獲得Bitmap,然後(上主應用程序線程)使用Bitmap更新ImageView

+0

應該這樣做嗎? Uri imageUri = data.getData(); Picasso.with(this).load(imageUri).into(imageView); – jack

+0

@jack:是的,看起來不錯,假設'this'是你的'Activity'。這將處理在後臺線程中加載圖像並將其放入你的'ImageView'中。畢加索還有許多其他的配置選項(例如縮放控制),以防您需要它們。 – CommonsWare

+0

好吧,應用程序停止崩潰,但沒有任何顯示在imageView .... imageuri =「內容://媒體/外部/圖像/媒體/ 182」......聽起來沒錯嗎? – jack