opening database connection custom adapter
I've a question with regard to android adapters.
I have a class, extending BaseAdapter. Which basically is my adapter. I am opening a database connection in this adapter and writing to a database when the user clicks on a button.
Is this a bad practice to open database connection in an adapter class? if so how do I overcome this?
I am not using the database to query, I'm only using it to insert a value when the user clicks on a button.
Here's a code snippet. I've cut out most of the code for brevity
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String genre = "";
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.featured_tab_sublayout, null);
}
ImageView imgFavourite = (ImageView) convertView.findViewById(R.id.imgFavourite);
imgFavourite.setOnClickListener(favPicture);
开发者_高级运维 imgFavourite.setTag(position);
return convertView;
}
OnClickListener favPicture = new OnClickListener() {
@Override
public void onClick(View v) {
int i = (Integer) v.getTag();
Radio rad = radios.get(i);
if(db.Exists(rad.getmStreamLink())){
showConfirmation(i,rad);
}else{
String genre = "";
if(rad.getGenre().size()>0){
for(String g: rad.getGenre()) {
genre += g + ",";
}
}
db.insertOrder(rad.getmName(), rad.getmDesc(), rad.getmLogo(),
genre, rad.getmCountry(), rad.getmCity(), rad
.getmStreamLink(), rad.getmTwitter(), rad
.getmFacebook(), rad.getmWebsite(), rad
.getmRadionomyID(), rad.getmAudienceRank());
ErrorDialog.show(context, resource.getString(R.string.alert_dialog_fav_added));
/*String name, String desc, String logo,
String genre, String country, String city, String stream_link,
String twitter, String facebook, String website, String radionomy,
String audience_rank*/
}
}
};
Probably you have good reason to use imgFavourite.setOnClickListener(favPicture);
but this is not the usual way to listen for clicks in adapter.
Usual way is in your activity to call lv.setOnItemClickListener(new OnItemClickListener() {...});
where lv
is your list view. Replace "..." with body of the onItemClick() which will contain essentially the same as your onClick(View v)
. You will get position as a parameter so you will not need to use setTag()
/getTag()
.
That you you move your DB functionality out of the adapter which is the correct way to do it in most cases.
But isn't the idea of adapters to let them manage the database ?, I mean you extend newVIew and bindView, and in these methods you got cursor pointing to some record in db, and you are just updating the list in some custom way . . .
so my question is isn't managing the databese for insertion (in Adapter) bad practise ?
精彩评论