Question

I'm getting a weird problem when refreshing my ListView, it works fine until the device is rotated and then when refreshing it again it goes completely blank. This can only be fixed by rotating the device again(as it is also refreshed in onCreate()) but then whenever its refreshed again it goes blank. Problem persists until app is restarted.

EDIT:

Some code:

private ListView contactlist = null;
private static MatrixCursor matrixcursor = null;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    contactlist = (ListView) findViewById(R.id.contactlist);
    if (savedInstanceState == null) {
        matrixcursor = new MatrixCursor(new String[] {"_id","name","one","two","three","four"});
    } else {
        contactlist.setAdapter(new listCursorAdapter(this,matrixcursor));
    }
}

this works fine but whenever:

contactlist.setAdapter(new listCursorAdapter(this,matrixcursor));

is called after onCreate() and after the device has been rotated the ListView goes blank.

Was it helpful?

Solution 2

Well I managed to fix it by making contactlist static:

 private static ListView contactlist = null;

I have no idea why this worked(just did a trial/error for a couple of hours) so if anyone could explain it that would be great.

OTHER TIPS

I think your MatrixCursor is actually null. When you rotate the phone as you know the activity is destroyed. So the savedinstanceState bundle might not be null but the MatixCursor then does not get reinitialized. Yes it's static but I have a feeling if it for some chance it's not loaded in the same classloader ... well that static is not going to be too reliable.

There is a method which is most awkwardly named:

onRetainNonConfigurationInstance()

Which I think will help you solve this case. So if you return your MatrixCursor instance there, you can in a later call to onCreate() use getLastNonConfigurationInstance() to read the data back out. It's not guaranteed to be called, so you will still need to handle the case where you have no stored state. Hopefully this helps.

private ListView contactlist = null;
private MatrixCursor matrixcursor = null;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    contactlist = (ListView) findViewById(R.id.contactlist);
    matrixcursor = (MatrixCursor)getLastNonConfigurationInstance();
    if (matrixcursor == null) {
        matrixcursor = new MatrixCursor(new String[] {"_id","name","one","two","three","four"});
    } else {
        contactlist.setAdapter(new listCursorAdapter(this,matrixcursor));
    }
}

public MatrixCursor onRetainNonConfigurationInstance() {
return matrixcuror;
}

public MatrixCuror getLastNonConfigurationInstance() {
return (MatrixCursor) super.getLastNonConfigurationInstance();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top