Android+sqlite implementation of content-driven random content push (i)

Source: Internet
Author: User

Do not say the Web app, many local apps have some random content push, such as random push some small knowledge, ancient poetry, famous paintings and so on, the interface to make a good look at a bit can appear special literary fan,

Recently is to see some of these applications, just want to implement it yourself, this method is to come out of their own, it is not clear how those apps are written.

In this I use the Android-supported SQLite, a lightweight database, just to add a little bit of knowledge that has not been used before.

1. First, a database file is required:

Directly with the database management software new SQLite will be missing two tables, I do not bother to add their own code to use the Android program to generate their own.

1  PackageCom.lfk.poem;2 3 ImportAndroid.content.Context;4 Importandroid.database.sqlite.SQLiteDatabase;5 ImportAndroid.database.sqlite.SQLiteOpenHelper;6 ImportAndroid.widget.Toast;7 8 /**9 * Created by Administrator on 2015/5/8.Ten  */ One  Public classDBHelperextendsSqliteopenhelper { A     Private  Static FinalString creat_db = "CREATE TABLE book (" -+ "ID integer primary key autoincrement," -+ "Poem text"); the     PrivateContext Mcontext; -  -      PublicDBHelper (context context, String name, Sqlitedatabase.cursorfactory factory,intversion) { -         Super(context, name, Factory, version); +Mcontext =context; -     } +  A @Override at      Public voidonCreate (Sqlitedatabase db) { - Db.execsql (creat_db); -Toast.maketext (Mcontext, "succeed++++++++++", Toast.length_short). Show (); -     } -  - @Override in      Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) { -     } to}

First rewrite a DBHelper class extends Sqliteopenhelper class inside set a static string, the string is to define the contents of the new table, the first is the ID set to the order of self-increment, the second is the ancient poetry, set to text form,

Db.execsql (creat_db); Use this statement to generate *.db files in OnCreate, and then issue a hint succeed++++++++.

Then add a button to the main interface, run Dbhelper.getwritabledatabase () in the onclick, and you can create/open a database.

2. Add content to the database:

Now we have an empty database, we can't use it, we don't want to enter the content manually, so we need to get the database out of the way.

You can find your database on the phone (or in the emulator with a re file manager) in Data/data/<package name>/database/.

Just like this, and then cuff it to the computer.

Install Navicat for SQLite on your computer and open the. db file you brought out:

The book in it is a table file we just created with the code, and then we have to prepare the content you want to enter.

id = Poem001= Zhang Jiuling: one of the four first to come to the sea, the pool Huang dare not care. Side See double Kingfisher, nest in three beads tree. To straighten the top of the precious wood, no golden pill to fear. The people in the United States are the ones who are wise to make God evil. This is my tour of the universe, Yi who mu. 002= Zhang Jiuling: four first Lan Yachun luxuriantly, Guihua Bright. Shin Shing is in this business, the holiday season. Behold dwelling, caught on sit and Yue. The grass has the heart, why ask the beauty to fold? 003= Zhang Jiuling: Four of the first three people to lie in the bedroom, the delay of the wash solitary Qing. This is to thank the high bird, because of the spread of love. Rixi Bosom empty intention, person who sense to fine? Fly Shenli from the isolated, how to comfort my sincerity? 004= Zhang Jiuling: Four of the first four Jiangnan has Dan Orange, through the winter of the Greenwood. Yi is warm in the atmosphere, its own age chilling. Can recommend the Jia, but the deep resistance! The circulation is not to be found when the fate of the operation is met. The tree is a peach, and the wood is not overcast? 005 = Li Bai: Under the end of Nanshan Hu Mountain, the night from the Green Hill, mountain month with people, but gu to the path, gray horizontal Cui Wei. Together with Tian, childish Open Jing Gate. Green bamboo into the path, Qing luo brush line clothes. Happy words to rest, wine chat together wave. Long singing pine Wind, the song of the river star sparse. I drunk June Fu Le, ran a total forget machine.

For example, I wrote the fixed format, and write their field names (on the regular expression Ah!). )

Then right-click the Book table to pour the wizard, and in the third step set the delimiter to =

If we succeed, we will find that the fields are set so that we can successfully import the

Then we have the data in our book table so that we can use it normally:

OK, let's save it and put it in the raw folder under the res of our project.

3. Modify the main function completion function:
1 PackageCom.lfk.poem;2 3ImportAndroid.content.Context;4ImportAndroid.database.Cursor;5Importandroid.database.sqlite.SQLiteDatabase;6ImportAndroid.os.Bundle;7Importandroid.os.Environment;8Importandroid.support.v7.app.ActionBarActivity;9ImportAndroid.util.Log;10ImportAndroid.view.View;11ImportAndroid.widget.Button;12ImportAndroid.widget.TextView;13 14ImportJava.io.File;15Importjava.io.FileNotFoundException;16ImportJava.io.FileOutputStream;17Importjava.io.IOException;18ImportJava.io.InputStream;19 20 21 Public classMainactivityextendsactionbaractivity {22Private Final intBuffer_size = 400000;23 Public Static FinalString db_name = "poem.db";//saved database file name24 Public Static FinalString package_name = "Com.lfk.poem";//app's package name25 Public Static FinalString Db_path = "/data" + environment.getdatadirectory (). GetAbsolutePath () + "/"//Some parameters are defined here, including file size, package name, database name, location of the database, etc.+ package_name+ "/databases";//where to store the database on your phone28PrivateContext Mcontext;29@Override30protected voidonCreate (Bundle savedinstancestate) {31Super. OnCreate (savedinstancestate);32Setcontentview (r.layout.activity_main);33//dbhelper = new DBHelper (This, "poem.db", null,1);Sqlitedatabase Database =OpenDatabase (); cursor cursor = database.query ("book",NULL,NULL,NULL,NULL,NULL,NULL);//This part is I want to print everything in the log to see, can be deleted36if(Cursor.movetofirst ()) {37 Do {The String id = cursor.getstring (cursor.getcolumnindex ("id"));The poem String = cursor.getstring (Cursor.getcolumnindex ("poem"));LOG.E ("id=" +id, "poem=" +poem);41} while(Cursor.movetonext ());42         }43cursor.close ();44database.close ();a button button =(Button) Findviewbyid (r.id.create_it);Button.setonclicklistener (NewView.onclicklistener () {47@Override48 Public voidOnClick (View v) {49intLL = (int) (1+math.random () * (5));Sqlitedatabase Database =OpenDatabase ();The cursor cursor = database.rawquery ("SELECT * FROM book Where id =" +ll,NULL);//Change the button, set a random number 1-5, open the database, and then use the SQL statement from the book to findCursor.movetofirst ();//and id= random amount and then take out the first bit of data, 0 bits is the ID set it into a textview insidePoem String = cursor.getstring (1);LOG.E (poem, "================");TextView TextView =(TextView) Findviewbyid (R.id.text_view);56Textview.settext (poem);57Cursor.close (); Database.close ();58             }59         });60     }61 Publicsqlitedatabase OpenDatabase () {62Try {File Mydatapath =NewFile (db_path);64if(!mydatapath.exists ())65             {Mydatapath.mkdirs ();//If you do not have this directory, create67             }DBFile String = mydatapath+ "/" +db_name;69if(! (NewFile (DBFile). Exists ()) {//determine whether the database file exists, if it does not exist, do import, or open the database directly//This function is used to open the database, if there is no database, it will be copied from the raw folder to the local folder70InputStream is;is = This. Getresources (). Openrawresource (R.raw.poem);//databases that you want to importFileOutputStream fos =NewFileOutputStream (dbfile);73byte[] buffer =New byte[buffer_size];74intCount = 0 ;75 while((count = is.read (buffer)) > 0) {Fos.write (buffer, 0, count);77                 }78fos.close ();79is.close ();80             }Bayi Sqlitedatabase db = Sqlitedatabase.openorcreatedatabase (DBFile,NULL);LOG.E ("=======================", "Get It ======================"));83returndb;84}Catch(FileNotFoundException e) {LOG.E ("Database", "File not Found");86e.printstacktrace ();87}Catch(IOException e) {LOG.E ("Database", "IO exception");89e.printstacktrace ();90         }91return NULL;92     }93}

So we can put the data from the database on the interface, so far, the initial function is finished

There may be a blog post, the next step is to do some changes in the interface, after all, now this picture is too ugly!

like, please, =_=! .

Android+sqlite implementation of content-driven random content push (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.