Notepad for Android project (one)-----Add database

Source: Internet
Author: User

This article is your own study notes, welcome reprint, but please indicate the source:http://blog.csdn.net/jesson20121020

through the previous 10 section, has realized most of the Notepad functions, there are added to take photos, add pictures, add audio, add drawings, add handwriting, in addition to careful to find, the bottom menu has a more options, this later implementation, to expand the function of Notepad.

This section is to add database support for our Notepad, so that you can add a note after it is saved in the database, easy to browse, modify, delete and so on.

Look first:

Three images show how to save notes, see notes, and delete notes.

For the database, nothing is related to the creation of databases, additions and deletions to check.

In order to encapsulate the operation of the database, a separate class was 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;}//Database open or create public void CRE ate_db () {//Create or Open database db = Sqlitedatabase.openorcreatedatabase (Context.getfilesdir (). toString () + "/MYNOTES.DB3", null    );      Db.execsql ("DROP TABLE IF EXISTS studentscore");    if (db = = null) {Toast.maketext (context, "Database creation unsuccessful", Toast.length_long). Show ();        }//toast.maketext (Context, "Database creation succeeded", Toast.length_long). Show (); CREATE TABLE Db.execsql ("CREATE table if not exists notes (_id Integer primary key autoincrement," + "title text," + "con        Text text, "+" time varchar (20)); } public void insert_db (String title,string text,string time) {if (Text.isempty ()) {Toast.maketext (context , "each field cannot be empty", toast.length_long). Show ();        } else{Db.execsql ("INSERT into notes (Title,context,time) VALUES ('" + title+ "', '" + text+ "', '" +time+ "');");    Toast.maketext (Context, "Insert succeeded", Toast.length_long). Show (); }} public void update_db (String title,string text,string time,int item_id) {if (Text.isempty ()) {toast.ma    Ketext (Context, "each field cannot be empty", Toast.length_long). Show (); } else{//string sql = "Update main set class1= '" + Class1 + "', class2= '" + Class2 + "', class3= '" + class4 + "', Clas    s4= ' "+ class4 +" ' where days= ' "+ Days +" '; ";        Db.execsql ("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+ "';", Nu    ll); REturn cursor;    } public void delete_db (int item_id) {db.execsql ("Delete from Notes where _id= '" + item_id+ "'");    Toast.maketext (context, "Delete succeeded", Toast.length_long). Show ();    }//Close database public void close_db () {db.close (); }}
With these database related operations, the following start to implement save notes, change notes, delete notes, query the function of notes.

Save Notes

When editing good one note, then click on the top of the Save button, will be written notes inserted into the database, of course, if the note has pictures, recordings, etc., and no picture, the recording itself is stored in the database, but the location of the path stored in the database, wait until re-view, then read from the database, and extracts the source file according to the saved path.

the idea of saving a note is to take out the contents of the EditText and capture the previous part as the title of the note, as well as to save the time to add notes.

The main code is:

        Gets the contents of the EditText string context = Et_notes.gettext (). toString (); if (Context.isempty ()) {Toast.maketext ( Addactivity.this, "Memo is empty!", Toast.length_long). Show (); else{//get current time SimpleDateFormat   formatter   =   new   simpledateformat   ("Yyyy-mm-dd hh:mm");  Date   curdate   =   new   date (System.currenttimemillis ());//Gets the current time of String times   =   Formatter.format (curdate);//intercepts the previous part of the EditText as a caption for display in the Home page list in string title = GetTitle (context);//Open Database dop.create_db ( );//Determine whether to update or add a note if (Editmodel.equals ("Newadd")) {//Insert notes into the database dop.insert_db (title,context,time);} If it is an edit, update the note to else if (editmodel.equals ("Update")) {dop.update_db (time,context,time,item_id);} dop.close_db ();//End current activityAddActivity.this.finish ();}
Among them, the GetTitle () function is to intercept the first 15 words of the note text as the title of the note, Editmodel that the current is a new note or change notes. GetTitle () is as follows:

       //intercepts the previous part of EditText as a caption for display in the home page list in private string GetTitle (string context) {   // Defines a regular expression that is used 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 ()) {//Remove the path before the text if (M.start () > 0) {strbuff.append (context.substring (StartIndex, M.start ()));    }//Take out the path, String path = M.group (). toString ();    Remove the suffix of the path String type = path.substring (Path.length ()-3, Path.length ());    Determine the type of attachment if (Type.equals ("AMR")) {strbuff.append ("[recording]");    } else{strbuff.append ("[Image]");        } StartIndex = M.end (); Only remove the first 15 words as the title if (Strbuff.length () > 15) {//Unity will enter, and so on special characters replaced by a space title = Strbuff.tostring (). ReplaceAll (        "\r|\n|\t", "" ");        return title;    }} strbuff.append (Context.substring (StartIndex, Context.length ())); Unification will enter, and so on special characters change to space title = Strbuff.tostriNg (). ReplaceAll ("\r|\n|\t", ""); return title;}
Here is the main use of regular expression, used to match is the ordinary text or picture recording, if it is a picture recording, it is obvious in the title picture recording text can, here also used a technique, is the return of the previous sentence, the purpose is to the title of the carriage return and other special characters into a space.

browse (Edit) Notes

After saving the note, of course, it will be removed from the database and displayed in the original format to the user. Imagine that when you add a note, go back to the home page, or re-enter the page, you should see a list of currently saved notes, so a list (ListView) should be placed in the activity of the home page to display the data fetched from the database. When you click on a list of items, you should open the details to see the note.

Because a part of the title is already captured when you save a note, only the title, time, and not the obvious details are displayed on the page's list of notes. The main code:

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);//Show List of Notes shownoteslist ();// Add Listener Lv_notes.setonitemclicklistener (new Itemclickevent ()) to the Notes list;

Among them, Shownoteslist () is used for the obvious list of notes, as follows:

    Show Memo list    private void Shownoteslist () {    //Create or Open 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 above only to browse the function of the list of notes, then click on the list item, it is natural to view or modify the details of the note, so add a click event for the list, and in its listener implementation from the database read the corresponding note content, and display, as follows:

Memo List click 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);}    }
This way, when you click on a list item, a new activity is opened to show the details of the note, which is still used to add a new note activity, which is the advantage of checking the notes, but also can be modified, which is the method used by most of the Notes software, and, can also pass intent some information to addactivity, wherein Editmodel is the editing mode, because here is the view or modify, so when you click on the save again, update the original note can, not add a note ; Noteid is to let addactivity know that the data in the database should be read. Accordingly, in the addactivity to add code to take out the data and display, the main code is as follows:

       //Load Data private void LoadData () {//If it is new note mode, the EditText will be emptied if (editmodel.equals ("Newadd") {et_ Notes.settext ("");} If you edit a note that already exists, the saved data for the database is taken out and displayed in EditText, else if (editmodel.equals ("Update")) {Tv_title.settext ("edit Notes"); dop.create_db (); cursor cursor = dop.query_db (item_id), Cursor.movetofirst ();//Remove the corresponding field contents of the database in string context = Cursor.getstring ( Cursor.getcolumnindex ("context"));//define regular expressions to match path Pattern p=pattern.compile ("/([^\\.]     *) \\.\\w{3} ");    Matcher M=p.matcher (context);    int startIndex = 0;    while (M.find ()) {//Remove the path before the text if (M.start () > 0) {et_notes.append (context.substring (StartIndex, M.start ()));                } spannablestring SS = new spannablestring (M.group (). toString ());    Take out the path, String path = M.group (). toString ();    Remove the suffix of the path String type = path.substring (Path.length ()-3, Path.length ());    Bitmap BM = NULL;    Bitmap RBM = null; Determine the type of attachment, if it is a recording file, load the picture from the resource file if (Type.equals ("AMR")) {BM = Bitmapfactory.decoderesoUrce (Getresources (), R.drawable.record_icon);    Scaled Picture RBM = resize (bm,200);        } else{//Take out picture BM = Bitmapfactory.decodefile (M.group ());    Scaled Picture RBM = resize (bm,480);        }//Add border effect to the picture RBM = Getbitmaphuasebiankuang (RBM);        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 picture in TextView et_notes.append (context.substring (Startindex,context.length ()));d op.close_db ();}}
A regular expression is also used here, because the path is to be identified. With this method, the method is called each time the addactivity is opened, which can be used for new notes or for modifying notes.

Delete Notes

Delete the implementation of the note or in the main page activity, when long press the list item, pop-up action selection, a total of two, one is the editor, one is deleted , here the editor is and click on the list item's view note function, mainly delete, when the deletion is selected, Delete the corresponding memo entry from the database and refresh the list. The main code is as follows:

...//Add a long press event Lv_notes.setonitemlongclicklistener (new Itemlongclickevent ()) to the Notes list;//note list Long press 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 for selecting Operations public void SimpleList (final int item_id) {Alertdialog.builder Alertdialogbuilder = new alertdial og. 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:d op.create_db ();d op.delete_db (item_id);d op.close_db ();// Refresh list shows lv_notes.invalidate (); Shownoteslist (); break;}});     Alertdialogbuilder.create (); Alertdialogbuilder.show ();}

above, the realization of the record save, modify, delete the function, to this, the function of Notepad has been basically completed, the rest is the subsequent improvement and optimization, as well as new features.

Notepad for Android project (one)-----Add database

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.