I have an UI which contains a button and a list which contains some data. When the user clicks on the button before the list is loaded, it gives a NPE. I added a null check like this which prevents the crash.
//here cardData is the List which needs load.
if (cardData != null) {
for (CardDisplayData display : cardData) {
// do something
}
}
I was doing this at the end of onCreate
new FetchData().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR).get();
I removed the null check and replaced the executor. Now, the list data loads before opening the UI and there is no crash anymore. But this has slowed down the performance as the UI loads first and then implements the button listener.
My Async task,
private class FetchData extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
displayData(); // here is the data that needs to be displayed
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
Collections.sort(cardData);
} catch (IllegalStateException ise) {
LOG.warn("Illegal state exception, ignoring it {}", ise);
}
PrintStockAdapter adapter = new PrintStockAdapter(getApplicationContext(), cardData);
details.setAdapter(adapter); //details is a listView
adapter.notifyDataSetChanged();
}
}