0

I've been following this tutorial for creating a database and have one question. It says "To access your database, instantiate your subclass of SQLiteOpenHelper: FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getContext());". But how can I instantiate my FeedReaderDbHelper class in another class (in a service in my case) without instantiating the whole FeedReaderContract class, because it says I should avoid instantiating the former class? In my service I am doing this:

FeedReaderContract.FeedReaderDbHelper mDbHelper = new FeedReaderContract().new FeedReaderDbHelper(mContext);

But the tutorial says it's forbidden.

Salivan
  • 1,876
  • 7
  • 26
  • 45

1 Answers1

3

If your inner class is associated to an instance of your outer class, you wouldn't be able to do that. IOW, if your inner class is not a static inner class, then it really doesn't make sense to create your inner class alone, right?

On the other hand, you can change your inner class to a static inner class. But you have to be careful if this is what you need since you are basically saying that the static inner class is not dependent on any one instance of the outer class.

Check this out: https://stackoverflow.com/a/70358/2231632

Community
  • 1
  • 1
Praba
  • 1,373
  • 10
  • 30
  • Oh, now it's clear for me. Thanks! But then how should I perform my database operations in a service class? How to communicate with the dbhelper class from another class? – Salivan May 01 '14 at 16:51
  • 1
    That is more of a design aspect. You don't decide the communication because you have written the dbhelper a particular way. Normally you'll have an instance of your service and there will be an instance of dbhelper per service. Look at the DAO pattern. I don't know what the `FeedReaderContract` object is all about and why you have chosen to include the `DbHelper` inside that contract. May be it'd be a better idea to think of the roles for each object and how they communicate and then design your code accordingly. – Praba May 01 '14 at 17:01
  • Well, I just based my code on google's tutorial but know I see that I need to implement it differently. – Salivan May 01 '14 at 17:05
  • code snippets are great to get started. but the moment you have your own objects, we can copy the way they _designed_ it. Good luck. And if you find your question answered, please mark it so. Or mark yours a duplicate of the other one. – Praba May 01 '14 at 17:13