Android uses a database to transfer data

Source: Internet
Author: User

---restore content starts---

I. Building a table

// Create a database from Sqlitedatabase stu.db3        Final Sqlitedatabase db = Sqlitedatabase.openorcreatedatabase (thisnull);        Db.execsql ("CREATE TABLE student (ID integer PRIMARY KEY, Name VARCHAR (), score INTEGER)");    // Create a student student table     

The Openorcreatedatabase () method is used to open or create the database. This is a static method that cannot be created with new but is called with the class name.

public static Sqlitegdatabase Openorcreatedatabase (String path,sqlitedatabase.cusorfactory Factory)

The first parameter is a database file path (including the file name) available Getfilesdir () to get the path

The second parameter generally defaults to NULL to use the default Gursorfactory object

Two. Data insertion

/** * Save Operation*/Save.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View arg0) {/** Get Data*/String i=Id.gettext (). toString (); String N=Name.gettext (). toString (); String s=Score.gettext (). toString (); //Execute INSERT statement                Try{db.execsql (INSERT into student VALUES (?,?,?),Newstring[]{i,n,s}); Format}Catch(Exception e) {//Insert FailedToast.maketext (mainactivity. This, "The school number already exists.", Toast.length_short). Show (); return; } toast.maketext (mainactivity. This, "Saved successfully", Toast.length_short). Show (); }        });

Third, data read

        /** * read operation and display in UI interface using Simpleadapter*/Read.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View arg0) {/** Bind data to ListView*/ArrayListNewArraylist(); //get data from database to ListItemcursor cursor = db.rawquery ("SELECT * FROM Student",NULL);  while(true) {                                        if(Cursor.movetonext () = =false) {                         Break; } HashMap<string, object> map =NewHashmap<string, object>(); Map.put ("ItemId", Cursor.getint (0)); Map.put ("ItemName", cursor.getstring (1)); Map.put ("Itemscore", Cursor.getint (2));                Listitem.add (map); }                                                //Build Adapter It's a bridge between data and interface to make the database SQLite content appear in the graphical user interface                FinalSimpleadapter Listitemadapter =NewSimpleadapter (mainactivity. This, Listitem,r.layout.list_item,Newstring[]{"ItemId", "ItemName", "Itemscore"},                        New int[]{,,}]; //Add and displayList.setadapter (Listitemadapter); /** 3 Click events in ListView list*/List.setonitemclicklistener (NewOnitemclicklistener () {@Override Public voidOnitemclick (adapterview<?>arg0, view view,intPositionLongArg3) {                        //TODO auto-generated Method Stubmap<string,object> m = (map<string,object>) Listitemadapter.getitem (position); Id.settext (M.get ("ItemId"). ToString (). Trim ()); Name.settext (M.get ("ItemName"). ToString (). Trim ()); Score.settext (M.get ("Itemscore"). ToString (). Trim ()); Index= M.get ("ItemId"). ToString (). Trim ();//Save the selected user ID for deletion and modification                                            }                                    });        }        }); 

The list and map<string,object> and Simpleadapter in Android are used to save data and display 366936905.shtml

Simpleadapter and ListView Introduction link Address 1.


Iv. Update of data

 /** Update Operation*/Update.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View arg0) {String updatename=Name.gettext (). toString (). Trim (); String Updatescore=Score.gettext (). toString (). Trim (); String SQL= "UPDATE student SET name=?,score=?" Whrer id=? "; if(Index! =NULL){                  Try{toast.maketext (mainactivity). This, updatename+ "--" +Updatescore, Toast.length_short). Show (); Db.execsql (SQL,NewString[]{updatename,updatescore,index}); Index=NULL;//index re-set to emptyToast.maketext (mainactivity. This, "Modified successfully", Toast.length_short). Show (); }Catch(Exception e) {toast.maketext (mainactivity. This, "Modify Failed", Toast.length_short). Show ();        }                }                                            }        }); 

V. Deletion of data

  /** Delete Operation*/Delete.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View arg0) {if(index!=NULL) {//a record has been selected//Execute INSERT statementDb.execsql ("DELETE from student WHERE id=?",NewString[]{index}); Index=NULL;//index re-set to nullToast.maketext (mainactivity. This, "Delete succeeded", Toast.length_short). Show (); } Else{toast.maketext (mainactivity). This, "Please select the data you want to delete", Toast.length_short). Show (); }            }        });

Android uses a database to transfer data

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: 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.