Vandervidi
Vandervidi

Reputation: 692

What is the right way in using SQLite when changing activities in android?

I have two activities. Activity 1 - connects to the database and gets some data. Activity 2 - Connects to the database and pushes new data.

There is a button that opens activity 2 from activity 1.

When i open the database connection in activity 1, should i close it before opening activity 2 and then reopen the connection in activity 2?

OR , Is there a way to open the database connection in activity 1 and then just pass the connection to other activities?

Upvotes: 1

Views: 53

Answers (1)

Kirill Shalnov
Kirill Shalnov

Reputation: 2216

I suggest these three solutions

  • You can close db every onStop() invocation and open when onStart() called in your activities, but it is not a good solution
  • Wrap your database in some singleton, for example call it DataSource or DataAccessObject. Its look like a global variable - one point to accessing application's data, I am especially recommend this way
  • May be you don't need connection to db in the second activity. Start second activity by yourIntent.startActivityForResult(), then you should to return new data from second to first by intent and add it to db in onActivityResult() method

P.S. sorry for my bad English

Upvotes: 2

Related Questions