2013-07-02 1 views
2

outOfMemory 오류가 발생하면 AsyncTask를 사용하여 비트 맵을로드하려고 했으므로 안드로이드 개발자 웹 사이트에서이 코드 샘플을 얻었고 모든 것이 함께 작동하는 데 문제가 있습니다.비트 맵을로드하기 위해 asynctask를 가져 오는 데 문제가 발생했습니다.

public class BitmapLoader { 

public static int calculateInSampleSize(BitmapFactory.Options options, 
     int reqWidth, int reqHeight) { 
    // Raw height and width of image 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 

     // Calculate ratios of height and width to requested height and 
     // width 
     final int heightRatio = Math.round((float) height 
       /(float) reqHeight); 
     final int widthRatio = Math.round((float) width/(float) reqWidth); 

     // Choose the smallest ratio as inSampleSize value, this will 
     // guarantee 
     // a final image with both dimensions larger than or equal to the 
     // requested height and width. 
     inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; 
    } 

    return inSampleSize; 
} 

public static Bitmap decodeSampledBitmapFromResource(String orgImagePath, 
     int reqWidth, int reqHeight) { 

    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(orgImagePath, options); 
    options.inSampleSize = calculateInSampleSize(options, reqWidth, 
      reqHeight); 
    options.inJustDecodeBounds = false; 
    return BitmapFactory.decodeFile(orgImagePath, options); 
} 

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> { 
    private final WeakReference<ImageView> imageViewReference; 
    private int data = 0; 

    public BitmapWorkerTask(ImageView imageView) { 
     // Use a WeakReference to ensure the ImageView can be garbage 
     // collected 
     imageViewReference = new WeakReference<ImageView>(imageView); 
    } 

    // Decode image in background. 
    @Override 
    protected Bitmap doInBackground(Integer... params) { 
     data = params[0]; 
     return decodeSampledBitmapFromResource(getResources(), data, 100, 
       100); 
    } 

    // Once complete, see if ImageView is still around and set bitmap. 
    @Override 
    protected void onPostExecute(Bitmap bitmap) { 
     if (imageViewReference != null && bitmap != null) { 
      final ImageView imageView = imageViewReference.get(); 
      if (imageView != null) { 
       imageView.setImageBitmap(bitmap); 
      } 
     } 
    } 
} 
} 

I 오류가 점점 오전 : 메소드의 GetResources은() 유형 BitmapLoader.BitmapWorkerTask에 대한 정의되지 않습니다. 나는 상대적으로 안드로이드에 익숙해서 잘못된 방법이나 무언가를 사용하고 있기 때문에 올바른 사용법을 가르쳐 주거나 적어도 올바른 방향으로 나를 가리킬 수 있기를 바랍니다. 미리 감사드립니다.

link to the code i copied

답변

3

당신은 활동 컨텍스트가 필요합니다. BitmapLoader의 생성자에 활동 컨텍스트를 전달합니다.

 public class BitmapLoader { 
    Context context; 
    public BitmapLoader(Context mContext) 
    { 
     context = mContext; 
    } 
    } 

사용 context.getResources()

확인 아래의 링크

http://developer.android.com/reference/android/view/ContextThemeWrapper.html#getResources()

+0

감사합니다. 굉장합니다! res 폴더 대신 리소스로 sdcard의 이미지를 전달하려고 할 때 도움이 될 것이라고 생각하십니까? – smmehl0311

+0

당신은 sdcard에서 이미지의 경로가 필요합니다. 당신이 많은 비슷한 게시물을 찾을 수 있도록 검색하십시오. 새로운 질문을하지 않으면. 나는 지역 사회가 당신을 도울 것이라고 확신합니다. – Raghunandan

0

안녕하세요 내가 같은 방법으로 그것을 해결 같은 문제가 있었다. 하지만 필자는 필요에 따라 FilePath를 대신 사용했습니다. 여기 내 해결책. 유일한 차이점은 파일의 쾅입니다

new BitmapWorkerTask(this, imageView, imageName).execute(); 

class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> { 
    private final WeakReference<ImageView> imageViewReference; 
    private String fName; 

    public BitmapWorkerTask(Context context, ImageView imageView, String res) { 
     // Use a WeakReference to ensure the ImageView can be garbage collected 
     imageViewReference = new WeakReference<ImageView>(imageView); 
     fName = new File(context.getFilesDir(), res).getAbsolutePath(); 
    } 

    // Decode image in background. 
    @Override 
    protected Bitmap doInBackground(String... args) { 

    return decodeSampledBitmapFromResource(fName, 100, 
      100); 

    } 

    // Once complete, see if ImageView is still around and set bitmap. 
    @Override 
    protected void onPostExecute(Bitmap bitmap) { 

     if (imageViewReference != null && bitmap != null) { 
      final ImageView imageView = imageViewReference.get(); 
      if (imageView != null) { 
       imageView.setImageBitmap(bitmap); 
      } 
     } 
    } 
} 

public static Bitmap decodeSampledBitmapFromResource(String fName) { 

    // First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    //BitmapFactory.decodeStream(is, padding, options); 
    BitmapFactory.decodeFile(fName, options); ...... The rest is the same 

에 당신 만이 "새 파일 (context.getFilesDir(), 고해상도) .getAbsolutePath();"

관련 문제