ListView Displays data for SQLite

Source: Internet
Author: User
Tags sqlite database

In Android, both ListView and SQLite are very common. This time we will combine this two knowledge point to write a demo.

Function: The data in SQLite is displayed with a ListView.

Look first.

The first is the database

Then the run

Next is the explanation, after running the program, first click the Create Database button, will create 50 data, and then click on the query, will be the 50 data query and display in the ListView.

Look directly at the code!

Layout file Activity_main.xml

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical"Android:paddingbottom= "@dimen/activity_vertical_margin"Android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"Tools:context= "Com.example.listviewdemo.MainActivity" >    <ButtonAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:onclick= "Create_data"Android:text= "Create Data" />    <ButtonAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:onclick= "Query_data"Android:text= "Query data" />        <ListViewAndroid:id= "@+id/lv"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"        /></LinearLayout>

Java files

Girl.java

As a javabean, the storage data class uses the

 PackageCom.example.listviewdemo; Public classGirl {PrivateString name; Private intAge ; PrivateString Phone;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString Getphone () {returnphone; }     Public voidSetphone (String phone) { This. Phone =phone; } @Override PublicString toString () {returnName+ "," +age+ "," +phone; }     PublicGirl (String name,intAge , String phone) {        Super();  This. Name =name;  This. Age =Age ;  This. Phone =phone; }        }

Mainactivity.java

 PackageCom.example.listviewdemo;Importjava.util.ArrayList;Importjava.util.List;Importandroid.app.Activity;Importandroid.content.ContentValues;ImportAndroid.database.Cursor;Importandroid.database.sqlite.SQLiteDatabase;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.BaseAdapter;ImportAndroid.widget.ListView;ImportAndroid.widget.TextView;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {PrivateMyopensqlhelp Mydatebasehelper; List<Girl>girlist; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Mydatebasehelper=NewMyopensqlhelp ( This, "People.db",NULL, 1); Sqlitedatabase DB=mydatebasehelper.getwritabledatabase (); Girlist=NewArraylist<girl>(); }         Public voidCreate_data (View v) {sqlitedatabase db=mydatebasehelper.getwritabledatabase ();  for(inti=0;i<=50;i++) {contentvalues values=Newcontentvalues (); Values.put ("Name", "Zhu Master Love" +i); Values.put ("Age", "19"); Values.put ("Phone", "135708" +i); Db.insert ("Girl",NULL, values); } toast.maketext ( This, "Data creation succeeded", 0). Show (); }         Public voidQuery_data (View v) {sqlitedatabase db=mydatebasehelper.getwritabledatabase (); Cursor Cursor= Db.query ("Girl",NULL,NULL,NULL,NULL,NULL,NULL);  while(Cursor.movetonext ()) {String name= Cursor.getstring (Cursor.getcolumnindex ("Name")); intAge = Cursor.getint (The Cursor.getcolumnindex ("Age")); String Phone= Cursor.getstring (Cursor.getcolumnindex ("Phone")); Girl Girl=NewGirl (Name,age,phone);                    Girlist.add (girl); }         //get the Listveiw object .ListView LV =(ListView) Findviewbyid (r.id.lv); //setting up the adapterLv.setadapter (NewMyaapter ()); }  //Adapter Class    classMyaapterextendsBaseadapter {//gets the number of elements in the collection that are called by the system@Override Public intGetCount () {//TODO auto-generated Method Stub            returngirlist.size (); } @Override PublicObject GetItem (intposition) {            //TODO auto-generated Method Stub            return NULL; } @Override Public LongGetitemid (intposition) {            //TODO auto-generated Method Stub            return0; }        //called by the system to return a View object as a ListView entry        /** Position: The View object returned by this GetView method call is in the ListView in the first few entries, the value of the position is how much **/@Override PublicView GetView (intposition, View Convertview, ViewGroup parent) {TextView TV=NewTextView (mainactivity. This); Tv.settextsize (18); //gets the elements in the collectionGirl Girl =Girlist.get (position);                        Tv.settext (Girl.tostring ()); returnTV; }            }}

Myopensqlhelp.java

Database helper, the class to be created with the SQLite database

 PackageCom.example.listviewdemo;ImportAndroid.content.Context;Importandroid.database.sqlite.SQLiteDatabase;Importandroid.database.sqlite.SQLiteDatabase.CursorFactory;ImportAndroid.database.sqlite.SQLiteOpenHelper;ImportAndroid.widget.Toast; Public classMyopensqlhelpextendssqliteopenhelper{ Public Static FinalString create_girl = "CREATE table GIRL (_id integer primary key Autoincrement,name char (), Age Integer,phone char (20))" ; PrivateContext Mcontext;  PublicMyopensqlhelp (Context context, String name, Cursorfactory factory,intversion) {        Super(context, name, Factory, version); //TODO auto-generated Constructor stubMcontext =context; } @Override Public voidonCreate (Sqlitedatabase db) {//TODO auto-generated Method StubDb.execsql (Create_girl); /*Toast.maketext (Mcontext, "Create successded", 0). Show ();*/} @Override Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) {        //TODO auto-generated Method Stub            }}

                                                                   

ListView Displays data for SQLite

Related Article

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.