I have a fragment that have a grid view.I'm putting 70 images in grid view.but when i run the app it get out of memory.how o solve it?should i convert all images to bitmap? this is my fragment class:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_games, container, false);
mDrawerList = (GridView) rootView.findViewById(R.id.list_slidermenu);
icons=new int[50];
for(int i=1 ;i<icons.length ;i++)
{
icon_id="@drawable/data_" + i;
icons[i]=getResources().getIdentifier(icon_id, null, MainActivity.PACKAGE_NAME);
Log.e("log",""+icons[i]);
}
navDrawerItems = new ArrayList<NavDrawerItem>();
for(int i=0 ;i<icons.length ;i++)
{
navDrawerItems.add(new NavDrawerItem(icons[i]));
}
adapter = new NavDrawerListAdapter(getActivity(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
return rootView;
}
and this is my adapter class:
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.itemlist, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
// displaying count
// check whether it set visible or not
return convertView;
}
You have to consider about several facts here .
If 70 images gave you a OOM exception, that means your images are must larger in size. But most of the time, you do not need the image as it is. Your image is 1024 * 1024 pixels, but you show it within 100 * 100 scale image view. In such cases you have to find the required size and scale down the image where it doesnt waste heap and also image doesnt get pixalated. read here
You have to use some kind of loading technique such as progressing loading instead of loading all 70 at once into the grid. Then images will be load when only user scroll the grid. It will not waste the memory.
You have de-allocate all the images which are not currently shown on the grid for a given particular moment.
You have to set the large heap for the app though it is not recommended but have to use in these kind of apps.