I have an application that has a layout with ~150 editText’s and a mainActivity that has an onClickListener for each of these editTexts, and a button which loops through them all and clears them.
The application was running fine, and without making any significant changes I am now getting the following logCat error everytime i start up the application:
Out of memory on a 2903056-byte allocation.
Is there any obvious bad practices I am doing here that is causing the memory loss?
Some of my code below as illustration (this is repeated many times obviously)
box0101.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
txtHint.setText(hintPrefix + onOneClick);
return false;
}
});
box0301.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
txtHint.setText(hintPrefix + onOneClick);
return false;
}
});
box0401.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
txtHint.setText(hintPrefix + onOneClick);
return false;
}
});
box0501.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
txtHint.setText(hintPrefix + onOneClick);
return false;
}
});
box0601.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
txtHint.setText(hintPrefix + onOneClick);
return false;
}
});
and also some buttonclick listeners that set off some loops
btnClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearBoard();
}
});
public void clearBoard() {
final int ROW_COUNT = 14;
final int COL_COUNT = 9;
final String ROWS[] = {"01","02","03","04","05","06","07","08","09","10","11","12","13","14","15"};
final String COLS[] = {"01","02","03","04","05","06","07","08","09","10"};
for(int i=0; i<ROW_COUNT; i++) {
for(int j=0; j<COL_COUNT; j++) {
String a = ROWS[i];
String b = COLS[j];
int editTextId = getResources().getIdentifier("box" + a + b , "id", getPackageName());
EditText et=(EditText)findViewById(editTextId);
et.setText("");
}
}
}
As @alex.veprik mentioned: try to use one
OnClickListener, and assign it to all yourEditText-objects. If you create a newOnClickListenerfor everyEditText-object, although they all do the same, this will eat a lot of your memory.Example)
It might also be wise to put the creation of your
EditText-objects in a loop, and to store only the list of all boxes in a member variable. So instead of having 150 variables, you now only need one for the list, while at the same time keeping all the references. (this doesn’t affect your memory problem, but it’s good code style)As @zapl recommended, it might also be good to use a memory profiler.