Holiday group assistant for Android basic Integration Project (1), android Group

Source: Internet
Author: User

Holiday group assistant for Android basic Integration Project (1), android Group

Basic Android Integration Project (1)Festival Group assistant part 1

-- Reprinted with the source: coder-pig



This section introduces:


I have already written more than half of the Android entry-level series. I have learned so much theoretical knowledge. How can I do it without practice?

In actual development, we will encounter more problems and reinforce our basic knowledge! In view

The level of the author is limited. This project is intended for beginners. If you are passing by, do not try it! Let's talk about the first one.

Trainer Program. The Mid-Autumn Festival of the past few days is Teachers' Day. Various blessing text messages are everywhere, and you can send a group of messages by hand.

The text message is boring! You can send a group of text messages that have been prepared by others. If others do not know who you are, add at least one:

Dear XXX, I am the Old Wang next door.At least others know who you are! Okay, you don't have to talk about it. Start the app.

Development!




Ps: the basic functions of the app have been implemented as follows. You can download the app if necessary.

Relevant functions will be gradually improved later:

:



Download reference code:

Source code download



Body:


Highlights of this section:







Detailed description of the development process:


1) Create a database

Create a database file: There are two tables: contacts for storing contacts and festival for storing holiday greetings.

You can directly use SQLite Expert or other SQLite visualization tools to create tables. You can create tables using code or manually.

Run the following statement to generate a database table:

"Create table festival (sentence_id integer primary key autoincrement, detail )"

"Create table contacts (_ id integer primary key, pname, pnumber, pstate )"

Next, enter the data in the day table. The structure of the ending table is as follows:

Festival table:


Contacts table:





2) check whether the database file exists when the application starts.

After creating the database, we needCopy database files to the assert directoryLower

What should we do here?

When starting an application, we need to determine whether there are any database files under data/<package name>/database.

If it does not exist, we need to use the code to import the database file to the specified directory!


① First define our database name and package name constant:

Public static String dbName = "my. db"; // database name private static String DATABASE_PATH = "/data/com. jay. example. festivalsmshelper/databases /";

② Then define the method to determine whether 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, 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 () // determines whether a folder exists. If no folder exists, a new dir is created. mkdir (); FileOutputStream OS = null; try {OS = new FileOutputStream (databaseFilenames); // get 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 onCreate () method of MainActivity to call the above two methods:

Boolean dbExist = checkDataBase (); if (dbExist) {} else {// if it does not exist, write the database in assert to the mobile phone try {copyDataBase ();} catch (IOException e) {throw new Error ("database replication Error ");}}

⑤ Open File Exploer to check whether the database File has been copied:


It indicates that the database file has been copied. There is only one my. db file! The next my. do-journal is executed.

Other operations are generated!




3) read the Contact Directory of the system:

Here, we only read the Contact Directory, not the contact in the SIM card!

This section relates to the usage system provided by us.ContentProviderNow!

Let's first find out the database file of the contacts provided by the system!

Open the file browser:Data/com. android. providers. contacts/databases

The followingContacts2.dbThe file is the database file of the storage system contact:


View several important basic tables and related fields after export:

Contacts table


Data Table


Phone_look_up table


Raw_contact table


The four above are the four tables that we should pay attention.

Let's talk about the data we want to obtain: Contact id, name, and phone number.

Therefore, we define a GetPhone class and a method for reading contacts to store read data in the list set:

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); while (cursor. moveToNext () {Person person Person = new Person (); // obtain the contact idString contatId = cursor. getString (cursor. getColumnIndex (ContactsContract. contacts. _ ID); person. setId (Integer. parseInt (contatId); // obtain the contact name String name = cursor. getString (cursor. getColumnIndex (ContactsContract. contacts. DISPLAY_NAME); person. setName (name); // because a contact may have several phone numbers, we only need to obtain one here, so we will not traverse Cursor phones = context cyclically. getContentResolver (). query (ContactsContract. commonDataKinds. phone. CONTENT_URI, null, ContactsContract. commonDataKinds. phone. CONTACT_ID + "=" + contatId, null, null); phones. moveToFirst (); String num = phones. getString (phones. getColumnIndex (ContactsContract. commonDataKinds. phone. NUMBER); person. setNumber (num); person. setState (-1); persons. add (person); phones. close ();} cursor. close (); return persons ;}



4) define a data insertion method:

The parameter of this method is a Person object. We use ContentValues to store different data retrieved from person!

Call db. insert ("contacts", null, contentValue) to insert the record to 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());db.insert("contacts", null, values);}


5) Call the method of getting contacts in MainActivity to insert data.

For fear of too much data and getting stuck, add a progress bar. the user is not so upset!

A new thread is added. After one second, the progress bar disappears. The first interface disappears and jumps through intent.

To the second interface!


Code:

// Add a progress bar, too much data may be stuck, and the user may not be happy with final ProgressDialog dialog = ProgressDialog. show (this, "prompt", "reading 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 (); // determines whether the number of contacts has changed. if no change is made, you do not need 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 to make the circle progress bar disappear after one second, and the first interface disappears, jump to the Second Interface new Thread () {public void run () {try {sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} dialog. dismiss (); Intent it = new Intent (getApplicationContext (), ChooseActivity. class); startActivity (it); finish ();};}. start ();


6) view the running results:


After exporting the my. db file, you can see that the data in the contacts table already has data.

In addition, I still remember that there is a Person class missing. Four attributes are defined: id, name, number, and state (whether the record has been sent)

This is not provided here. In addition, you need to create a second Activity to complete the Intent jump! Otherwise, an error will be reported!





Knowledge Point summary:

1. Check whether database files in the app exist? If it does not exist, how can I use the input stream to write files to the corresponding directory?

2. How to obtain files in assert to obtain input stream objects;

3. Where can I find the database where the system saves contacts? Learn about related tables and fields!

Read the contact information we need in the table!

4. Call the insert () method of the database to insert data of the ContentValues type.

5. How to obtain the number of records in 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 set:List. size ();

Now, let's take a look at this section. If you have any suggestions or comments for this article, please point them out!

Thank you! The code of the project will be gradually improved later!







How can I crack the limit on sending SMS messages to Android systems? I want to send over 100 text messages to my group on a holiday, so I have to order to continue to be speechless on my cell phone.

Provides SMS sending platform, MMS sending platform software, and wap platform software. 3g integrated messaging platform (SMS message wap)
Provides SMS sending platform, MMS sending platform software, and wap platform software. 3g integrated messaging platform (SMS message wap)
 
How many people can a group assistant send at a time?

A maximum of 200 people, with a limit of about 25 messages. (after I sent so many messages, I failed to send messages ..)
 

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.