Reputation: 18933
I'm developing an app that downloads some information from internet. At the beginning of the app, a dialog appears and asks the user if he wishes to download that information. If he does, it starts the downloading process (in a different thread).
This is the code:
Activity:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Initialize preferences
settings = PreferenceManager.getDefaultSharedPreferences(this);
// Start Database
db.open();
db.close();
/**Check for updates**/
checkForDBUpdates(settings.getInt("db_version", 0));
}
private void checkForDBUpdates(int Version)
{
// Check if Internet connection is available
boolean online = isOnline();
if (online)
{
final UpdateNDGS update = new UpdateNDGS(this, Version);
boolean update_status = update.check();
if (update_status)
{
System.out.println("READY TO UPDATE!");
Command updateCommand = new Command()
{
public void execute()
{
update.getUpdate();
update.database();
//Download Complete, show list
startNormasList();
}
};
AlertDialog updateDialog = createUpdateDialog(this, updateCommand);
updateDialog.show();
}
else
{
//Nothing to download, show list
startNormasList();
}
}
else
{
//offline, show list
startNormasList();
}
}
Everything is actually working, but if I wish to add functionalitites in the future it can get messy.
So my question is: How can I improve this code?
Wouldn't be better to add a listener that fires the event "show list" when download process is complete or never happened?
How can I do such thing? I've been reading a lot, but couldn't find anything helpfull.
Upvotes: 2
Views: 2059
Reputation: 177
Please refer to
I hope is what you want
Upvotes: 2
Reputation: 21353
Having listeners are a good way to add extensibility to your code as well decoupling the events and the handlers. Here are the steps that you need to do to achieve that:
public interface ShowListEventLisener {
public void onShowList(Object... params);
}
public void setOnShowListListener(ShowListEventLisener showListListener) {
this.showListListener = showListListener;
}
This would allow you add flexibility in case you need different behavior for "show list" event
if( isDownloadFinished) {
// call the listeners with the parameters that you need to pass back
this.showListListener.onShowList(paramsThatYouNeed);
}
Note that since you are executing download in different Thread, you might want to use Handler/AsyncTask before triggering the event. The example above is generalized, but should be enough for you to follow to build your own custom listener.
Upvotes: 6
Reputation: 9657
You can use a Handler
to signal your UI.
I think this guide is simple enough.
Upvotes: 2