Android 19th issue-SQLite offline storage teaches you to write Millet Notepad

Source: Internet
Author: User

This period said SQLite offline storage, the recent app to add offline file download function, oneself is also made a day, finally is small have the result, want to thank the strong support of the wife, help me test what, are hard-work, now can this to me such a good person only wife. Share code to everyone, look at some of the Notepad is very practical, so also reckoned to get a, UI design it, the function realized everything is to say. Start here:

First, SQLite can go to the official website http://www.sqlite.org/lang.html, to query all the operation, create tables, additions and deletions and so on.

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/4C/65/wKioL1Q8hzrRc6OcAASOz9FSWeA686.jpg "title=" 1.png " alt= "wkiol1q8hzrrc6ocaasoz9fswea686.jpg"/> 650) this.width=650; "Src=" http://s3.51cto.com/wyfs02/M00/4C/64/    Wkiom1q8h42dqwj1aagp9bo56ti104.jpg "title=" 2.png "alt=" Wkiom1q8h42dqwj1aagp9bo56ti104.jpg "/> And then you build a SQLite class that inherits to Sqliteopenhelper:

package com.liangxiao.usingsqlite;import android.content.context;import  Android.database.sqlite.sqlitedatabase;import android.database.sqlite.sqlitedatabase.cursorfactory;import  android.database.sqlite.sqliteopenhelper;public class db extends sqliteopenhelper  {public db (Context context, string name, cursorfactory factory, int  version)  {super (context,  "db",  null, 1);// todo auto-generated  Constructor stub} @Overridepublic  void oncreate (sqlitedatabase db)  {// TODO  Auto-generated method stub// db.execsql ("Create table user" (" + " name  Text default \ "\", "// + " sex text default \ "\") ");d B.execsql (" CREATE  Table user ("+" _id integer primary key autoincrement, "+ " name TEXT  Default \ "\", " + " Sex text&nbsP;default \ "\") ")// db.execsql (" Create table user (" + " name text  Default \ "\" ");} @Overridepublic  void onupgrade (sqlitedatabase db, int oldversion, int  newversion)  {// todo auto-generated method stub}}

Note: In this adapter I used the official bring the convenience of operation, so the need to reference the table _id, added a field.

And then I wrote to you two kinds of read interface, one is TextView read, and one is the ListView reading mode.

First say TextView, we can play the imagination to construct the UI, what the drop hover, scrollview and so on.

Code I have commented PS: Jump form to Mainactivity_dbread:

package com.liangxiao.usingsqlite;import android.app.activity;import android.database.cursor; import android.database.sqlite.sqlitedatabase;import android.os.bundle;import  Android.widget.textview;public class mainactivity_dbread extends activity {private  TextView xianshi; @Overrideprotected  void oncreate (bundle savedinstancestate)  { Super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main_dbread);xianshi =  (TextView )  findviewbyid (R.id.xianshi); read_db ();} /** *  Read db section  */private void read_db ()  {db db = new db (This,   "DB",  null, 1); Sqlitedatabase dbread = db.getreadabledatabase (); Cursor c = dbread.query ("User", null, null, null, null, null,  NULL);while  (C.movetonext ())  {string name = c.getstring (C.getcolumnindex ("name")); String&nbsP;sex = c.getstring (C.getcolumnindex ("Sex"));d b_lastindex_content +=  "Mood:"  +  name +  "  "  +  "party:"  + sex +  "\ n";} Xianshi.settext (Db_lastindex_content.tostring ());} private string db_lastindex_content =  "";}

Note: This textview you can display your operation on the current page, you can also jump to the operation, will be directly displayed in the main UI, no lag phenomenon, very smooth.

Main form mainactivity:

package com.liangxiao.usingsqlite;import android.app.activity;import  Android.content.contentvalues;import android.content.intent;import android.database.cursor;import  android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.view.View; import android.view.view.onclicklistener;import android.widget.button;import  Android.widget.edittext;import android.widget.textview;import android.widget.toast;public class  mainactivity extends activity implements onclicklistener {private button  btn_fly;private textview xianshi1;private edittext add_db_text;private edittext  add_db_text2;private Db db;private SQLiteDatabase dbRead, dbWrite;private  Cursor c;// private string add_db_text_string;// private string add_db_text _string2, @Overrideprotected  void oncreate (bundle savedinstancestate)  {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); init (); read_db ();} /** *  Initialize part  */private void init ()  {xianshi1 =  (TextView)   Findviewbyid (R.ID.XIANSHI1);btn_fly =  (Button)  findviewbyid (r.id.btn_fly); add_db_text =   (EditText)  findviewbyid (r.id.add_db_text);add_db_text2 =  (EditText)  findviewbyid ( R.ID.ADD_DB_TEXT2); Btn_fly.setonclicklistener (this);} /** *  Add Operation section  */private void add_db ()  {string add_db_text_string =  add_db_text.gettext (). toString (); String add_db_text_string2 = add_db_text2.gettext (). toString (); Toast.maketext (this, add_db_text_string +  ","  + add_db_text_string2, 2). Show (); Db = new db (this,  "Db",  null, 1);d bwrite = db.getwritabledatabase (); Contentvalues cv = new contentvalues (); Cv.put ("Name",  add_db_text_string); Cv.put ("Sex",  add_db_text_string2);d bwrite.insert ("user",  NULL, CV); Dbwrite.close ();} /** *  Read db part  */private void read_db ()  {db = new db (this,  "db ",  null, 1);d bread = db.getreadabledatabase (); C = dbread.query (" User ",  null ,  null, null, null, null, null);while  (C.movetonext ())  {String name  = c.getstring (C.getcolumnindex ("name")); String sex = c.getstring (C.getcolumnindex ("Sex")); System.out.println (String.Format ("name%s,sex%s",  name, sex));// xianshi1.settext ("Mood:"  +  name +  "  "  +  "party:"  + sex +  "\ n");d b_datebase +=   "Mood:"  + name +  "  "  +  "party:"  + sex +  "\ n";} Xianshi1.settext (Db_datebase.tostring ());} private string db_datebase =  "";p Rivate&nbsP;void refresh ()  {db = new db (this,  "db",  null, 1);d bread =  Db.getreadabledatabase (); C = dbread.query ("User", null, null, null, null,  Null, null);while  (C.movetonext ())  {string name = c.getstring (C.getColumnIndex (" Name ")); String sex = c.getstring (C.getcolumnindex ("Sex")); System.out.println (String.Format ("name%s,sex%s",  name, sex));// xianshi1.settext ("Mood:"  +  name +  "  "  +  "party:"  + sex +  "\ n");d b_datebase =   "Mood:"  + name +  "  "  +  "party:"  + sex +  "\ n";} String xinshi_text_lastindex = xianshi1.gettext (). toString (); Xianshi1.settext (Xinshi_text_ Lastindex+db_datebase.tostring ());} /** * click part  */@Overridepublic  void onclick (view v)  {add_db (); refresh ();//  intent inteNt = new intent ();// intent.setclass (mainactivity.this, mainactivity_dbread.class);//  mainactivity.this.startactivity (intent);// mainactivity.this.finish ();}}

Note In the onclick, the part of my comment is the action of the jump, which is currently the UI display action of the main form.

These two effects are as follows:

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M02/4C/65/wKiom1Q8lhjzhqmVAADFpVlO2Qk485.jpg "title=" 1.png " alt= "Wkiom1q8lhjzhqmvaadfpvlo2qk485.jpg"/>

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/4C/66/wKioL1Q8l9GAQGoVAADKV6sTv4E812.jpg "title=" si@a]w ]l5mokt3_st8k~xpl.jpg "alt=" Wkiol1q8l9gaqgovaadkv6stv4e812.jpg "/>


Then for the operation of the ListView, everyone is generally for this operation more, first of all is the main form mainactivity_listview_db:

package com.liangxiao.usingsqlite;import android.app.alertdialog;import  Android.app.listactivity;import android.content.contentvalues;import android.content.dialoginterface ;import android.content.intent;import android.database.cursor;import  Android.database.sqlite.sqlitedatabase;import android.os.bundle;import android.view.keyevent;import  android.view.View;import android.view.View.OnClickListener;import android.widget.AdapterView; import android.widget.adapterview.onitemclicklistener;import  android.widget.adapterview.onitemlongclicklistener;import android.widget.button;import  Android.widget.edittext;import android.widget.listview;import android.widget.relativelayout;import  android.widget.RelativeLayout.LayoutParams;import android.widget.SimpleCursorAdapter;import  android.widget.textview;import android.widget.toast;public class mainactivity_listview_db  Extends listactivity implementsonclicklistener {private listview list;private edittext  edit_name, edit_sex;private TextView tvname, tvsex;private Button btn; Private simplecursoradapter adapter;private db db;private sqlitedatabase dbread,  dbWrite;private Cursor c;private long firstime = 0;private  relativelayout mainlayout; @Overrideprotected  void oncreate (bundle savedinstancestate)  {// todo auto-generated method stubsuper.oncreate (savedInstanceState); SetContentView (R.layout.activity_main_listview); init ();d b_add_read (); Refreshlistview ();} Private void init ()  {btn =  (Button)  findviewbyid (R.ID.BTN);// list =   (ListView)  findviewbyid (r.id.list);edit_name =  (EditText)  findviewbyid (r.id.edit_ Name);edit_sex =  (EditText)  findviewbyid (r.id.edit_sex);Btn.setonclicklistener (this);} Private void db_add_read ()  {db = new db (this,  "db",  null, 1); Dbread = db.getreadabledatabase ();// c = dbread.query ("User",  null, null,  null, null, null, null);d bwrite = db.getwritabledatabase ();adapter =  New simplecursoradapter (this,r.layout.activity_main_listview_item, null, new string[]  {"name",  "Sex" &NBSP;},&NBSP;NEW&NBSP;INT[]&NBSP;{&NBSP;R.ID.TVNAME,&NBSP;R.ID.TVSEX&NBSP;});//  list.setadapter (adapter); Setlistadapter (adapter);//  Delete operation section Getlistview (). Setonitemlongclicklistener ( New onitemlongclicklistener ()  {@Overridepublic  boolean onitemlongclick (adapterview<? > parent, view view,final int position, long id)  {new  Alertdialog.builder (mainactivity_listview_db.this). Settitle ("Your Sister"). Setmessage ("Are you sure?"). SetnegativebUtton ("No",  null). Setpositivebutton ("delete", New dialoginterface.onclicklistener ()  {@ Overridepublic void onclick (DIALOGINTERFACE&NBSP;ARG0,INT&NBSP;ARG1)  {// TODO  Auto-generated method stubcursor c = adapter.getcursor (); c.moveToPosition (position); Int itemid = c.getint (C.getcolumnindex ("_id"));d bwrite.delete ("User",  "_id=?",new  string[] { itemid +  "" &NBSP;}); Refreshlistview ();}}). Show (); return true;}); /  Modify Part Getlistview (). Setonitemclicklistener (New onitemclicklistener ()  {@Overridepublic  void  onitemclick (Adapterview<?> parent, view view,int position, long id)  {cursor c = adapter.getcursor (); c.movetoposition (position);int itemid =  C.getint (C.getcolumnindex ("_id")); Intent intent = new intent (); Intent.putextra ("ItemId",  itemId +  ""); Intent.setclass(Mainactivity_listview_db.this,mainactivity_listview_db_detail.class); MainActivity_ListView_db.this.startActivity (Intent); MainActivity_ListView_db.this.finish ();}});} Private void refreshlistview ()  {c = dbread.query ("User", null, null,  Null, null, null, null); Adapter.changecursor (c);} @Overridepublic  void onclick (view v)  {// TODO Auto-generated method  stubif  (V&NBSP;==&NBSP;BTN)  {contentvalues cv = new contentvalues (); Cv.put ("Name ",  edit_name.gettext (). ToString ()); Cv.put (" Sex ",  edit_sex.gettext (). ToString ());d Bwrite.insert (" User ", &NBSP;NULL,&NBSP;CV); Refreshlistview (); Edit_name.gettext (). Clear (); Edit_sex.gettext (). Clear ();}} @Overridepublic  boolean onkeydown (int keycode, keyevent event)  {if  (keycode  == keyevent.keycode_back && event.getrepeatcount ()  == 0)  {//  Relativelayout.layoutparams lp =  (Layoutparams)  mainlayout// .getlayoutparams (); long secondtime  = system.currenttimemillis ();if  (secondtime - firstime > 3000)  { Toast.maketext (mainactivity_listview_db.this,  "Press the return key again to exit", Toast.length_short). Show (); firstime =  system.currenttimemillis (); return true;}  else {mainactivity_listview_db.this.finish (); System.exit (0); Android.os.Process.killProcess (Android.os.Process.myPid ());}} Return super.onkeydown (keycode, event);}}

     then edit mainactivity_listview_db_detail:

package com.liangxiao.usingsqlite;import android.app.activity;import  Android.content.contentvalues;import android.content.intent;import android.database.cursor;import  android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.view.KeyEvent; Import android.view.view;import android.widget.button;import android.widget.edittext;import  android.widget.toast;public class mainactivity_listview_db_detail extends activity  {private EditText name, sex;private Button btn_update;private  Sqlitedatabase dbread, dbwrite;private string itemid;private cursor c;private  Db db; @Overrideprotected  void oncreate (bundle savedinstancestate)  {// todo  auto-generated method stubsuper.oncreate (savedinstancestate); Setcontentview (R.layout.activity_ Main_listview_detail); init (); intent intent = gEtintent (); Itemid = intent.getstringextra ("itemId"); C = dbread.query ("User",  null,   "_id=",  new string[] { itemid }, null,null, null);// String  name1 = c.getstring (C.getcolumnname (1));if  (C.movetofirst ())  {string name1  = c.getstring (C.getcolumnindex ("name")); String sex1 = c.getstring (C.getcolumnindex ("Sex")); Name.settext (name1); Sex.settext (SEX1);} C.close ();} Private void init ()  {db = new db (this,  "db",  null, 1);d bread  = db.getreadabledatabase ();d bwrite = db.getwritabledatabase ();name =  (EditText)  findviewbyid (R.id.name);sex =  (EditText)  findviewbyid (r.id.sex);btn_update =  ( Button)  findviewbyid (r.id.btn_update); Btn_update.setonclicklistener (New view.onclicklistener ()   {@Overridepublic  void onclick (view arg0)  {ContentValues Cv = new contentvalues (); Cv.put ("Name",  name.gettext (). toString ()); Cv.put ("Sex",  Sex.gettext (). toString ());// dbwrite.insert ("User", &NBSP;NULL,&NBSP;CV);d bwrite.update ("User", &NBSP;CV,   "_id=",  new string[] { itemid });intent intent = new  Intent (Mainactivity_listview_db_detail.this,mainactivity_listview_db.class); MainActivity_ListView_db_detail.this.startActivity (Intent); MainActivity_ListView_db_detail.this.finish ();}});} @Overridepublic  boolean onkeydown (int keycode, keyevent event)  {if  (keycode  == keyevent.keycode_back && event.getrepeatcount ()  == 0)  {Intent  intent = new intent (Mainactivity_listview_db_detail.this,mainactivity_listview_db.class); MainActivity_ListView_db_detail.this.startActivity (Intent); MainActivity_ListView_db_detail.this.finish ();} Return super.onkeydown (keycode, event);}}

Note: There are two actions to edit the details, one row of records for the ID of the ListView in which the query is located, and an update operation. The main form is the read and add operation. Code inside are written more detailed, see for yourself, PS: This inside has 2 small operation, one is Listeview item click, one is long press, oneself try it, effect such as:

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M00/4C/65/wKiom1Q8mBTA6mTnAADKsTbzCVQ956.jpg "style=" float: none; "title=" Screenshot_2014-10-14-11-26-14.png "alt=" Wkiom1q8mbta6mtnaadkstbzcvq956.jpg "/>

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/4C/66/wKioL1Q8mEuSiDWbAADUlnCJF3w913.jpg "style=" float: none; "title=" Screenshot_2014-10-14-11-26-18.png "alt=" Wkiol1q8meusidwbaadulncjf3w913.jpg "/>

650) this.width=650; "src=" http://s3.51cto.com/wyfs02/M01/4C/65/wKiom1Q8mBTB4LjxAADJYs8ujH0324.jpg "style=" float: none; "title=" Screenshot_2014-10-14-11-26-30.png "alt=" Wkiom1q8mbtb4ljxaadjys8ujh0324.jpg "/>

Love the wife, love life, love it ...

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/4C/66/wKioL1Q8mHTDBiDSABArQlKWAEA370.jpg "title=" Lnhhjghh.jpg "alt=" Wkiol1q8mhtdbidsabarqlkwaea370.jpg "/>


This article is from the "Liangxiao Technology Center" blog, please be sure to keep this source http://liangxiao.blog.51cto.com/3626612/1563815

Android 19th issue-SQLite offline storage teaches you to write Millet Notepad

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.