tags:

views:

33

answers:

1

I've got a view which has an onClickListener, when the user clicks at a certain position I'd like to query the database and then pull data from it. Problem is I can't seem to do this in a view class because it's not an Activity.

I've tried implementing an OnTouchListener over the Layout in the Activity but it seems the view's layout overrides any attempt to get a touch registering from there.

So, I've tried a few approaches and they've failed. I'm wondering do any of you guys have any ideas? How would I implement it so that when the user touches the screen, I can retrieve the X Y values and then query the database?

+1  A: 

Use getContext() method of view. You then can obtain a database instance from the context. Somewhat like this:

class TestView extends View{

    public TestView(Context context) {
        super(context);
        SQLiteDatabase db = getContext().openOrCreateDatabase(...);
    }

}
Konstantin Burov
I'm getting `tweets cannot be resolved or is not a field` for the following.. `SQLiteDatabase db = getContext().tweets.getWritableDatabase();` why? I have it declared as a class variable.
Ulkmun
This is because getContext() returns you Context reference, not reference of your type where you declared the field. You may try to cast returned reference to your type, i.e. SQLiteDatabase db = ((YourType)getContext()).tweets.getWritableDatabase();
Konstantin Burov
Sorry, but what do you mean by "your type"?
Ulkmun
You're trying to access member variable of your own class which extends Context or Activity I guess. Your type is your class.
Konstantin Burov