Android + Sqlite: Random content presentation (1), androidsqlite
Not to mention the network app, many local apps have some random content push, such as random push of some small knowledge, ancient poetry, famous quotes and famous paintings, the interface can look a little better, it can look special style fan,
I recently read some of these applications and want to implement them myself. This method is self-developed and I don't know how those apps are written.
In this example, I used a lightweight database such as sqlite supported by android to add some useful knowledge points.
1. First, a database file is required:
Two tables are missing for sqlite created directly using the database management software, and I am too lazy to add it myself and use the code to make the android program generate it myself.
1 package com.lfk.poem; 2 3 import android.content.Context; 4 import android.database.sqlite.SQLiteDatabase; 5 import android.database.sqlite.SQLiteOpenHelper; 6 import android.widget.Toast; 7 8 /** 9 * Created by Administrator on 2015/5/8.10 */11 public class DBhelper extends SQLiteOpenHelper {12 private static final String CREAT_DB = "create table book ("13 + "id integer primary key autoincrement,"14 + "poem text)";15 private Context mcontext;16 17 public DBhelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {18 super(context, name, factory, version);19 mcontext = context;20 }21 22 @Override23 public void onCreate(SQLiteDatabase db) {24 db.execSQL(CREAT_DB);25 Toast.makeText(mcontext,"succeed++++++++++",Toast.LENGTH_SHORT).show();26 }27 28 @Override29 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {30 }31 }
First, rewrite a dbhelper extends SQLiteOpenHelper class to set a static string. The saved string is the content of the new table. The first one is id set to sequential auto-increment, and the second is the ancient poetry, set to text format,
Db.exe cSQL (CREAT_DB); Use this statement to generate the *. db file in OnCreate, and then send a prompt "succeed ++.
Then add a Button on the main interface and run dbhelper. getWritableDatabase () in OnClick to create/open a database.
2. add content to the database:
Now we get an empty database, which cannot be used. We do not want to manually enter the content one by one, so we need to take out the database.
You can find your database in data/<package name>/database/on your mobile phone (or the RE File Manager installed in the simulator.
Just like this, and then copy it to your computer.
Install Navicat for SQLite on your computer and open the. db file you have taken out:
The book in it is a table file we just created using code. Then we need to prepare the content you want to input.
Id = poem001 = Zhang Jiu-ling: I was surprised to hear that one of the four leaders, GU Hong, was at sea and did not dare to care about it. On the other side, you can see the double emerald bird, Which is nested in the sanzhu tree. Correction Zhenmu summit, have no fear of gold. The beauty server suffers from evil. Today, I am traveling, and I want to know what kind of yundun is. 002 = Zhang Jiu-ling: I was surprised by four heads: Lan ye Chunchun, and Gui Hua Qiujie. Xin this business, from ER for the festive season. Who knows Lin Qi, smell the wind sit happy. The grass and wood have their own heart, why do you want to fold the beauty? 003 = Zhang Jiu-ling: I was surprised to hear that the third person was lying alone, and I was so worried that I would be alone. Thank you for your patience. Who is the most refined person? Fei Shen Li is separated from him. How can he comfort me? 004 = Zhang Jiu-ling: I was surprised to see Dan-orange in the south of the Yangtze River. Ye yidi is warm and has a cold heart. You can recommend a guest! The endless cycle is not available. Do the trees have no Yin? 005 = Li Bai: at the bottom of the Nanshan Mountains, the people who stayed in the mountains and stayed in the mountains, and the mountains and months went with others. She joined Tian Jia, and Tong zhikai. The green bamboo enters the path, and the green radish is flushed. Happy words have to rest, wine chat swing. Song Wu hexing thin. I was drunk and lost.
For example, I have written such a fixed format and written their column name (on a regular expression !)
Right-click the book table, select the import wizard, and set the separator to = in step 3.
If it succeeds, we will find that all the columns are set, so that we can import them successfully.
Let's look at the data in our book table, so that we can use it normally:
Let's save it and put it in the raw folder under res of our project.
3. Modify the main function to complete the function:
1 package com. lfk. poem; 2 3 import android. content. context; 4 import android. database. cursor; 5 import android. database. sqlite. SQLiteDatabase; 6 import android. OS. bundle; 7 import android. OS. environment; 8 import android. support. v7.app. actionBarActivity; 9 import android. util. log; 10 import android. view. view; 11 import android. widget. button; 12 import android. widget. textView; 13 14 import java. io. file; 15 import java. io. fileNotFoundException; 16 import java. io. fileOutputStream; 17 import java. io. IOException; 18 import java. io. inputStream; 19 20 21 public class MainActivity extends ActionBarActivity {22 private final int BUFFER_SIZE = 400000; 23 public static final String DB_NAME = "poem. db "; // The Name Of The saved database file 24 public static final String PACKAGE_NAME =" com. lfk. poem "; // application package name 25 public static final String DB_PATH = "/data" 26 + Environment. getDataDirectory (). getAbsolutePath () + "/" // some parameters are defined here, including the file size, package name, database name, and database storage location 27 + PACKAGE_NAME + "/databases "; // location where the database is stored on the mobile phone 28 private Context mcontext; 29 @ Override30 protected void onCreate (Bundle savedInstanceState) {31 super. onCreate (savedInstanceState); 32 setContentView (R. layout. activity_main); 33 // dBhelper = new DBhelper (this, "poem. db ", null, 1); 34 SQLiteData Base database = openDatabase (); 35 Cursor cursor = database. query ("book", null, null); // This part is what I want to print everything into the log, you can delete 36 if (cursor. moveToFirst () {37 do {38 String id = cursor. getString (cursor. getColumnIndex ("id"); 39 String poem = cursor. getString (cursor. getColumnIndex ("poem"); 40 Log. e ("id =" + id, "poem =" + poem); 41} while (cursor. moveToNext (); 42} 43 cursor. close (); 44 database. close (); 45 Button button = (Button) findViewById (R. id. create_it); 46 button. setOnClickListener (new View. onClickListener () {47 @ Override48 public void onClick (View v) {49 int ll = (int) (1 + Math. random () * (5); 50 SQLiteDatabase database = openDatabase (); 51 Cursor cursor = database. rawQuery ("Select * From book Where id =" + ll, null); // modify the Button, set a random number 1-5, and open the database, then, use the SQL statement to find 52 cursor from the book. moveToFirst ();// And id = random amount, and then the first data is taken out. 0 is the id, which is set to 53 String poem = cursor in a textview. getString (1); 54 Log. e (poem, "===================="); 55 TextView textView = (TextView) findViewById (R. id. text_view); 56 textView. setText (poem); 57 cursor. close (); database. close (); 58} 59}); 60} 61 public SQLiteDatabase openDatabase () {62 try {63 File myDataPath = new File (DB_PATH); 64 if (! MyDataPath. exists () 65 {66 myDataPath. mkdirs (); // if this directory is not available, create 67} 68 String dbfile = myDataPath + "/" + DB_NAME; 69 if (! (New File (dbfile ). exists () {// determines whether the database file exists. If it does not exist, execute import. Otherwise, open the database directly. // This function is used to open the database. If there is no database, 70 InputStream is; 71 is = this. getResources (). openRawResource (R. raw. poem); // the database to be imported 72 FileOutputStream fos = new FileOutputStream (dbfile); 73 byte [] buffer = new byte [BUFFER_SIZE]; 74 int count = 0; 75 while (count = is. read (buffer)> 0) {76 fos. write (buffer, 0, count); 77} 78 fos. close (); 79 is. close (); 80} 81 SQLiteDatabase db = SQLiteDatabase. openOrCreateDatabase (dbfile, null); 82 Log. e ("=============================== ", "get it =================="); 83 return db; 84} catch (FileNotFoundException e) {85 Log. e ("Database", "File not found"); 86 e. printStackTrace (); 87} catch (IOException e) {88 Log. e ("Database", "IO exception"); 89 e. printStackTrace (); 90} 91 return null; 92} 93}
In this way, we can display the data obtained from the database on the interface. By now, the preliminary function is complete.
There may be another blog post, and the next step is to make some interface modifications. After all, this picture is still too ugly!
Like, please click like, = _ =!