Android Learning Notes-save data to SQL database (saving data in SQL Databases) _android

Source: Internet
Author: User
Tags sqlite

Knowledge Points:

1. Using SQL Helper to create a database
2. Check and delete data (Prdu:put, Read, Delete, Update)

Background knowledge:

The previous article learned about Android save files, and today I learned to save data to a SQL database. I believe you are not unfamiliar with the database. For a large number of duplicate, with a specific structure of the data to save, with the SQL database to save is the ideal.

The following will be a database demo on the contact person to learn specific.

Specific knowledge:

1. Define Contract class

Before you create the SQL database, create the contract class. So what is the contract class?

Copy Code code as follows:

Definition of Contract class:
Contract class, can also be called Companion class.
This is what the Android developer Help document says:
< A contract class is a container for constants this define names for URIs,
tables, and columns. The contract class allows the same constants
Across all of the other classes in the same package. This lets your change a
Column name in one place and have it propagate throughout your code.>
The contact class is a container that defines the names of the URIs, tables, and columns. This class allows us to use the same constants under different classes of the same package.
We changed the name of the column in one place and spread it to every part of our code.

Copy Code code as follows:

Package com.example.sqlitetest;
Contract class
public class Contacts {

int _id;
String _name;
String _phone_number;

Public Contact () {

}
public contacts (int ID, string name, String _phone_number) {
this._id = ID;
This._name = name;
This._phone_number = _phone_number;
}

Public Contacts (string name, String _phone_number) {
This._name = name;
This._phone_number = _phone_number;
}
public int GetID () {
return this._id;
}

public void SetID (int id) {
this._id = ID;
}

Public String GetName () {
return this._name;
}

public void SetName (String name) {
This._name = name;
}

Public String Getphonenumber () {
return this._phone_number;
}

public void Setphonenumber (String phone_number) {
This._phone_number = Phone_number;
}
}

2. Create a database using SqlHelper

Just as saving files are stored internally, Android stores our databases in proprietary application storage, which ensures that our data is secure. cannot be accessed by other applications.

The database stored on the device is guaranteed to exist:
The/data/data/<package_name>/databases directory

To use Sqliteopenhelper, we need to create a subclass that overrides the OnCreate (), Onupgrade (), and OnOpen () callback methods.

3. Change the data to check and delete

Add: Pass Contentvalue value to insert () method.

Copy Code code as follows:

Sqlitedatabase db = This.getwritabledatabase ();

Contentvalues values = new Contentvalues ();
Values.put (Key_name, Contact.getname ());
Values.put (Key_ph_no, Contact.getphonenumber ());

Db.insert (table_contacts, null, values);
Db.close ();

Delete: Delete () method

Copy Code code as follows:

Sqlitedatabase db = This.getwritabledatabase ();
Db.delete (table_contacts, key_id + "=?",
New string[] {string.valueof (Contact.getid ())});
Db.close ();

Change: Update () method

Copy Code code as follows:

Sqlitedatabase db = This.getwritabledatabase ();

Contentvalues values = new Contentvalues ();
Values.put (Key_name, Contact.getname ());
Values.put (Key_ph_no, Contact.getphonenumber ());


Return Db.update (Table_contacts, values, key_id + "=?"),
EW string[] {string.valueof (Contact.getid ())});

Check: Query () method

Copy Code code as follows:

Sqlitedatabase db = This.getreadabledatabase ();

Cursor Cursor = Db.query (table_contacts, new string[] {key_id,
Key_name, Key_ph_no}, key_id + "=?",
New string[] {string.valueof (ID)}, NULL, NULL, NULL, NULL);
if (cursor!= null)
Cursor.movetofirst ();

Contact contacts = new Contact (integer.parseint (cursor.getstring (0)),
Cursor.getstring (1), cursor.getstring (2));

return contacts;

The complete Databasehelper code is as follows:

Copy Code code as follows:

Package com.example.sqlitetest;

Import java.util.ArrayList;
Import java.util.List;

Import android.content.ContentValues;
Import Android.content.Context;
Import Android.database.Cursor;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.database.sqlite.SQLiteOpenHelper;

public class Databasehelper extends Sqliteopenhelper {

Database version
private static final int database_version = 1;

Database name
private static final String database_name = "Contactsmanager";

Contact table Name
private static final String table_contacts = "CONTACTS";

The column name of the Contact table
private static final String key_id = "ID";
private static final String Key_name = "NAME";
private static final String key_ph_no = "Phone_number";

Public Databasehelper {
Super (context, database_name, NULL, database_version);
}

Create a table
@Override
public void OnCreate (Sqlitedatabase db) {
String create_contacts_table = "CREATE TABLE" + table_contacts + "("
+ key_id + "INTEGER PRIMARY KEY," + Key_name + "TEXT,"
+ key_ph_no + "TEXT" + ")";
Db.execsql (create_contacts_table);
}

Update table
@Override
public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
Delete old tables
Db.execsql ("DROP TABLE IF EXISTS" + table_contacts);

Create a table again
OnCreate (DB);
}

/**
* Additions and deletions to check operation
*/

Add a new Contact
void Addcontact (Contact contacts) {
Sqlitedatabase db = This.getwritabledatabase ();

Contentvalues values = new Contentvalues ();
Values.put (Key_name, Contact.getname ());
Values.put (Key_ph_no, Contact.getphonenumber ());

Insert Row
Db.insert (table_contacts, null, values);
Db.close (); To close a database connection
}

Get Contact
Contact getcontact (int id) {
Sqlitedatabase db = This.getreadabledatabase ();

        Cursor Cursor = Db.query (table_contacts, new string[] {key_id,
                key_name, Key_ph_no}, key_id + "=?",
                New String[] {string.valueof (ID)}, NULL, NULL, NULL, NULL);
        if (cursor!= null)
             Cursor.movetofirst ();

Contact contacts = new Contact (integer.parseint (cursor.getstring (0)),
Cursor.getstring (1), cursor.getstring (2));
return contacts;
}

Get all Contacts
Public list<contact> getallcontacts () {
list<contact> contactlist = new arraylist<contact> ();
Select All Query
String selectquery = "SELECT * from" + table_contacts;

Sqlitedatabase db = This.getwritabledatabase ();
Cursor Cursor = db.rawquery (selectquery, NULL);

        if (Cursor.movetofirst ()) {
             do {
                 contacts = new Contact ();
                Contact.setid ( Integer.parseint (cursor.getstring (0)));
                Contact.setname ( Cursor.getstring (1));
                Contact.setphonenumber (cursor.getstring (2));
                Contactlist.add ( Contact);
           } while (Cursor.movetonext ());
       }

return contactlist;
}

Update individual contacts
public int updatecontact (contacts contact) {
Sqlitedatabase db = This.getwritabledatabase ();

Contentvalues values = new Contentvalues ();
Values.put (Key_name, Contact.getname ());
Values.put (Key_ph_no, Contact.getphonenumber ());

Update rows
Return Db.update (Table_contacts, values, key_id + "=?"),
New string[] {string.valueof (Contact.getid ())});
}

Delete a single contact
public void DeleteContact (contacts contact) {
Sqlitedatabase db = This.getwritabledatabase ();
Db.delete (table_contacts, key_id + "=?",
New string[] {string.valueof (Contact.getid ())});
Db.close ();
}


Get the number of contacts
public int Getcontactscount () {
String countquery = "SELECT * from" + table_contacts;
Sqlitedatabase db = This.getreadabledatabase ();
Cursor Cursor = db.rawquery (countquery, NULL);
Cursor.close ();

return Cursor.getcount ();
}
}

There are some code is not the focus of this study, it is not posted. I need to leave a message for me.

Demo Run Effect chart:

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.