2015-12-04 22 views
1

我有一種從畫廊中檢索圖像的方法,對我來說工作得很好。我的問題是,我在三個不同的活動中使用它,並覺得我應該創建一個可以調用的類來獲取圖像。創建一個專門用於檢索圖像的類?

這是我的代碼:

private void getImage() { 
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, 
      android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
    // Start the Intent 
    startActivityForResult(galleryIntent, RESULT_LOAD_IMG); 
} 

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

    mRLMenuParams.setVisibility(View.GONE); 
    mRLImageParams.setVisibility(View.VISIBLE); 

    bmSelectedImage = null; 

    try { 
     // When an Image is picked 
     if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK 
       && null != data) { 
      // Get the Image from data 

      Uri selectedImage = data.getData(); 
      String[] filePathColumn = { MediaStore.Images.Media.DATA }; 

      // Get the cursor 
      Cursor cursor = getContentResolver().query(selectedImage, 
        filePathColumn, null, null, null); 
      // Move to first row 
      cursor.moveToFirst(); 

      int columnIndex = cursor.getColumnIndex(filePathColumn[0]); 
      imgDecodableString = cursor.getString(columnIndex); 
      cursor.close(); 
      ImageView imSelectedImage = (ImageView) findViewById(R.id.imageView_image); 
      imSelectedImage.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString)); 
      Bitmap bmImage = Bitmap.createBitmap(BitmapFactory.decodeFile(imgDecodableString)); 
      bmSelectedImage = bmImage.copy(Bitmap.Config.ARGB_8888, true); 
     } else { 
      Toast.makeText(this, "You haven't picked Image", Toast.LENGTH_LONG).show(); 
     } 
    } catch (Exception e) { 
     Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show(); 
    } 
} 

當我嘗試把這個在自己的課,我不能讓它工作,傳遞上下文時也是如此。看起來我需要把它變成一項活動,如果是的話,我認爲沒有把它分開。我是否錯過了能讓我把它放在自己的課堂並返回圖像的東西?

謝謝!

回答