Android ListView Add Data Dynamically (Sqliteopenhelper class add data)

Source: Internet
Author: User

First, Sqliteopenhelper class:

This time we use SQLite to dynamically add data, next we create a Openhelper.java, in the previous SQLite blog we have described in detail the creation and use of SQLite, we will be in OnCreate Create a table in the method and insert related values to complete the operation of SQLite through Db.execsql ().

①openhelper2.java file:

 Public classOpenHelper2extendsSqliteopenhelper {Private Static FinalString db_name = "mydata.db";//Database name    Private Static Final intVersion = 1;//Database Version     PublicOpenHelper2 (Context context) {Super(Context, Db_name,NULL, version); //TODO auto-generated Constructor stub} @Override Public voidonCreate (Sqlitedatabase db) {//TODO auto-generated Method StubLOG.I ("Hi", "no database, CREATE DATABASE"); String Sql_message= "CREATE table messaget (ID int primary key,username varchar (), lastmessage varchar (), datetime varchar (50))";        Db.execsql (Sql_message); LOG.I ("Hi", "CREATE TABLE"); String Inse= "INSERT into messaget values (1, ' TT ', ' Go traveling together ', ' October 1 ')"; String Inse2= "INSERT into Messaget values (2, ' TT ', ' Go traveling together ', ' October 1 ')"; String INSE3= "INSERT into Messaget values (3, ' TT ', ' Go traveling together ', ' October 1 ')";            Db.execsql (Inse);            Db.execsql (INSE2);            Db.execsql (INSE3); LOG.I ("Hi", "Add data to Table"); } @Override Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) {        //TODO auto-generated Method Stub            }}

1, by inheriting the sqliteopenhelper to achieve the operation of SQLite.

2. Create data name and database version statically.

We need to make the appropriate changes in the Mainactvity.java file.

②mainactvity.java file:

protected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);      Setcontentview (r.layout.weichatlayout); //This 3 line of code is used to create the table structure and initialize the dataOpenHelper2 helper =NewOpenHelper2 (mainactivity. This); Sqlitedatabase DB=helper.getwritabledatabase ();        Db.close (); LV=(ListView) Findviewbyid (R.ID.LISTVIEW1); SA=NewSimpleadapter ( This, MessageList2,//Data is a data mix coupled to the interfaceR.layout.listviewitems,NewString[] {"UserName", "Lastmessage", "datetime", "Tou"},//from Never come                New int[] {r.id.tv_username,r.id.tv_lastmessage,r.id.tv_datetime,r.id.img}//to get there.                );        Lv.setadapter (SA); Lv.setonitemclicklistener (NewOnitemclicklistener () {@Override Public voidOnitemclick (adapterview<?>Parent, view view,intPositionLongID) {//map<string,object> item = messagelist2.get (position); //item.put ("Tou", "0");sa.notifydatasetchanged ();                }                    }); OpenHelper2 Helpert=NewOpenHelper2 (mainactivity. This); Sqlitedatabase DB=helpert.getreadabledatabase (); Cursor C= Db.query ("Messaget",NULL,NULL,NULL,NULL,NULL,NULL);if(c! =NULL){             while(C.movetonext ()) {LOG.I ("DD", "Assigned value 1"); Messages M=Newmessages (); M.setit (Integer.parseint (c.getstring (C.getcolumnindex ("id")))); M.setdatetime (c.getstring (C.getcolumnindex ("DateTime"))); M.setlastmessage (c.getstring (C.getcolumnindex ("Lastmessage"))); M.setusername (c.getstring (C.getcolumnindex ("UserName")));           Messagelist3.add (m);    }} db.close ();  for(intJ=1;j<messagelist3.size (); j + +) {log.i ("DD", "Assigned value 2"); Messages M=Messagelist3.get (j); Map<String,Object> item =NewHashmap<string,object>(); //one row of records, containing multiple controlsItem.put ("Tou", "" "+j); Item.put ("UserName", m.getusername () +j); Item.put ("Lastmessage", M.getlastmessage ()); Item.put ("DateTime", M.getdatetime ()); //item.put ("Color", r.color.red); //item.put ("Bacgkunon", r.color.red);Messagelist2.add (item); } LV=(ListView) Findviewbyid (R.ID.LISTVIEW1); SA=NewSimpleadapter ( This, MessageList2,//Data is a data mix coupled to the interfaceR.layout.listviewitems,NewString[] {"UserName", "Lastmessage", "datetime", "Tou"},//from Never come                New int[] {r.id.tv_username,r.id.tv_lastmessage,r.id.tv_datetime,r.id.img}//to get there.                );        Lv.setadapter (SA); Lv.setonitemclicklistener (NewOnitemclicklistener () {@Override Public voidOnitemclick (adapterview<?>Parent, view view,intPositionLongID) {MAP<String,Object> item =Messagelist2.get (position); Item.put ("Tou", "0");            Sa.notifydatasetchanged (); }                    });

1, through openHelper2 helper = new OpenHelper2 (mainactivity.this); Sqlitedatabase db = Helper.getwritabledatabase (); Call OpenHelper2 to create the table and initialize the data at the time of creation.

2, through the Cuosor cursor to determine whether the Messaget table has a value, if not NULL, through the C.getcolumnindex () method to fetch the field-related values in the table.

3. Then add the value to the Union.

4. The set () and The Get () method are used to assign and value the set.

Android ListView Add Data Dynamically (Sqliteopenhelper class add data)

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.