Android project notepad (11) ----- Add a database
Through the previous 10 sections, you have implemented most of the functions of notepad, including adding photos, adding photos, recording, drawing, and handwriting. You can also find out carefully, there is another option in the bottom menu, which will be implemented later and used to expand the notepad function.
In this section, we will add database support for our notepad. In this way, we can save the notebook to the database after it is added, so that we can easily browse, modify, delete it next time.
First look:
The three pictures respectively demonstrate how to save, view, and delete Notes.
For databases, it is nothing more than about creating databases, adding, deleting, modifying, and querying databases.
To encapsulate database operations, a separate class is written as follows:
Database Operations
DatabaseOperation. java
Import android. content. context; import android. database. cursor; import android. database. sqlite. SQLiteDatabase; import android. widget. toast; public class DatabaseOperation {private SQLiteDatabase db; private Context context; public DatabaseOperation (Context context, SQLiteDatabase db) {this. db = db; this. context = context;} // open a database or create a public void create_db () {// create or open a database db = SQLiteDatabase. openOrCreateDatabase (context. getFilesDir (). toString () +/mynotes. db3, null); db.exe cSQL (drop table if exists studentScore); if (db = null) {Toast. makeText (context, database creation failed, Toast. LENGTH_LONG ). show ();} // Toast. makeText (context, database created successfully, Toast. LENGTH_LONG ). show (); // create the table db.exe cSQL (create table if not exists notes (_ id integer primary key autoincrement, + title text, + context text, + time varchar (20);} public void insert_db (String title, String text, String time) {if (text. isEmpty () {Toast. makeText (context, each field cannot be blank, Toast. LENGTH_LONG ). show ();} else {db.exe cSQL (insert into notes (title, context, time) values ('+ title +', '+ text + ', '+ time +'); // Toast. makeText (context, inserted successfully, Toast. LENGTH_LONG ). show () ;}} public void update_db (String title, String text, String time, int item_ID) {if (text. isEmpty () {Toast. makeText (context, each field cannot be blank, Toast. LENGTH_LONG ). show ();} else {// String SQL = update main set class1 = '+ class1 +', class2 = '+ class2 +', class3 = '+ class4 + ', class4 = '+ class4 + 'where days =' + days + '; db.exe cSQL (update notes set context =' + text + ', set title =' + title + ', set time = '+ time + 'where _ id =' + item_ID + '); // Toast. makeText (context, modified successfully, Toast. LENGTH_LONG ). show () ;}} public Cursor query_db () {Cursor cursor = db. rawQuery (select * from notes, null); return cursor;} public Cursor query_db (int item_ID) {Cursor cursor = db. rawQuery (select * from notes where _ id = '+ item_ID +';, null); return cursor;} public void delete_db (int item_ID) {db.exe cSQL (delete from notes where _ id = '+ item_ID +'); // Toast. makeText (context, deleted successfully, Toast. LENGTH_LONG ). show () ;}// close the public void close_db () {db. close ();}}With the related operations of these databases, we will start to implement the functions of saving, modifying, deleting, and querying records.
Save notes
When editing a notebook, click the Save button on the top to insert the notebook into the database. Of course, if there are pictures, recordings, and no pictures in the notebook, the recording itself is stored in the database, but its path is stored in the database. When you view it again, you can read it from the database and retrieve the source file based on the saved path.
The idea of saving the notebook is to extract the content in EditText, extract the first part of the notebook as the title, and save the time for adding the notebook.
The main code is:
// Get the content String context = et_Notes.getText (). toString (); if (context. isEmpty () {Toast. makeText (AddActivity. this, the record is blank !, Toast. LENGTH_LONG ). show ();} else {// get the current time SimpleDateFormat formatter = new SimpleDateFormat (yyyy-MM-dd HH: mm); Date curDate = new Date (System. currentTimeMillis (); // obtain the current time String time = formatter. format (curDate); // capture the first part of EditText as the title, which is used to display String title = getTitle (context) in the home page list; // open the database dop. create_db (); // determines whether to update or add a notebook if (editModel. equals (newAdd) {// Insert the notebook into the database dop. insert_db (title, context, time);} // update the notebook if it is edited. else if (editModel. equals (update) {dop. update_db (time, context, time, item_Id);} dop. close_db (); // ends the current activityAddActivity. this. finish ();}Specifically, the getTitle () function is used to capture the first 15 words of the notebook body as the title of the notebook. The editModel indicates whether to add or modify the notebook. GetTitle () is as follows:
// Intercept the first part of EditText as the title. It is used to display the private String getTitle (String context) in the homepage list {// define a regular expression to match the path Pattern p = Pattern. compile (/([^ \.] *)\. \ w {3}); Matcher m = p. matcher (context); StringBuffer strBuff = new StringBuffer (); String title =; int startIndex = 0; while (m. find () {// retrieve the text before the path if (m. start ()> 0) {strBuff. append (context. substring (startIndex, m. start ();} // retrieves the path String path = m. group (). toString (); // retrieves the path suffix String type = path. substring (path. length ()-3, path. length (); // judge the attachment type if (type. equals (amr) {strBuff. append ([recording]);} else {strBuff. append ([Image]);} startIndex = m. end (); // only extract the first 15 words as the title if (strBuff. length ()> 15) {// enter the carriage return and other special characters with spaces title = strBuff. toString (). replaceAll (|,); return title ;}} strBuff. append (context. substring (startIndex, context. length (); // enter the carriage return and other special characters with spaces title = strBuff. toString (). replaceAll (|,); return title ;}Here we mainly use regular expressions for matching common text or image recording. If it is an image recording, it is clear that the text of the image recording can be displayed in the title. Here we also use a technique, is the previous sentence of return, the purpose is to replace the carriage return and other special characters in the title with spaces.
Browsing (modifying) Notes
After saving the notes, You must retrieve them from the database and display them to the user in the original format. Imagine that after a notebook is added, you can return to the home page or go back to the home page to view the saved notebook list. Therefore, you should place a list (ListView) in the Activity of the home page) displays the data retrieved from the database. When you click a project in the list, you should view the details of the notebook.
Because a part has been taken as the title when saving the notebook, only the title, time, and details are displayed on the home page notebook list. The main code is as follows:
Private SQLiteDatabase db; private DatabaseOperation dop; private ListView lv_notes ;...... // database operation dop = new DatabaseOperation (this, db); lv_notes = (ListView) findViewById (R. id. lv_notes); // display the notebook list showNotesList (); // Add the listener lv_notes.setOnItemClickListener (new ItemClickEvent () to the notebook list ());
Among them, showNotesList () is used to clearly remember the list, as follows:
// Display the notebook list private void showNotesList () {// create or open the database dop. create_db (); Cursor cursor = dop. query_db (); SimpleCursorAdapter adapter = new SimpleCursorAdapter (this, R. layout. note_item, cursor, new String [] {_ id, title, time}, new int [] {R. id. TV _note_id, R. id. TV _note_title, R. id. TV _note_time}); lv_notes.setAdapter (adapter); dop. close_db ();}
The preceding function only allows you to browse the notebook list. By clicking a list item, you can view or modify the details of the notebook. Therefore, you can add a click event to the list, in the listener, you can read the corresponding notes from the database and display them as follows:
// In the notebook list, click the listener class ItemClickEvent implements OnItemClickListener {@ Overridepublic void onItemClick (AdapterView
Parent, View view, int position, long id) {TV _note_id = (TextView) view. findViewById (R. id. TV _note_id); int item_id = Integer. parseInt (TV _note_id.getText (). toString (); Intent intent = new Intent (MainActivity. this, AddActivity. class); intent. putExtra (editModel, update); intent. putExtra (noteId, item_id); startActivity (intent );}}In this way, when you click a list item, a new activity is opened to display the details of the notebook. Here, a new notebook Activity is still used, the advantage of doing so is that you can modify the notebook while viewing the notebook. This is also the method used by most Notebook software, and some information can be passed to AddActivity through intent, here, editModel is the editing mode. Because it is viewed or modified here, when you click Save again, you can update the original notebook, instead of adding another notebook; noteId is used to let AddActivity know the data in the database to be read. Correspondingly, add the code in AddActivity to retrieve the data and display it. The main code is as follows:
// Load data private void loadData () {// if the recording mode is added, the editText is cleared if (editModel. equals (newAdd) {et_Notes.setText () ;}// if an existing notebook is edited, the stored data of the database is taken out, else if (editModel. equals (update) {TV _title.setText (edit note); dop. create_db (); Cursor cursor = dop. query_db (item_Id); cursor. moveToFirst (); // retrieves the corresponding field content in the database String context = cursor. getString (cursor. getColumnIndex (context); // defines a regular expression to match the path Pattern p = Pattern. compile (/([^ \.] *)\. \ w {3}); Matcher m = p. matcher (context); int startIndex = 0; while (m. find () {// retrieve the text before the path if (m. start ()> 0) {et_Notes.append (context. substring (startIndex, m. start ();} SpannableString ss = new SpannableString (m. group (). toString (); // retrieves the path String path = m. group (). toString (); // retrieves the path suffix String type = path. substring (path. length ()-3, path. length (); Bitmap bm = null; Bitmap rbm = null; // determine the attachment type. if it is a recording file, the image if (type. equals (amr) {bm = BitmapFactory. decodeResource (getResources (), R. drawable. record_icon); // scaled image rbm = resize (bm, 200);} else {// retrieve image bm = BitmapFactory. decodeFile (m. group (); // zoom in the image rbm = resize (bm, 480);} // Add the border effect rbm = getBitmapHuaSeBianKuang (rbm) for the image; System. out. println (rbm. getWidth () + ------- + rbm. getHeight (); ImageSpan span = new ImageSpan (this, rbm); ss. setSpan (span, 0, m. end ()-m. start (), Spannable. SPAN_EXCLUSIVE_EXCLUSIVE); et_Notes.append (ss); startIndex = m. end () ;}// add the text after the last image to the TextView et_Notes.append (context. substring (startIndex, context. length (); dop. close_db ();}}Here, we also use regular expressions because we need to identify the path. This method can be called every time AddActivity is opened. This method can be used to add or modify a notebook.
Delete Notes
The implementation of Delete Notes is still implemented in the home Activity. When a long-pressed list item is displayed, two items are displayed, one is edit and the other is Delete, the editing function is the same as the function of clicking the items in the list. It is mainly used to delete the items. When the items are deleted, the corresponding items are deleted from the database and the list is refreshed. The main code is as follows:
...... // Add a long-press event lv_notes.setOnItemLongClickListener (new ItemLongClickEvent () for the notebook list ());...... // record list long by listener class ItemLongClickEvent implements OnItemLongClickListener {@ Overridepublic boolean onItemLongClick (AdapterView
Parent, View view, int position, long id) {TV _note_id = (TextView) view. findViewById (R. id. TV _note_id); int item_id = Integer. parseInt (TV _note_id.getText (). toString (); simpleList (item_id); return true ;}// simple List dialog box, used to select the public void simpleList (final int item_id) {AlertDialog. builder alertDialogBuilder = new AlertDialog. builder (this, R. style. custom_dialog); alertDialogBuilder. setTitle (select operation); alertDialogBuilder. setIcon (R. drawable. ic_launcher); alertDialogBuilder. setItems (R. array. itemOperation, new android. content. dialogInterface. onClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {switch (which) {// edit case 0: Intent intent = new Intent (MainActivity. this, AddActivity. class); intent. putExtra (editModel, update); intent. putExtra (noteId, item_id); startActivity (intent); break; // Delete case 1: dop. create_db (); dop. delete_db (item_id); dop. close_db (); // refresh the list to display lv_notes.invalidate (); showNotesList (); break ;}}); alertDialogBuilder. create (); alertDialogBuilder. show ();}
The above functions have been implemented to save, modify, and delete NOTES. At this point, the notepad functions have been basically completed, and the rest is the subsequent improvements and optimizations, as well as new features.