Search code examples
androidsqliteandroid-custom-view

How to connect database from custom view [Android]


I have this database connector class with a constructor as follows

public class DBConnectionTableTVShow {

     public DBConnectionTableTVShow(Context ctx){
       this.context = ctx;
       dbh = new DBHelper(context);
     }
}

I can create object from an Activity like following

public class Select_episode extends Activity {

    DBConnectionTableTVShow dbcon = new DBConnectionTableTVShow(this);
}

Now I want to create object, like i did in above in the custom view adapter class

public class CustomListViewAdapter extends BaseAdapter
{ 

}

How to do this?

I tried

DBConnectionTableTVShow dbcon = new DBConnectionTableTVShow(this);

this in CustomListViewAdapter class and it doesn't work

Complete code of Select_episode : http://pastebin.com/R1mSRrqj

Complete code of CustomListViewAdapter : http://pastebin.com/U8Zqw924


Solution

  • If CustomListViewAdapter is an inner class of Select_episode then you can use

    DBConnectionTableTVShow dbcon = new DBConnectionTableTVShow(Select_episode.this);  
    

    or you can create a constructor with a Context param and instantiate your database helper using the pass in context (when you pass this it is equivalent to passing a Context so instead of Activity you should make your param Context since you only need context)

    LayoutInflater inflater;
    List<ListViewItem> items;
    DBConnectionTableTVShow dbcon;
    
    public CustomListViewAdapter(Context context, List<ListViewItem> items) {  
        super();
    
        this.items = items;
        this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.dbcon = new DBConnectionTableTVShow(context);
    }