Android Foundation integration Project Holiday Group Assistant (i)

Source: Internet
Author: User

Android Foundation Integration Project (i) Festival Mass Helper Part 1

--Reprint Please specify Source: Coder-pig



Introduction to this section:


The Android entry series has been written half, learned so much theoretical knowledge, do not practice how to do?

In the actual development we will encounter more problems, but also to strengthen our basic knowledge! Given

The level of the author is limited, the project, the face of beginners, you do not like to go by Daniel! Well, the first one.

Practiced hand project Bar, a few days ago, the Mid-Autumn Festival today is Teachers ' day, all kinds of blessing messages flying, hand hit again mass, all

Text message A kind of, not fun! Directly with others to fix the message mass, others do not know who you are, at least add a:

Dear xxx, I'm the old king,..... next door. At least someone knows who you are! Okay, nonsense, don't say much, start the app

Development of it!




PS: The basic functions of the app have been implemented, as below, if necessary to download

The following will gradually improve the relevant functions:

:



Reference code Download:

SOURCE download



Body:


Highlights of this section:







Detailed development process:


1) Create a database

Create a database file: There are two tables, one for storing the contact's table contacts and the table for storing the festive Blessing words festival

Tables can be created directly using SQLite expert or other SQLite visualization tools, either code creation or manual creation

The code is created by executing the following statement to generate the database table:

"CREATE TABLE Festival (sentence_id INTEGER PRIMARY KEY autoincrement,detail)"

"CREATE TABLE Contacts (_id INTEGER PRIMARY key,pname,pnumber,pstate)"

Then the data entry for the festival table, the end of the table structure is as follows:

Festival table:


Contacts table:





2) Determine if the database file exists when the application starts

after completing the steps to create the database above, we then need to Copy the database file to the Assert directory under

What are we going to do here?

When the app starts we need to determine if the data/data/< package name >/database has our database file

If it doesn't exist, we need to import the database file into the specified directory by code!


① first defines our database name and the package name constants:

public static string Dbname= "my.db";//Database name private static string Database_path= "/data/data/ Com.jay.example.festivalsmshelper/databases/";

② then defines the method by which the database file exists:

public Boolean checkdatabase () {        sqlitedatabase CheckDB = null;        try{            String databasefilename = database_path+dbname;            CheckDB =sqlitedatabase.opendatabase (DatabaseFileName, NULL,                    sqlitedatabase.open_readonly);        } catch (Sqliteexception e) {                     }        if (checkdb!=null) {            checkdb.close ();        }        return CheckDB!=null?true:false;    }

③ If the database file does not exist, we need to copy the database file to the specified directory:

    public void Copydatabase () throws ioexception{        String databasefilenames =database_path+dbname;        File dir = new file (Database_path);        if (!dir.exists ())//Determine whether the folder exists, does not exist to create a new            dir.mkdir ();        FileOutputStream OS = null;        try{            os = new FileOutputStream (databasefilenames);//Gets the write stream of the database file        }catch (FileNotFoundException e) {            E.printstacktrace ();        }        InputStream is = MainActivity.this.getAssets (). Open ("my.db");        byte[] buffer = new byte[4096];        int count = 0;        try{while              ((count=is.read (buffer)) >0) {                os.write (buffer, 0, count);                Os.flush ();            }        } catch (IOException e) {e.printstacktrace ();}        Is.close ();        Os.close ();      }

④ Add the following code to the Mainactivity OnCreate () method to invoke the two methods:

Boolean dbexist = Checkdatabase (); if (dbexist) {}else{//does not exist write the database in assert to the phone try{    copydatabase ();} catch (IOException e) {throw new error ("Replication database Error");}}

⑤ Open File Exploer to see if the database file is copied:


This means that the database file has been copied, and there is only one my.db file! The back of the my.do-journal was executed.

Other operations generated!




3) Read the system's contact directory:

The only thing we read here is the directory of the contacts, not the contacts in the SIM card!

This piece involves what we have learned before using the system provided by the ContentProvider !

Let's find out the database files of the contact people we have provided in the system.

Open File Explorer:data/data/com.android.providers.contacts/databases

The following contacts2.db file is the database file for the storage system contact:


After exporting, see a few important basic tables, along with related fields:

Contacts table


Data table


PHONE_LOOK_UP table


Raw_contact table


The above four are the four watches we need to keep an eye on.

All right, here's the data we're going to get: Contact ID, name, a phone number .

So we define a class Getphone class and define a method to read the contact, reading to the data store in the list collection:

The code is as follows:

public static list<person> Getperson (context context) {list<person> persons = new Arraylist<person> () ; Contentresolver CR = Context.getcontentresolver (); cursor cursor = cr.query (contactscontract.contacts.content_uri,null, NULL, NULL, NULL), while (Cursor.movetonext ()) { Person man = new Person ();//Get contact idstring Contatid = cursor.getstring (Cursor.getcolumnindex ( contactscontract.contacts._id));p Erson.setid (Integer.parseint (Contatid));//Get contact name String name = Cursor.getstring ( Cursor.getcolumnindex (ContactsContract.Contacts.DISPLAY_NAME));p erson.setname (NAME);//Because there may be several phone numbers for a contact, But we're just getting one here and that's enough, so we don't loop through the cursor phones = context.getcontentresolver (). Query ( Contactscontract.commondatakinds.phone.content_uri,null, contactscontract.commondatakinds.phone.contact_id+ "=" + Contatid, NULL, NULL);p Hones.movetofirst (); String num = phones.getstring (Phones.getcolumnindex (ContactsContract.CommonDataKinds.Phone.NUMBER)); Person.setnumber (num);p erson.setstate ( -1);p ersons.add (person);p Hones.close ();} Cursor.close (); return persons;}



4) Define a method for inserting data:

The parameter of this method is the object of a person, and we use contentvalues to store the different data taken from person!

Then call db.insert ("Contacts", Null,contentvalue) to insert the record into the contacts table

Code:

public void Insert (person person) {Sqlitedatabase db = Dbopenhelper.getwritabledatabase (); Contentvalues values = new Contentvalues (), Values.put ("_id", Person.getid ()), Values.put ("PName", Person.getname ()); Values.put ("Pnumber", Person.getnumber ()), Values.put ("Pstate", Person.getstate ());d B.insert ("Contacts", NULL, values);}


5) Call the Get contact method in Mainactivity, insert the data

Afraid of data too much, there is stuck in the situation, add a progress bar, the user looked not so uncomfortable!

New one thread, a second after the progress bar disappears, the first interface disappears, through intent jump

To the second interface!


Code:

Add a progress bar, too much data may not be stuck, the user looked uncomfortable final progressdialog dialog = Progressdialog.show (this, "prompt", "read Contacts", false, true); Getcontactsservice getcontacts = new Getcontactsservice (Getapplicationcontext ()); list<person> persons = Getperson.getperson (Mainactivity.this); cursor cursor = getcontacts.query ("SELECT count (*) from contacts", null); Cursor.movetofirst ();//Determine if the number of contacts has changed, Without change, you don't have to call the following for loop if (persons.size ()! = Cursor.getint (0)) {for (person p:persons) {System.out.println (p.tostring ()); Getcontacts.insert (P);}} Set the circular progress bar to disappear after one second, and the first interface disappears, jumps to the second interface new Thread () {public void run () {try {sleep ()} catch (Interruptedexception e) { E.printstacktrace ();} Dialog.dismiss (); Intent it = new Intent (Getapplicationcontext (), chooseactivity.class); startactivity (it); Finish ();};}. Start ();


6) After running the effect view:


After exporting the my.db file, you can see that the data for the Contacts table is already available, and you have completed

Also remember that there is a person category missing, define four properties: Id,name,number,state (Record has been sent)

It is not given here, in addition to create a second activity to complete the intent jump Oh! Otherwise it will be an error!





Summary of Knowledge points:

1. Determine if the database file exists in the app? How to use an input stream to write a file to the appropriate directory

2. How to obtain the file in the assert, so as to obtain the input stream object;

3. Where can I find the database where the system holds the contacts, and the related tables and fields?

Read the contact information we need in the table!

4. Call the database's insert () method to insert data of type Contentvalues

5. How many records are available for a database table:

cursor cursor = getcontacts.query ("SELECT count (*) from contacts", NULL);

Cursor.movetofirst ();

Cursor.getint (0);

6. Get the data elements in the list collection :list.size ();

Well, this section will be here for the moment, if the article has any suggestions, criticism, welcome point!

Careless Gratitude! The code of the project will be refined with the following depth!






Holiday Group Assistant for Android Foundation Integration Project (i)

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.