Using Sqliteopenhelper to create a database, and to make additional deletions and checks

Source: Internet
Author: User
Tags gettext sqlite

The Sqliteopenhelper class is available in Android, and in the constructor of the class, call the method in the context to create and open a database object of the specified name. The main task of inheriting and extending the Sqliteopenhelper class is to rewrite the following two methods. OnCreate (Sqlitedatabase db): This method is executed when the database is first created, and initialization operations such as table creation are typically performed in the method.
Onupgrade (sqlitedatabse dv, int oldversion,int new version): This method is called to update when the database is opened with a different version number than the current version number.
A class named mydbhelper is first established to inherit Sqliteopenhelper in order to create the database.
We're going to use three classes,
mydbhelper (CREATE DATABASE)    Userdao (method of operation)     User (data)
An activity

The code is as follows:
import Android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import Android.database.sqlite.SQLiteOpenHelper;

/**
* Created by Administrator on 2016/8/22.
*/
Public class Mydbhelper extends Sqliteopenhelper {
Private Final String tablename= "info"; //Create a database with table name info
Private Final String info_colum_id= "_id"; //The data in the table, where "_id" represents the ID as the primary key
Private Final String info_colum_name= "NAME"; //second for name,pwd,age,img
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);//user.db indicates that the database name 1 represents the version number, and later, if the code is modified, the revision number is updated

}
Public Mydbhelper (context context, String name, Sqlitedatabase.cursorfactory factory, int version) {
Super (context, name, Factory, version);
}



@Override
Public void OnCreate (Sqlitedatabase db) {
StringBuilder sql=new StringBuilder ();
sql.append ("Create table if not exists");
Sql.append (tablename+ "(");
sql.append (info_colum_id+ "Integer primary Key AutoIncrement,"); //integer primary key AutoIncrement denotes primary key

sql.append (info_colum_name+ "varchar (10),"); varchar indicates length
sql.append (info_colum_pwd+ "varchar (),");
sql.append (info_colum_age+ "varchar (),");
sql.append (info_colum_img+ "varchar");
sql.append (")");
Db.execsql (sql.tostring ());
}

@Override
Public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
String sql= "drop table if exist" +tablename; //update is called
db.execsql (SQL);
onCreate (db);

}
}


The method of writing additions and deletions in Userdao class
Import android.content.ContentValues;
Import Android.content.Context;
Import Android.database.Cursor;
Import Android.database.sqlite.SQLiteDatabase;

Import java.util.ArrayList;
Import java.util.List;

/**
* Created by Administrator on 2016/8/22.
*/
public class Userdao {
Private Mydbhelper Mydbhelper;
Public Userdao (Context context) {
Mydbhelper=new Mydbhelper (context);
}
Inserting 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 ();
}
Delete all data
public void Delete () {
Sqlitedatabase db=mydbhelper.getwritabledatabase ();
Db.delete ("info", NULL, NULL);
Db.close ();
}
Delete a piece of data
public void DeleteUser (String id) {
Sqlitedatabase db=mydbhelper.getwritabledatabase ();
Db.delete ("info", "_id=?", New String []{id});
Db.close ();
}
Querying a single piece of 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;
}
Querying 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;
}
modifying data
public void update (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 ());

String id=string.valueof (User.getuserid ());
Db.update ("info", CV, "_id=?") ", New String[]{id});
Db.close ();
}



User class
public class User {
private int userId;
private String name;
Private String pwd;
Private String age;
Private String img;

public int getUserId () {
return userId;
}

public void Setuserid (int userId) {
This.userid = userId;
}

Public String GetName () {
return name;
}

public void SetName (String name) {
THIS.name = name;
}

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;
}

Public String getimg () {
return img;
}

public void Setimg (String img) {
This.img = img;
}

@Override
Public String toString () {
Return "user{" +
"Userid=" + userId +
", Name= ' + name + ' + ' +
", pwd= ' + pwd + ' \ ' +
", age= '" + Age + "\" +
", img= ' + img + ' + ' +
‘}‘;
}
}


}

The code in the activity is as follows
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.administrator.ch02.entity.User;
Import Com.example.administrator.ch02.entity.UserDao;

Import java.util.ArrayList;
Import java.util.List;

public class Mainactivity extends Appcompatactivity {
private EditText name,age,pwd; EditView in the layout
private Button inster,search,delete,update; button in the layout
private TextView Show; Used to display data
private Userdao Userdao; DAO class
private Spinner Spinner; Spinner in the layout
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Name= (EditText) Findviewbyid (r.id.name);
Age= (EditText) Findviewbyid (r.id.age);
Pwd= (EditText) Findviewbyid (R.ID.PWD);
Inster= (Button) Findviewbyid (r.id.inster1);
Search= (Button) Findviewbyid (R.id.search);
Spinner= (Spinner) Findviewbyid (R.id.spinner);
Delete= (Button) Findviewbyid (r.id.delete);
Update= (Button) Findviewbyid (r.id.update);
Userdao=new Userdao (this);
Inster.setonclicklistener (New View.onclicklistener () { //Add Data
@Override
Public void OnClick (View v) {
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 ();

}
});
Search.setonclicklistener (New View.onclicklistener () { //query data
@Override
Public void OnClick (View v) {
list<user> List=userdao.search ();
//Show.settext (list.tostring ());
List mydate=new ArrayList ();
For (User u:list) {
Mydate.add (U.getuserid () + ":" +u.getname ());
}
arrayadapter aa=new Arrayadapter (Getbasecontext (), Android. R.layout.simple_list_item_1,mydate);
spinner.setadapter (AA);
}
});
Spinner.setonitemselectedlistener (New Adapterview.onitemselectedlistener () {//spinner Click events
@Override
public void onitemselected (adapterview<?> parent, view view, int position, long ID) {
String str = Spinner.getselecteditem (). toString ();
if (!str.equals ("")) {
String id1 = Str.split (":") [0];
User user = Userdao.searchuser (ID1);
Name.settext (User.getname (). toString ());
Age.settext (User.getage (). toString ());
Pwd.settext (User.getpwd (). toString ());
}
}

@Override
public void onnothingselected (adapterview<?> parent) {

}
});
Delete.setonclicklistener (New View.onclicklistener () {//Delete data
@Override
public void OnClick (View v) {
String str = Spinner.getselecteditem (). toString ();
if (!str.equals ("")) {
String id = str.split (":") [0];
Userdao.deleteuser (ID);
}

}
});
Update.setonclicklistener (New View.onclicklistener () {//Modify Data
@Override
public void OnClick (View v) {
String str = Spinner.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.update (user);
}
}
});
}
}

Using Sqliteopenhelper to create a database, and to make additional deletions and checks

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.