Android ListView Integrated Using Demo sample _ combined with database operations and ListItem Click on Long Press events handling

Source: Internet
Author: User

This demo sample illustrates:

1. Define the ListView entry style yourself, define how many columns the ListView displays, and flexibly bind to the fields in the database.

2. To achieve the addition and deletion of the DB, and after the operation of the ListView self-refresh.

3. In response to user action click events, the Demo sample shows the primary key ID and other content to be removed when clicked.

4. In response to user actions long press events, the demo sample shows long time to edit and delete data based on the primary key ID.

5. The presentation layer is separate from the data processing layer, and does not depend on the cursor (using cursor is not easy to perform and business separation), support interface programming.

6. Use database processing Framework ahibernate flexible Operation SQLite database, see: http://blog.csdn.net/lk_blog/article/details/7455992


Examples of this demo:


List the main code:

1.list.xml:

<?xml version= "1.0" encoding= "UTF-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:id=" @+id/child "android:layout_width=" fill_parent "android:layout_height=" Fill_parent "Androi D:background= "#E3D25E" android:orientation= "Horizontal" > <!--if you want to hide the ID increase this property: Android:visibility= "Gone", this is a bit similar In HTML hidden domain--<textview android:id= "@+id/idto" android:layout_width= "Wrap_content" Andro        id:layout_height= "Wrap_content" android:textcolor= "#ff0000"/> <textview android:id= "@+id/nameTo"        Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:paddingbottom= "5px" android:paddingleft= "50px" android:paddingtop= "5px" android:text= "No Data" android:textcolor= "# 0000FF "android:textsize=" 20sp "/> <textview android:id=" @+id/ageto "Android:layout_width=" W Rap_content "Android:layout_height= "Wrap_content" android:paddingbottom= "5px" android:paddingleft= "50px" android:paddingtop= "5px"  android:text= "No data" android:textcolor= "#00ff00" android:textsize= "20SP"/></linearlayout>

2.mainactivity.java:

Package Com.tgb.lk.listview;import Java.util.list;import Java.util.map;import Com.tgb.lk.demo.dao.StudentDao; Import Com.tgb.lk.demo.dao.impl.studentdaoimpl;import Com.tgb.lk.demo.model.student;import Com.tgb.lk.listview.R; Import Android.app.activity;import android.content.context;import android.os.bundle;import android.text.TextUtils; Import Android.view.contextmenu;import Android.view.menuitem;import Android.view.view;import Android.view.contextmenu.contextmenuinfo;import Android.view.view.onclicklistener;import Android.widget.adapterview;import Android.widget.button;import Android.widget.listview;import Android.widget.simpleadapter;import Android.widget.textview;import Android.widget.toast;import Android.widget.adapterview.adaptercontextmenuinfo;import android.widget.adapterview.onitemclicklistener;/** * Welcome to my blog for code Exchange: Http://blog.csdn.net/lk_blog * Database processing using the Ahibernate framework, see: http://blog.csdn.net/lk_blog/article/ details/7455992 * @author Likun */public class Mainactivity extends ActivitY {private static final int item_modify = 1;private static final int item_delete = 2;//defines the interface private Studentdao DAO = null; Private ListView LV = null, @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate ); Setcontentview (r.layout.main);//Add button Btnadd = (button) Findviewbyid (R.id.btnadd); Btnadd.setonclicklistener ( listener);//Display the first 3 data Button btnshow = (button) Findviewbyid (r.id.btnshow); Btnshow.setonclicklistener (listener);// Delete data Button btnclear = (button) Findviewbyid (r.id.btnclear); Btnclear.setonclicklistener (listener); LV = (ListView) Findviewbyid (r.id.lvstudent);//Set on the entry click Listener Lv.setonitemclicklistener (ItemListener);// Set Long press event Registerforcontextmenu (LV);//Show All Data ShowData (-1);} Displays the data, num is less than or equal to 0 o'clock displays all data, num is greater than 0 o'clock to display the top N. private void showData (int num) {dao = (dao = = null? New Studentdaoimpl (This): DAO);  list<map<string, string>> data = null;if (num <= 0) {//Show all students, call the DAO layer interface data = Dao.queryallstudent ();} else {//show top n students, call DAO layer interface data = Dao.quERYTOPN (num);} Simpleadapter adapter = Buildlistadapter (this, data); Lv.setadapter (adapter);} Build Adapter.public simpleadapter buildlistadapter (Context context,list<map<string, string>> data) { Simpleadapter adapter = new Simpleadapter (context, data, r.layout.list,new string[] {"_id", "name", "Age"}, new int[] { R.id.idto,r.id.nameto, R.id.ageto}); return adapter;} Initialize data Onclicklistener listener = new Onclicklistener () {@Overridepublic void OnClick (View v) {dao = (dao = = null? New S) Tudentdaoimpl (mainactivity.this): DAO); switch (V.getid ()) {case r.id.btnadd://join student Student student1 = new Student (); Student1.setname ("LK"); Student1.setage (+);d Ao.insert (STUDENT1); Student Student2 = new Student () student2.setname ("CLS"), Student2.setage (;d ao.insert (Student2); Student Student3 = new Student () student3.setname ("lb") student3.setage;d Ao.insert (STUDENT3); ShowData (-1); Break;case r.id.btnshow://Display the first 3 data showdata (3); break;case r.id.btnclear://Delete all data dao.deletedata ();//Show All data showdATA ( -1); break;default:break;}}};/ /item, click Processing Method. Onitemclicklistener ItemListener = new Onitemclicklistener () {@Overridepublic void Onitemclick (adapterview<?> Parent, view view, int Position,long ID) {//The view here is the LinearLayout object we defined in List.xml.// So the Findviewbyid method can be used to find its sub-objects defined in List.xml, such as the following: TextView Stuid = (TextView) View.findviewbyid (r.id.idto); TextView stuname = (TextView) View.findviewbyid (R.id.nameto); TextView stuage = (TextView) View.findviewbyid (R.id.ageto); Toastshow ("study number:" + stuid.gettext (). toString () + "; Name: "+ Stuname.gettext (). toString () +"; Age: "+ Stuage.gettext (). toString ());}};/ /wrapper Toast, on the one hand call simple, there is also a side to adjust the display time only to change this place can. public void Toastshow (String text) {Toast.maketext (mainactivity.this, text , +). Show ();} Long-on-time menu @overridepublic void Oncreatecontextmenu (ContextMenu menu, View v,contextmenuinfo menuinfo) { Menu.setheadertitle ("Please select operation"); Menu.add (0, item_modify, 0, "edit"), Menu.add (0, Item_delete, 1, "delete"); Response Edit and Delete event handling public boolean oncontextitemselected (MenuItem Item){Adaptercontextmenuinfo info = (adaptercontextmenuinfo) item.getmenuinfo ();// Info.targetview gets the LinearLayout object in the list.xml. String stuid = ((TextView) info.targetView.findViewById (r.id.idto)). GetText (). toString (); if (! Textutils.isempty (Stuid)) {int id = integer.parseint (stuid);d ao = (dao = = null? New Studentdaoimpl (This): DAO); switch (i Tem.getitemid ()) {case item_modify://edit data toastshow ("edit" + stuid);//This method is defined in Ahibernate. A lot of other examples of using demo see http:// Blog.csdn.net/lk_blog/article/details/7455992student student = Dao.get (ID); Student.setname ("Kun"); Student.setage ( ;d ao.update (student); This method is defined in Ahibernate. break;case item_delete://Delete data toastshow ("delete" + Stuid);d ao.delete (ID);//This method is defined in ahibernate. break ;d Efault:break;}} ShowData ( -1); return false;}}

3. Database processing layer: Studentdaoimpl.java:

Package Com.tgb.lk.demo.dao.impl;import Java.util.list;import Java.util.map;import Com.tgb.lk.ahibernate.dao.impl.basedaoimpl;import Com.tgb.lk.demo.dao.studentdao;import Com.tgb.lk.demo.model.student;import Com.tgb.lk.demo.util.dbhelper;import android.content.context;// This document deals with reference jar package ahibernate processing.//ahibernate Tutorial Demo sample address: http://blog.csdn.net/lk_blog/article/details/7455992// Ahibernate Source Exchange Address: Http://blog.csdn.net/lk_blog/article/details/7456125//AHibernate jar package Download and source code:/http Download.csdn.net/detail/lk_blog/4222048public class Studentdaoimpl extends basedaoimpl<student> implements Studentdao {public Studentdaoimpl (context context) {Super (New DBHelper (context));} Returns an object in a list,list that is a map with the lowercase form of a column in SQL. (In this case _id,name,age is key) public list<map<string, string>> queryallstudent () {String sql = "Select _id, Name,age From T_student "; return super.query2maplist (SQL, NULL);} Returns an object in a list,list that is a map with the lowercase form of a column in SQL. (In this case _id,name,age is key) public list<map<string, String>> QUERYTOPN (int num) {String sql = "Select _id, name,age from t_student limit?"; return super.query2maplist (SQL, new string[] {string.valueof (num)}); public void DeleteData () {String sql = ' delete from t_student '; super.execsql (sql, NULL);}}
This demo sample source: http://download.csdn.net/detail/lk_blog/4278055

Finally, I hope you will comment on the shortcomings of this article to criticize.







Android ListView Integrated Using Demo sample _ combined with database operations and ListItem Click on Long Press events handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.