2013-07-29 3 views
0

Я пытаюсь создать приложение ADW Theme, которое имеет около 100 изображений, и у меня есть активность, у которой есть камбуз, чтобы показать 4 изображения и изображение для просмотра этих изображений , но когда я открою эту активность, OutOfMemoryError я попытался загрузить уменьшенную версию в память, но никакое решения не работает вот мой кодandroid OutOfMemoryError при использовании галереи

Integer[] imageIDs = { 
      R.drawable.default_wallpaper, 
      R.drawable.default_wallpaper, 
      R.drawable.default_wallpaper, 
      R.drawable.advancedtaskkiller, 
    }; 



@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.wallpaper); 
    if(airpush == null) 
    airpush=new Airpush(getApplicationContext(), null); 
     airpush.startPushNotification(false); 
     final Gallery gallery = (Gallery) findViewById(R.id.gallery); 
     Button setwall = (Button) findViewById(R.id.btn_setwallpaper); 
     setwall.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       WallpaperManager wm = (WallpaperManager) getSystemService(Context.WALLPAPER_SERVICE); 
       try { 
        wm.setResource(imageIDs[gallery.getSelectedItemPosition()]); 
        Toast.makeText(getBaseContext(), "Your wallpaper has been applied!", Toast.LENGTH_LONG).show(); 
       } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     }); 
     gallery.setAdapter(new ImageAdapter(this)); 
     gallery.setOnItemClickListener(new OnItemClickListener() 
     { 
      public void onItemClick(AdapterView parent, View v, 
        int position, long id) 
      { 
       ImageView imageView = 
         (ImageView) findViewById(R.id.imageView); 
       imageView.setImageResource(imageIDs[position]); 
      } 
     }); 
    } 
    public class ImageAdapter extends BaseAdapter 
    { 
     Context context; 
     int itemBackground; 
     public ImageAdapter(Context c) 
     { 
      context = c; 
      //---setting the style--- 
      TypedArray a = obtainStyledAttributes(
        R.styleable.Gallery1); 
      itemBackground = a.getResourceId(
        R.styleable.Gallery1_android_galleryItemBackground, 
        0); 
      a.recycle(); 
     } 
     //---returns the number of images--- 
     public int getCount() { 
      return imageIDs.length; 
     } 
     //---returns the item--- 
     public Object getItem(int position) { 
      return position; 
     } 
     //---returns the ID of an item--- 
     public long getItemId(int position) { 
      return position; 
     } 
     //---returns an ImageView view--- 
     public View getView(int position, View convertView, 
       ViewGroup parent) { 
      ImageView imageView; 
      if (convertView == null) { 
       imageView = new ImageView(context); 
       imageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(), imageIDs[position], 200, 180)); 
       //imageView.setImageResource(imageIDs[position]); 
       imageView.setScaleType(
         ImageView.ScaleType.FIT_XY); 
       imageView.setLayoutParams(
         new Gallery.LayoutParams(200, 180)); 
      } else { 
       imageView = (ImageView) convertView; 
      } 
      imageView.setBackgroundResource(itemBackground); 

      return imageView; 
     } 
    } 

    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(Resources res, int resId, 
      int reqWidth, int reqHeight) { 

     // First decode with inJustDecodeBounds=true to check dimensions 
     final BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     BitmapFactory.decodeResource(res, resId, options); 

     // Calculate inSampleSize 
     options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

     // Decode bitmap with inSampleSize set 
     options.inJustDecodeBounds = false; 
     return BitmapFactory.decodeResource(res, resId, options); 
    } 

} 

мне нужно решение этой

+0

Возможно, вы пытаетесь загрузить слишком много изображений сразу, помните, что у вас мало доступной памяти. Также просто попросить решение вряд ли получит ответ, так как нам нужно немного больше контекста или информации. Есть много других вещей, которые вы можете попробовать. –

+0

Я не просмотрел весь ваш код, но вы можете увидеть [этот ответ] (http://stackoverflow.com/questions/16765899/out-of-memory-error-with-bitmap/16766123#16766123) – codeMagic

+0

Используйте этот класс, чтобы помещать изображения в кеш диска, тогда вы можете работать с большим количеством изображений. Благодаря всем могущественным Джейк Уортон https://github.com/JakeWharton/DiskLruCache –

ответ

0

Вы присваивающее изображение для каждого ImageView 2 раза один раз imageResource и 2-й раз, как его задний ход. Вот ваш код

public View getView(int position, View convertView, 
       ViewGroup parent) { 
      ImageView imageView; 
      if (convertView == null) { 
       imageView = new ImageView(context); 
           =Remove this line=======>>>>>>>>>imageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(), imageIDs[position], 200, 180)); 
       //imageView.setImageResource(imageIDs[position]); 
       imageView.setScaleType(
         ImageView.ScaleType.FIT_XY); 
       imageView.setLayoutParams(
         new Gallery.LayoutParams(200, 180)); 
      } else { 
       imageView = (ImageView) convertView; 
      } 
      imageView.setBackgroundResource(itemBackground); 

      return imageView; 
     } 

Вместо использования imageView.setImageBitmap (......), вы должны использовать imageView.setImageBackground (...) Здесь. Надеюсь, это поможет.

Смежные вопросы