anroid--Database Sqlite--sqliteopenhelper+sqlitedatabase

Source: Internet
Author: User
Tags gettext sqlite

1.SQLite Lightweight . DP files are used in mobile phones

Lightweight, embedded relational data model.

Sqliteopenhelper

Responsible for creating open updates close database

Create a data table

Sqlitedatabase

Execute SQL statement

Increase the data table. By deleting. Change. Check.




<span style= "FONT-SIZE:18PX;" >package com.example.jreduch08.sqlitedemo.entity;/** * Created by the peak of the cupola on 2016/8/22.    */public class User {private int UserId;    private String name;    Private String pwd;    Private String age;    Private String img;    Public String GetName () {return name;    } public void SetName (String name) {this.name = name;    } public int getUserId () {return UserId;    } public void Setuserid (int userid) {userid = userid;    } public String Getpwd () {return pwd;    } public void SetPwd (String pwd) {this.pwd = pwd;    } public String Getage () {return age;    public void Setage (String age) {this.age = age;  } @Override Public String toString () {return "user{" + "userid=" + UserId + ",  Name= ' + name + ' \ ' + ', pwd= ' + pwd + ' \ ' + ', age= ' + age + ' + ', Img= ' " + img + ' \ ' + '} ';    } public String getimg () {return img;    } public void Setimg (String img) {this.img = img; }}</span>
<span style= "FONT-SIZE:18PX;" >package Com.example.jreduch08.sqlitedemo.entity;import Android.content.contentvalues;import Android.content.context;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Com.example.jreduch08.sqlitedemo.mydbhelper;import java.util.arraylist;import java.util.List;/** * Created by the peak of the cupola on 2016/8/22.    */public class Userdao {private Mydbhelper mydbhelper;    Public Userdao (Context context) {Mydbhelper =new mydbhelper (context);        }//Insert data public void Insert (user user) {sqlitedatabase db= mydbhelper.getwritabledatabase ();        Contentvalues cv=new contentvalues ();        Cv.put ("Name", User.getname ());        Cv.put ("pwd", user.getpwd ());        Cv.put ("Age", User.getage ());        Cv.put ("img", User.getimg ());        Db.insert ("info", NULL,CV);    Db.close ();        }//Query a data public User Searchuser (String id) {sqlitedatabase db=mydbhelper.getreadabledatabase (); Cursor cs= Db.query ("Info ", NULL," _id=?        ", new String[]{id},null,null,null);        User User=null;            if (Cs.movetonext ()) {user=new user ();            User.setuserid (Cs.getint (Cs.getcolumnindex ("_id"));            User.setname (Cs.getstring (Cs.getcolumnindex ("name"));            User.setpwd (Cs.getstring (Cs.getcolumnindex ("pwd"));            User.setage (Cs.getstring (Cs.getcolumnindex ("Age"));        User.setimg (Cs.getstring (Cs.getcolumnindex ("img"));        } cs.close ();        Db.close ();    return user;        }//Query all data public List search () {sqlitedatabase db=mydbhelper.getreadabledatabase ();        Cursor cs= db.query ("info", null,null,null,null,null,null);        User User=null;     List<user> list=new arraylist<> ();         while (Cs.movetonext ()) {user=new user ();         User.setuserid (Cs.getint (Cs.getcolumnindex ("_id"));         User.setname (Cs.getstring (Cs.getcolumnindex ("name")); User.setpwd (Cs.getstring (Cs.getcolumnindex ("PWD ")));        User.setage (Cs.getstring (Cs.getcolumnindex ("Age"));         User.setimg (Cs.getstring (Cs.getcolumnindex ("img"));     List.add (user);        } cs.close ();        Db.close ();    return list;       }//Delete all data public void Delete () {sqlitedatabase db=mydbhelper.getreadabledatabase ();        Db.delete ("info", null,null);    Db.close ();        }//delete a data public void DeleteUser (String id) {sqlitedatabase db=mydbhelper.getreadabledatabase ();        Db.delete ("info", "_id=?", New String[]{id});    Db.close ();        }//Modify data public void Updata (user user) {sqlitedatabase db=mydbhelper.getreadabledatabase ();        Contentvalues cv=new contentvalues ();        Cv.put ("Name", User.getname ());        Cv.put ("pwd", user.getpwd ());        Cv.put ("Age", User.getage ());        Cv.put ("img", User.getimg ());        String id=string.valueof (User.getuserid ());    Db.update ("info", CV, "_id=?", New String[]{id}); }}</span>
<span style= "FONT-SIZE:18PX;" >package Com.example.jreduch08.sqlitedemo;import Android.content.context;import Android.database.sqlite.sqlitedatabase;import android.database.sqlite.sqliteopenhelper;/** * Created by the peak of cupola on 2016/ 8/22.    */public class Mydbhelper extends sqliteopenhelper{//private final String DBNAME = "user.db";    Private final String table_name = "INFO";    Private final String info_colum_id = "_id";//Column name before private final string info_colum_name = "name";    Private final String info_colum_pwd = "PWD";    Private final String info_colum_age = "Age";    Private final String info_colum_img = "IMG";   Public Mydbhelper (Context context) {Super (context, "user.db", null,1); 1 version number.        Walk Onupgrade} public mydbhelper (context context, String name, Sqlitedatabase.cursorfactory factory, int version) {    Super (context, name, Factory, version); } @Override public void OnCreate (Sqlitedatabase SqlitedatabaSE) {StringBuilder sql=new StringBuilder ();        Sql.append ("Create table if not exists"),//+++++++++++++ space +++++++++++ sql.append (table_name+ "(");        Sql.append (info_colum_id+ "Integer primary Key AutoIncrement,");         Sql.append (info_colum_name+ "varchar (10),");        Sql.append (info_colum_pwd+ "varchar (10),");        Sql.append (info_colum_age+ "varchar (10),");        Sql.append (info_colum_img+ "varchar (10)");        Sql.append (")");    Sqlitedatabase.execsql (Sql.tostring ());  } @Override public void Onupgrade (sqlitedatabase sqlitedatabase, int i, int i1) {String sql= "drop table if        Exists "+table_name;        Sqlitedatabase.execsql (SQL);    OnCreate (sqlitedatabase); }}</span>
<span style= "FONT-SIZE:18PX;" >package Com.example.jreduch08.sqlitedemo;import Android.os.bundle;import Android.support.v7.app.appcompatactivity;import Android.view.view;import Android.widget.adapterview;import Android.widget.arrayadapter;import Android.widget.button;import Android.widget.edittext;import Android.widget.spinner;import Android.widget.textview;import Android.widget.toast;import Com.example.jreduch08.R; Import Com.example.jreduch08.sqlitedemo.entity.user;import Com.example.jreduch08.sqlitedemo.entity.UserDao; Import Java.util.arraylist;import Java.util.list;public class Sqllitetestactivity extends Appcompatactivity {private    EditText name,age,pwd;    Private Button button1,button2,button3,button4,button5;   Private TextView TV;    Private Spinner sp;    Private Userdao Userdao;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_sqllite_test); Name= (EditText) findViewbyid (R.id.name);       Age= (EditText) Findviewbyid (r.id.age);        Pwd= (EditText) Findviewbyid (R.ID.PWD);        button1= (Button) Findviewbyid (R.id.button1);        Button2= (Button) Findviewbyid (R.id.button2);        button3= (Button) Findviewbyid (R.id.button3);        button4= (Button) Findviewbyid (R.ID.BUTTON4);        button5= (Button) Findviewbyid (R.ID.BUTTON5);        sp= (Spinner) Findviewbyid (R.ID.SP);        tv= (TextView) Findviewbyid (r.id.tv);        Userdao=new Userdao (this);                Button1.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {                User User=new user ();                User.setname (Name.gettext (). toString ());                User.setage (Age.gettext (). toString ());                User.setpwd (Pwd.gettext (). toString ());                Userdao.insert (user);            Toast.maketext (Getbasecontext (), "added success", Toast.length_short). Show ();        }        }); Button2.setonclickListener (New View.onclicklistener () {@Override public void OnClick (view view) {List                <User> List=userdao.search ();                Tv.settext (List.tostring ());            List mydata=new ArrayList ();                              for (User u:list) {Mydata.add (U.getuserid () + ":" +u.getname ()); } arrayadapter aa=new Arrayadapter (Getbasecontext (), Android.                R.layout. Simple_list_item_1,mydata);            Sp.setadapter (AA);        }        });  Modify Button3.setonclicklistener (new View.onclicklistener () {@Override public void OnClick (view view) {String        Str=sp.getselecteditem (). toString ();            if (!str.equals ("")) {String id = str.split (":") [0];            User User=userdao.searchuser (ID);            User.setname (Name.gettext (). toString ());            User.setpwd (Pwd.gettext (). toString ());    User.setage (Age.gettext (). toString ());        Userdao.updata (user);  }    }}); Button4.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {Stri          Ng Str=sp.getselecteditem (). toString ();              if (!str.equals ("")) {String id=str.split (":") [0];          Userdao.deleteuser (ID);        }      }  });                Button5.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {            Userdao.delete ();        }        }); Sp.setonitemselectedlistener (New Adapterview.onitemselectedlistener () {@Override public void Onitem Selected (adapterview<?> adapterview, view view, int I, long l) {String str= Sp.getselecteditem (). toSt                Ring ();                 if (!str.equals ("")) {String id=str.split (":") [0];                    User user= userdao.searchuser (ID);                Name.settext (User.getname (). toString ());    Age.settext (User.getage (). toString ());                Pwd.settext (User.getpwd (). toString ());            }} @Override public void onnothingselected (adapterview<?> adapterview) {    }        }); }}</span>
<span style= "FONT-SIZE:18PX;" ><?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/ Res/android "xmlns:tools=" Http://schemas.android.com/tools "android:layout_width=" Match_parent "android:layout_he    ight= "Match_parent" tools:context= "com.example.jreduch08.sqlitedemo.SqlliteTestActivity" ><linearlayout Android:layout_width= "Match_parent" android:layout_height= "match_parent" android:orientation= "vertical" > & Lt EditText android:layout_width= "match_parent" android:layout_height= "wrap_content" android:id= "@+id/na Me "android:hint=" Please enter the name "/> <edittext android:layout_width=" Match_parent "Android:lay out_height= "Wrap_content" android:id= "@+id/pwd" android:hint= "Please enter password"/> <edittext and Roid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:id= "@+id/age" android:h Int= "Please enter age "/> <linearlayout android:layout_width=" match_parent "android:layout_height=" Wrap_cont            Ent "android:orientation=" horizontal "> <button android:layout_width=" wrap_content "            android:layout_height= "Wrap_content" android:id= "@+id/button1" android:text= "new"            /> <button android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:id= "@+id/button2" android:text= "Query"/> <button android:la            Yout_width= "Wrap_content" android:layout_height= "wrap_content" android:id= "@+id/button3" android:text= "Modify"/> <button android:layout_width= "Wrap_content" Android:lay out_height= "Wrap_content" android:id= "@+id/button4" android:text= "delete"/> </linea Rlayout> <button android:layout_width= "match_parent" android:layout_height= "wrap_content" android:id= "@+id/button5" android:text= "Delete all"/> <textview android:layout_width= "Match_parent" Android:layout_h eight= "Wrap_content" android:id= "@+id/tv" android:text= "Result:"/> <spinner Android:layo Ut_width= "Match_parent" android:layout_height= "wrap_content" android:id= "@+id/sp" > </spinne R></linearlayout></relativelayout></span>






anroid--Database Sqlite--sqliteopenhelper+sqlitedatabase

Related Article

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.