2014-07-07 2 views
1

피드에서 사진을 가져 오려고하는데이 오류로 인해이 오류 메시지가 나타납니다.java.lang.OutOfMemoryError 그림

오류 :

java.lang.OutOfMemoryError 
at android.graphics.BitmapFactory.nativeDecodeStream(Native Method) 
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:623) 
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:696) 
at com.ultrait.cobat.FindPropertyActivity.DownloadImage(FindPropertyActivity.java:140) 
at com.ultrait.cobat._09_LatestDetailed$7.run(_09_LatestDetailed.java:262) 
at java.lang.Thread.run(Thread.java:841) 

내 코드 :

<!-- public class _06_Photos extends Activity implements ViewFactory { 

private static final int SWIPE_MIN_DISTANCE = 120; 
private static final int SWIPE_MAX_OFF_PATH = 250; 
private static final int SWIPE_THRESHOLD_VELOCITY = 200; 


//GUI Components 
TextView tv_counter; 
ImageSwitcher imageSwitcher; 

Button b_play; 
Button b_next; 
Button b_previous; 
Button b_more; 

FrameLayout topFrame, bottomFrame; 

//Images and Stuff 
String [] str_imageURLs; 
Bitmap [] bm_images; 
String propertyid; 
int picNum = 0; 
boolean play; 
boolean stop; 
Handler handler; 

Thread playThread; 


public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.xl_06_photos); 

    handler = new Handler(); 
    propertyid = ""; 
    playThread = new Thread(Play); 

    play = false; 
    stop = false; 
    playThread.start(); 


    str_imageURLs = new String[10]; 
    for(int i=0; i<10;++i) 
     str_imageURLs[i] = ""; 

    bm_images = new Bitmap[10]; 
    for(int i=0; i<10;++i) 
     bm_images[i] = BitmapFactory.decodeResource(getResources(), R.drawable.downloading); 

    InitView(); 

    Bundle extras = getIntent().getExtras(); 
    if (extras != null) { 
     str_imageURLs[0] = extras.getString("img1"); 
     str_imageURLs[1] = extras.getString("img2"); 
     str_imageURLs[2] = extras.getString("img3"); 
     str_imageURLs[3] = extras.getString("img4"); 
     str_imageURLs[4] = extras.getString("img5"); 
     str_imageURLs[5] = extras.getString("img6"); 
     str_imageURLs[6] = extras.getString("img7"); 
     str_imageURLs[7] = extras.getString("img8"); 
     str_imageURLs[8] = extras.getString("img9"); 
     str_imageURLs[9] = extras.getString("img10"); 
    } 

    for(int i=0; i<9; i++) 
     System.out.println(str_imageURLs[i]); 



    new Thread(new Runnable() { 
     public void run() { 
      for(int i=0; i<9; ++i) 
      { 
       try{ 
        bm_images[i] = FindPropertyActivity.DownloadImage(str_imageURLs[i]); 
       } 
       catch(Exception e){ 
        System.out.println("Image" + i + " not downloaded - " + e); 
       } 

       try{ 
        if(bm_images[i] == null){ 
         System.out.println("Bitmap " + i + " is null"); 
         bm_images[i] = BitmapFactory.decodeResource(getResources(), R.drawable.download_error); 
        } 

        if(picNum == i) 
         handler.post(SetPic); 
       } 
       catch(Exception e){ 
        System.out.println("PicNum null/visiablity" + i + " not setCorrectly - " + e); 
       } 
      } 
      System.gc(); 
     } 
    }).start(); 
} 

private void InitView(){ 

    handler.post(SetPic); 
    tv_counter = (TextView)findViewById(R.id.photo_tv_counter); 
    imageSwitcher = (ImageSwitcher)findViewById(R.id.photo_imageSwitcher); 
    imageSwitcher.setFactory(this); 

    topFrame = (FrameLayout)findViewById(R.id.photo_topFrame); 
    bottomFrame = (FrameLayout)findViewById(R.id.photo_bottomFrame); 

    final GestureDetector gestureDetector = new GestureDetector(new MyGestureDetector()); 
    imageSwitcher.setOnTouchListener(new View.OnTouchListener() { 

     public boolean onTouch(View v, MotionEvent event) { 
      gestureDetector.onTouchEvent(event); 
      return true; 
     } 
    }); 


    b_play = (Button)findViewById(R.id.photo_b_play); 
    if(play){ 
     b_play.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_pause)); 
     topFrame.setVisibility(View.INVISIBLE); 
     bottomFrame.setVisibility(View.INVISIBLE); 
    } 
    else{ 
     b_play.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_play)); 

    } 
    b_play.setOnTouchListener(new View.OnTouchListener() { 

     public boolean onTouch(View v, MotionEvent event) { 
      if (event.getAction() == MotionEvent.ACTION_DOWN) { 
       Drawable background = v.getBackground(); 
       background.setColorFilter(0xFF7A7A7A, PorterDuff.Mode.MULTIPLY); 
       v.setBackgroundDrawable(background); 
      } else if (event.getAction() == MotionEvent.ACTION_UP) { 
       Drawable background = v.getBackground(); 
       background.setColorFilter(null); 
       v.setBackgroundDrawable(background); 

       if(play){ 
        play = false; 
        b_play.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_play)); 
       } 

       else{ 
        play = true; 
        b_play.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_pause)); 
        topFrame.setVisibility(View.INVISIBLE); 
        bottomFrame.setVisibility(View.INVISIBLE); 
       } 
      } 
      return false; 
     } 
    }); 



    b_previous = (Button)findViewById(R.id.photo_b_previous); 
    b_previous.setOnTouchListener(new View.OnTouchListener() { 

     public boolean onTouch(View v, MotionEvent event) { 
      if (event.getAction() == MotionEvent.ACTION_DOWN) { 
       Drawable background = v.getBackground(); 
       background.setColorFilter(0xFF7A7A7A, PorterDuff.Mode.MULTIPLY); 
       v.setBackgroundDrawable(background); 
      } else if (event.getAction() == MotionEvent.ACTION_UP) { 
       Drawable background = v.getBackground(); 
       background.setColorFilter(null); 
       v.setBackgroundDrawable(background); 

       PreviousPic(); 
      } 
      return false; 
     } 
    }); 

    b_next = (Button)findViewById(R.id.photo_b_next); 
    b_next.setOnTouchListener(new View.OnTouchListener() { 

     public boolean onTouch(View v, MotionEvent event) { 
      if (event.getAction() == MotionEvent.ACTION_DOWN) { 
       Drawable background = v.getBackground(); 
       background.setColorFilter(0xFF7A7A7A, PorterDuff.Mode.MULTIPLY); 
       v.setBackgroundDrawable(background); 
      } else if (event.getAction() == MotionEvent.ACTION_UP) { 
       Drawable background = v.getBackground(); 
       background.setColorFilter(null); 
       v.setBackgroundDrawable(background); 

       NextPic(); 
      } 
      return false; 
     } 
    }); 


} 

public void onDestroy(){ 
    super.onDestroy(); 
    stop = true; 
} 

private final Runnable SetPic = new Runnable() { 
    public void run() { 
     //iv_activity.setVisibility(View.INVISIBLE); 
     Drawable d =new BitmapDrawable(bm_images[picNum]); 
     imageSwitcher.setImageDrawable(d); 
     System.out.println("Pic Set"); 

     tv_counter.setText("" + (picNum+1) + "/5"); 
    } 
}; 

private final Runnable Play = new Runnable() { 
    public void run() { 
     while(!stop){ 
      try{ 
       Thread.sleep(3000); 
       handler.post(new Runnable() { 
        public void run() { 
         if(play) 
          NextPic(); 
        } 
       }); 
      } 
      catch(Exception e){ 
       System.out.println("Play Error - " + e); 
      } 
     } 
    } 
}; 


protected void NextPic(){ 

    try{ 
     picNum++; 
     if(picNum > 9) 
      picNum = 0; 

     tv_counter.setText("" + (picNum+1) + "/10"); 

     imageSwitcher.setInAnimation(this, R.anim.slide_in_left); // added 
     imageSwitcher.setOutAnimation(this, R.anim.slide_out_left); // added 
     Drawable d =new BitmapDrawable(bm_images[picNum]); 
     imageSwitcher.setImageDrawable(d); 
     System.out.println("Next Pic"); 
    } 
    catch(Exception e){ 
     System.out.println("Next Fail " + e); 
     //imageSwitcher.setImageResource(R.drawable.download_error); 
     imageSwitcher.setImageDrawable(null); 
    } 
} 

protected void PreviousPic(){ 


     picNum--; 
     if(picNum < 0) 
      picNum = 9; 

     tv_counter.setText("" + (picNum+1) + "/10"); 
    try{  
     imageSwitcher.setInAnimation(this, R.anim.slide_in_right); // added 
     imageSwitcher.setOutAnimation(this, R.anim.slide_out_right); // added 
     Drawable d =new BitmapDrawable(bm_images[picNum]); 
     imageSwitcher.setImageDrawable(d); 
     System.out.println("Previous Pic"); 
    } 
    catch(Exception e){ 
     System.out.println("Previous Fail " + e); 
     //imageSwitcher.setImageResource(R.drawable.download_error); 
     imageSwitcher.setImageDrawable(null); 
    } 

} 
protected void ChangeBarVisibles(){ 
    if(topFrame.isShown()){ 
     topFrame.setVisibility(View.INVISIBLE); 
     bottomFrame.setVisibility(View.INVISIBLE); 
    } 
    else{ 
     topFrame.setVisibility(View.VISIBLE); 
     bottomFrame.setVisibility(View.VISIBLE); 
    } 
} 


public View makeView() 
{ 
    ImageView imageView = new ImageView(this); 
    imageView.setBackgroundColor(0xFF000000); 
    imageView.setScaleType(ImageView.ScaleType.FIT_CENTER); 
    imageView.setLayoutParams(new 
      ImageSwitcher.LayoutParams(
        LayoutParams.FILL_PARENT, 
        LayoutParams.FILL_PARENT)); 
    return imageView; 
} 

class MyGestureDetector extends SimpleOnGestureListener { 
    @Override 
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 
     try { 

      if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) 
       return false; 
      // right to left swipe 
      if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { 
       //Toast.makeText(SelectFilterActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show(); 
       NextPic(); 
       //return true; 
      } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { 
       //Toast.makeText(SelectFilterActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show(); 
      PreviousPic(); 
      //return true; 
      }  
     } catch (Exception e) { 
      // nothing 
     } 
     return true; 
    } 

    public boolean onSingleTapUp(MotionEvent e){ 
     if(e.getAction() == MotionEvent.ACTION_UP){ 
      ChangeBarVisibles(); 
     } 
     return true; 
    } 
} 

@Override 
public void onConfigurationChanged(Configuration newConfig) { 
    super.onConfigurationChanged(newConfig); 
    setContentView(R.layout.xl_06_photos); 

    InitView(); 
} 

} --> 

FindPropertyActivity :

// 인터넷에서

public static Bitmap DownloadImage(String URL){ 

    Bitmap bmImg = null; 
    URL myFileUrl =null; 

    try { 
     myFileUrl= new URL(URL); 
    } catch (Exception e) { 
     //e.printStackTrace(); 
     System.out.println(e); 
    } 
    try { 
     HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection(); 
     conn.setDoInput(true); 
     conn.connect(); 
     InputStream is = conn.getInputStream(); 
     bmImg = BitmapFactory.decodeStream(is); 
    } 
    catch(Exception e){ 
     System.out.println(e); 
    } 
    return bmImg; 
} 

public static Bitmap DownloadImage2(String URL){ 

    Bitmap bmImg = null; 
    URL myFileUrl =null; 

    try { 
     myFileUrl= new URL(URL); 
    } catch (Exception e) { 
     //e.printStackTrace(); 
     System.out.println(e); 
    } 
    try { 
     HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection(); 
     conn.setDoInput(true); 
     conn.connect(); 
     InputStream is = conn.getInputStream(); 
     BitmapFactory.Options options=new BitmapFactory.Options(); 
     options.inSampleSize = 7; 
     bmImg=BitmapFactory.decodeStream(is,null,options); 
     //bmImg = BitmapFactory.decodeStream(is); 

    } 
    catch(Exception e){ 
     System.out.println(e); 
    } 
    return bmImg; 
} 
+0

휴대 전화에서 렌더링 할 수있는 OpenSL 바운드가 있습니다. 확인해보십시오. 'final int [] maxSize = 새로운 int [1]; GLES10.glGetIntegerv (GL10.GL_MAX_TEXTURE_SIZE, maxSize, 0); ' 필요하다면 이미지를 확대하십시오 – busylee

+0

[Android Universal Image Loader] (https://github.com/nostra13/Android-Universal-Image-Loader)를 사용해보세요. , 이미지로드 및 캐싱 및 OOM 오류 방지에 도움이됩니다. 희망이 도움이 될 수 있습니다. –

+0

글쎄, 시도해 볼 수는 있지만, 4.3에서 충돌 만하는 것은 전혀 문제가되지 않는다. –

답변

0

이미지를 이미지를 다운로드 할 수있는 공공 정적 메서드 다시 디코디 무거운 사람이어야합니다. 일반적으로이 오류는 비트 맵이 부주의하게 크기를 무시하면서 메모리로 디코딩 될 때 발생합니다. 디코딩 중에 비트 맵 옵션 (디코딩 매개 변수 높이, 너비 등)을 지정해야합니다.

친절히 해결책을 찾으십시오. http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

+0

4.2, 4.0 등에서 작동한다. 4.3 및 4.4에서만 충돌합니다. 어떤 아이디어? –

+0

OS 문제는 아닌 것 같습니다. 디스크에서 이미지를 다운로드하고 디코딩하는 FindPropertyActivity 클래스를 게시하십시오. – humblerookie

+0

humblerookie, 빠른 응답을 주셔서 감사합니다. 지금하겠습니다. –

0

저는 개인적으로 Jake Wharton의 Picasa 라이브러리를 사용합니다. http://square.github.io/picasso/

당신이 필요로하는 모든 코드는 다음과 같습니다 :

Picasso.with(context).load("http://yourimage.jpg").into(yourImageView); 
그것의 좋은 방법은 여기

라이브러리를 다운로드 할 수있는 링크입니다 등등 다운로드 한 줄에 이미지를로드 및 캐싱, 변환을 관리 할 수

당신은 그것을 시도해야하고 나는 그것이 당신을 돕기를 바란다 :

1

비트 맵은 실제로 많은 RAM을 사용하며 OOM은 그것들과 꽤 공통적이다. 위의 제안 된 모든 솔루션과 함께 AndroidManifest.xml의 태그 안에 android : largeHeap = "true"를 추가해야합니다. 이 태그를 사용하여 Android는 애플리케이션에 약간의 RAM을 제공하고 가장 일반적인 문제 중 일부를 수정합니다. 이것은 해결책이며 최선의 해결책이 아니라 가능한 경우 구현을 수정하는 것이 더 나은 옵션입니다.

+0

답장을 보내 주셔서 감사합니다. 지금 해보겠습니다. 유일한 문제는 나에게 가장 낮은 버전 4.0.3에서 작동하는 등등, 4.3 이상에서만 작동합니다. –

+0

비트 맵과 비슷한 경험이 있었지만 이것이 저에게 효과가있는 유일한 방법이었습니다. 4.2.2가있는 장치에서는 약 30MB 만 사용했지만 4.4.4에서는 S4를 사용하여 120MB에 가깝게 사용했고 5 번에 5 번에 110을 사용했습니다. 이,하지만 지금은 나를 위해 작동합니다. –

+0

그것은 나를 위해 작동하지 않았다 : ( –

관련 문제