Dbadapter has been created, now we can use the database. The following sections will introduce General CRUD (add, read, update, delete).
Add a contact to the table.
1. Use the previous project to add some code to the Databasesactivity.java.
The public class Databasesactivity extends activity {/** called the ' when ' is the ' The activity ' is the ' the '
---'
@Override
public void OnCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.main);
Dbadapter db = new Dbadapter (this);
---Add a contact---
db.open ();
Long id = db.insertcontact ("Manoel", "manoel@hotmail.com");
id = db.insertcontact ("Mary", "mary@hotmail.com");
Db.close ();
}
2. Press F11 to debug on the simulator.
First, create an instance of the Dbadapter class:
Dbadapter
db = new Dbadapter (this);
The Insertcontact () method returns the ID of the inserted row. If this process is wrong, return-1.
Using DDMS to view the Android device or emulator, you will see a database named MyDB below the Databases folder.
Get all the contacts.
Using the Getallcontacts () method, you can get all the contact information.
1. Use the previous example and add some code.
The public class Databasesactivity extends activity {/** called the ' when ' is the ' The activity ' is the ' the '---' @Override
public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Dbadapter db = new Dbadapter (this);
*//---Add a contact---db.open ();
Long id = db.insertcontact ("Manoel", "manoel@hotmail.com");
id = db.insertcontact ("Mary", "Mary@hotmail.com");
Db.close ();
* *//--get All contacts---db.open ();
Cursor C = db.getallcontacts ();
if (C.movetofirst ()) {do {displaycontact (c);
while (C.movetonext ());
} db.close (); public void DisplayContact (Cursor c) {Toast.maketext (this, "ID:" + c.getstring (0) + "\ N "+" Name: "+ C.GEtstring (1) + "\ n" + "Email:" + c.getstring (2), Toast.length_long). Show (); }
}