-1

GridView に画像を描画するこのクラスがあります。

    public class ImageAdapter extends BaseAdapter
{
   Context MyContext;
   Vector<User> users;
   int level;


   public ImageAdapter(Context _MyContext, Vector<User> _users, int _level)
   {
      MyContext = _MyContext;
      users = _users;
      level = _level;
   }

   @Override
   public int getCount() 
   {
                     /* Set the number of element we want on the grid */
       if(users==null)
           return 0;
      return users.size();
   }

   @Override
   public View getView(int position, View convertView, ViewGroup parent) 
   {
      View MyView = convertView;            
                             /*we define the view that will display on the grid*/
         //Inflate the layout
         LayoutInflater li = getLayoutInflater();
         MyView = li.inflate(R.layout.grid_item, null);

         // Add The Text!!!
         TextView tv = (TextView)MyView.findViewById(R.id.grid_item_text);

         // Add The Image!!!           
         ImageView iv = (ImageView)MyView.findViewById(R.id.grid_item_image);
         iv.setBackgroundResource(R.drawable.button_restricted);
         iv.setImageResource(R.drawable.defaultperson02);
         byte[] bytes;
         if(position<users.size()){
             final User user =users.get(position);
            tv.setText(users.get(position).getDisplay_name());  
            bytes = user.getAvatar();
            if(bytes!=null && bytes.length>0 ){
                try{
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    iv.setImageBitmap(bitmap);
                }catch(Exception e){                        

                }
            }

         }

      return MyView;
   }

    @Override
    public Object getItem(int arg0) {
        return null;
    }

    @Override
    public long getItemId(int arg0) {
        return 0;
    }
}

通常、このクラスは完全に機能しますが、次の例外が発生することがあります。

01-18 12:39:26.160: ERROR/AndroidRuntime(30496): FATAL EXCEPTION: main
01-18 12:39:26.160: ERROR/AndroidRuntime(30496): java.lang.OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=15303KB, Allocated=10747KB, Bitmap Size=18391KB)
01-18 12:39:26.160: ERROR/AndroidRuntime(30496):     at android.graphics.BitmapFactory.nativeDecodeByteArray(Native Method)
01-18 12:39:26.160: ERROR/AndroidRuntime(30496):     at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:625)
01-18 12:39:26.160: ERROR/AndroidRuntime(30496):     at android.graphics.BitmapFactory.decodeByteArray(BitmapFactory.java:638)

ビットマップのリサイクルを試みましたが、まだエラーが表示されます。

なぜ私がこの問題を抱えているのか分かりますか?

4

1 に答える 1

0

convertview クラスを再利用する必要があります。上記のコードで行っていることは、getView が呼び出されるたびに新しいビューを作成することです。これは正しいやり方ではありません。代わりに、convertview が null かどうかを確認してください。null の場合は、ビューを膨張させます。それ以外の場合は、convertview を再利用します。詳細については、これを確認してください。

于 2012-01-18T11:56:25.573 に答える