Question

Understandable this question is a little subjective, but I believe there is a concrete answer.

I have a really small activity that does nothing more than display some data to the user in a ListActivity. The data I use comes from the app's SQLite database and I find myself doing this

public class MainActivity extends ListActivity{
     private DatabaseAdapter dbHelper;
     @Override
     public void onCreate(Bundle b){ 
          dbHelper = new DatabaseAdapter(this);
          super.onCreate(b); 
     }

     @Override
     public void onResume(){
            dbHelper.open();
            fill_data();//a small method that uses dbHelper to setListAdapter
            super.onResume();
       }

     @Override
     public void onPause(){
          dbHelper.close();
          super.onPause();
     }

     private void fill_data(){/*makes use of dbHelper */ }

Is this just code largely unnecessary? I'd like to handle the lifecycles so I can use the least amount of resources when MainActivity is not on top, but at the same time, this whole activity could be done in onCreate().

Was it helpful?

Solution

You could probably get away with not overriding the onPause method if you just open and close the dbHelper whenever you use it. It's not all that intensive to open the helper (I'm assuming SQLiteOpenHelper), so you might consider it premature optimization.

At any rate, you'll almost always need to override onCreate, often override onResume, and sometimes override onPause. What's important is when the framework calls the various callbacks and what you have to do in them.

If you need to do something when your Activity hits the foreground or if you want to do something in your Activity's Looper (say, location updates), you'll have to override onResume. If you need to clean up after yourself, you'll have to implement onPause.

I generally don't implement onDestroy because it is not guaranteed to be called.

OTHER TIPS

It actually probably better to just open and close when you need the database. Though it doesn't affects your case, some phones (Samsung Galaxy S) can have very slow databases and having multiple connections open (e.g. in a activity and service) really slows things down... (i saw 1s write times!!)

Opening and closing a database does take time and you should do it in a separate thread. More details in this talk and PDF: http://www.google.com/events/io/2010/sessions/writing-zippy-android-apps.html

So you need to write even more code. :P

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top