Android Learning-----How to use SQLite for background data exchange, SQLite get started with routines

Source: Internet
Author: User
Tags sqlite database



SQLite This is a very popular embedded database. It supports SQL queries, and only uses very little memory. Android is implemented in integration with SQLite, so each Android application is able to use the SQLite database. When you are familiar with SQL developers. Using SQLite is fairly straightforward.

Can. Because JDBC is not suitable for memory-constrained devices such as mobile phones. So Android developers need to learn new APIs to use SQLite. This article introduces you to the introduction of SQLite using a register login demo.

Let's go first. Execution Result: (Please ignore ugly interface ~ ~)

The following is the main code, followed by analysis:

/** * Login Page activity * @author D_xiao * */public class Mainactivity extends activity {sqlitedatabase db; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); Button loginbtn = (button) Findviewbyid (R.ID.LOGINBTN); Button regbtn = (button) Findviewbyid (r.id.regbtn);d B = Sqlitedatabase.openorcreatedatabase (This.getfilesdir (). ToString () + "/ANDROID1.DB3", null); Create or Open database Loginbtn.setonclicklistener (new Onclicklistener () {public void OnClick (View sourse) {Boolean flag = false; String UserName = ((EditText) Findviewbyid (R.id.useredittext)). GetText (). toString (); String UserPassword = ((EditText) Findviewbyid (R.id.passwordedittext)). GetText (). toString (); Try{cursor Cursor = Db.rawquery ("SELECT * from users where name =?") and password =? ", new String[]{username,userpassword}); if (Cursor.getcount () ==0) {Intent intente = new Intent ( Mainactivity.this,erroractivity.class); startactivity (Intente);} Else{intent IntentS = new Intent (MaiNactivity.this,homeactivity.class); Intents.putextra ("name", UserName); startactivity (IntentS);}} catch (Sqliteexception se) {Intent intente = new Intent (mainactivity.this,erroractivity.class); StartActivity (Intente) ;}}}); Regbtn.setonclicklistener (New Onclicklistener () {public void OnClick (View sourse) {Intent Intentreg = new Intent ( Mainactivity.this,regactivity.class); startactivity (Intentreg);});} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}
/** * Register Activity * @author D_xiao * */public class Regactivity extends activity {sqlitedatabase db; ListView ListView; Button btn;protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_reg);d B = Sqlitedatabase.openorcreatedatabase (This.getfilesdir (). toString () + "/ANDROID1.DB3", NULL); final String a = This.getfilesdir (). toString (); Button Regok = (button) Findviewbyid (R.id.regok); Button Backtologin = (button) Findviewbyid (R.id.backtologin); Regok.setonclicklistener (new Onclicklistener () {public void OnClick (View sourse) {String name = ((EditText) Findviewbyid (R.id.name)). GetText (). toString (); String Password = ((EditText) Findviewbyid (R.id.password)). GetText (). toString (); TextView suc = (TextView) Findviewbyid (R.ID.SUC); Try{db.execsql (insert into users values (NULL,?

,?) ", New String[]{name,password}); Suc.settext (" The register succeeds. Please click the Cancel button to return to the login screen "); catch (Sqliteexception se) {db.execsql ("CREATE TABLE" users (_id integer primary key autoincrement, "+" name varchar (20), "+" Password varchar);d b.execsql ("INSERT into users values (null,?,?)", New String[]{name,password}), Suc.settext (" Registration is successful. Please click the Cancel button to return to the login screen ");}}); Backtologin.setonclicklistener (New Onclicklistener () {public void OnClick (View sourse) {Intent Intent = new Intent ( Regactivity.this,mainactivity.class); startactivity (intent);});} public void OnDestroy () {Super.ondestroy (); if (Db!=null&&db.isopen ()) {db.close ();}} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}


/** * Login Successful display homepage, be able to tweet and display the Circle of friends * @author D_xiao * */public class Homeactivity extends Activity {sqlitedatabase db; ListView ListView; Button btn;protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_home);d B = Sqlitedatabase.openorcreatedatabase (This.getfilesdir (). toString () + "/ANDROID1.DB3", NULL), ListView = (ListView) Findviewbyid (r.id.show), btn = (Button) Findviewbyid (r.id.send); Btn.setonclicklistener ( New Onclicklistener () {cursor cursor = Null;public void OnClick (View sourse) {String Weibo = ((EditText) Findviewbyid ( R.id.newtext). GetText (). toString (); Intent Intent = Getintent (); String name = Intent.getstringextra ("name"); Try{insertdata (Db,name,weibo);//select * from weibo3cursor = Db.rawquery (" SELECT * from Weiboa ", null); inflatelist (cursor);} catch (Sqliteexception se) {//primary key autoincrementdb.execsql ("CREATE Table Weiboa (_id integer PRIMARY key AutoIncrement, "+" name varchar (+), "+" Weibo varchar "); InsertData (Db,namE,weibo);//Query cursor = db.rawquery ("SELECT * from Weiboa", null); inflatelist (cursor);} Finally{//cursor.close ();}});} private void InsertData (Sqlitedatabase db,string name,string Weibo) {//Run INSERT statement db.execsql ("INSERT into WEIBOA values (null ,?,?) ", New String[]{name,weibo}); private void Inflatelist (cursor cursor) {//fill Simplecursoradaptersimplecursoradapter adapter = new Simplecursoradapter ( Homeactivity.this,r.layout.line,cursor,new string[]{"Name", "Weibo"},new Int[]{r.id.my_name,r.id.my_weibo}, Cursoradapter.flag_register_content_observer); Listview.setadapter (adapter);} public void OnDestroy () {Super.ondestroy (); if (Db!=null&&db.isopen ()) {db.close ();}} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}


/** * Username or password error jump * @author D_xiao * */public class Erroractivity extends Activity {@Overrideprotected void oncr Eate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_error); Button backbtn = (button) Findviewbyid (R.ID.EBACKBTN); Backbtn.setonclicklistener (new Onclicklistener () {public void OnClick (View sourse) {Intent intentback = new Intent (erroractivity.this,mainactivity.class); StartActivity (Intentback );}});} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}


With this example, you can see the difference between SQLite and SQL Server databases:

SQLite does not have a graphical interface, and no matter what the configuration of the installation of open connections, and so on, a few simple sentences can be finished adding or removing changes to check operation. It is also very convenient to use. and SQLite and SQL Server, MySQL is very much similar to the place. In addition to most query statements in SQLite can be used outside, SQLite also has its own API provides methods to query, this later. And the running statements are very similar.

For example db = Sqlitedatabase.openorcreatedatabase (This.getfilesdir (). toString () + "/ANDROID1.DB3", null); This is equivalent to establishing a connection in SQL Server, so closing the connection after use is the same.

cursor cursor = db.rawquery ("SELECT * from users where name =?") and password =? ", new String[]{username,userpassword}); the cursor in this sentence corresponds to a resultset in SQL Server.

There is no graphical interface is a bit more troublesome, is not good operation to view the data table, it is necessary to perform a CMD view, relatively troublesome. Take a look at the next blog post: http://blog.csdn.net/frightingforambition/article/details/24439981

Full Demo:

http://download.csdn.net/detail/u011250851/7248227





Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

Android Learning-----How to use SQLite for background data exchange, SQLite get started with routines

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.