Currently I have a custom view:
public class MyView extends View {
public MyView(Context c, AttributeSet attrs) {
super(context, attrs);
}
....
....
}
Now, I want to access an object that is not Android related, say a database connection, how do i do that? My current solution is to do the following
public class MyView extends View {
DBConnection connection;
public MyView(Context c, AttributeSet attrs) {
super(context, attrs);
}
....
....
public void setDBConnection(DBConnection c)
this.connection = c;
}
public void onDraw(Canvas canvas) {
this.connection.ensureUser();
...
....
}
My question is that is there a better way to do this? Currently I need to set (via setter) to ensure that the object that is going to be used in the MyView
class is set, above code snippet works but I don't know if this is the elegant / popular approach?
I am thinking to pass the object via the constructor, but I can't do that, because Android only calls the MyView(Context c, AttributeSets attrs)
constructor, it won't call the version if I have MyView(Context c, AttributeSets attrs, DBConnection db)
one.
please help
When I come across situations like this, I tend to take the approach of injecting the displayable data after the view is created. So, if your view needed a string of text to display, you inject that string or the object the string is pulled from during your activities creation by looking up the View
using findViewById
and then calling the appropriate setter.
As to "is there a better way to do this", I would be nervous about passing a dbconnection
into a view class. It doesn't pass the "smell" test and seems like you are leaking your logic into your view. It would make more sense to me to say, give your view a Cursor
or some object you've filled in inside your Activity
. This prevents building custom views that are tightly coupled to a very specific use/scenario.
On the other hand, you'll have to decide how reusable you want the view to be. It might be that quick and dirty is the appropriate tact for this particular project.