很长时间没有写博客了,最近一直在写android for gis方面的项目。不过这篇博客就不写gis方面的了,今天刚刚做的一个简单的android登录系统。数据库是android自带的sqlite,sqlite的优势就不用我说了哈。下面进入正题。
1.数据库Help类
我们需要编写一个数据库辅助类来访问sqlite数据库。在数据库辅助类中,可以完成数据库的创建,表的增加、删除、修改、查询等操作。
1 public class DBHelper extends SQLiteOpenHelper {
2
3 public static final String TB_NAME = "user";
4 public static final String ID = "id";
5 public static final String NAME = "userid";
6 public static final String UerPwd = "userpwd";
7 public DBHelper(Context context, String name, CursorFactory factory,
8 int version) {
9 super(context, name, factory, version);
10 this.getWritableDatabase();
11 // TODO Auto-generated constructor stub
12 }
13
14 @Override
15 //建立表
16 public void onCreate(SQLiteDatabase arg0) {
17 // TODO Auto-generated method stub
18 arg0.execSQL("CREATE TABLE IF NOT EXISTS "
19 + TB_NAME + " ("
20 + ID + " INTEGER PRIMARY KEY,"
21 + NAME + " VARCHAR,"
22 + UerPwd + " VARCHAR)");
23 }
24
25 @Override
26 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
27 // TODO Auto-generated method stub
28
29 }
30 //关闭数据库
31 public void close()
32 {
33 this.getWritableDatabase().close();
34 }
35 //添加新用户
36 public boolean AddUser(String userid,String userpwd)
37 {
38 try
39 {
40 ContentValues cv = new ContentValues();
41 cv.put(this.NAME, userid);//添加用户名
42 cv.put(this.UerPwd,userpwd);//添加密码
43 this.getWritableDatabase().insert(this.TB_NAME,null,cv);
44 return true;
45 }
46 catch(Exception ex)
47 {
48 return false;
49 }
50 }
51
52 }
2.登录页面
这个登录系统比较简单,我们只是简单的验证用户名和密码。
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2 xmlns:tools="http://schemas.android.com/tools"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 android:gravity="center"
6 android:paddingBottom="@dimen/activity_vertical_margin"
7 android:paddingLeft="@dimen/activity_horizontal_margin"
8 android:paddingRight="@dimen/activity_horizontal_margin"
9 android:paddingTop="@dimen/activity_vertical_margin"
10 tools:context=".MainActivity" >
11
12 <LinearLayout
13 android:layout_width="fill_parent"
14 android:layout_height="150dp"
15 android:layout_alignParentTop="true"
16 android:layout_centerHorizontal="true"
17 android:orientation="vertical" >
18
19 <LinearLayout
20 android:id="@+id/lluser"
21 android:layout_width="match_parent"
22 android:layout_height="wrap_content"
23 android:layout_gravity="center"
24 android:gravity="center"
25 android:orientation="horizontal" >
26
27 <TextView
28 android:id="@+id/tv_user"
29 android:layout_width="wrap_content"
30 android:layout_height="match_parent"
31 android:layout_gravity="center"
32 android:gravity="center"
33 android:text="@string/tv_loginnum"
34 android:textSize="18sp" />
35
36 <EditText
37 android:id="@+id/ed_user"
38 android:layout_width="150dp"
39 android:layout_height="40dp"
40 android:layout_marginLeft="10dp"
41 android:inputType="text"
42 android:textSize="18sp"
43 android:textStyle="normal"
44 android:typeface="normal" >
45
46 <requestFocus />
47 </EditText>
48 </LinearLayout>
49
50 <LinearLayout
51 android:id="@+id/llpwd"
52 android:layout_width="match_parent"
53 android:layout_height="wrap_content"
54 android:layout_gravity="center"
55 android:layout_marginTop="10dp"
56 android:gravity="center"
57 android:orientation="horizontal" >
58
59 <TextView
60 android:id="@+id/tv_pwd"
61 android:layout_width="wrap_content"
62 android:layout_height="match_parent"
63 android:gravity="center"
64 android:text="@string/tv_password"
65 android:textSize="18sp" />
66
67 <EditText
68 android:id="@+id/ed_pwd"
69 android:layout_width="150dp"
70 android:layout_height="40dp"
71 android:layout_marginLeft="10dp"
72 android:inputType="textPassword"
73 android:textSize="18sp"
74 android:textStyle="normal" />
75
76 </LinearLayout>
77
78 <LinearLayout
79 android:layout_width="match_parent"
80 android:layout_height="wrap_content"
81 android:layout_gravity="center"
82 android:layout_marginTop="10dp"
83 android:gravity="center"
84 android:orientation="horizontal" >
85
86 <Button
87 android:id="@+id/btnlogin"
88 android:layout_width="wrap_content"
89 android:layout_height="match_parent"
90 android:text="@string/txlogin" />
91
92 <Button
93 android:id="@+id/btnreg"
94 android:layout_width="wrap_content"
95 android:layout_height="match_parent"
96 android:layout_gravity="center"
97 android:layout_marginLeft="30dp"
98 android:text="@string/txregister" />
99
100 </LinearLayout>
101 </LinearLayout>
102
103 </RelativeLayout>
这个登录界面没有任何的修饰,而且我最近喜欢用RelativeLayout和LinearLayout搭配使用。RelativeLayout是相对布局,LinearLayout是绝对布局。登录页面只有两个输入框和两个按钮,一个用于提交,另一个用于注册。
1 package com.example.login;
2
3 import android.os.Bundle;
4 import android.app.Activity;
5 import android.content.Intent;
6 import android.database.Cursor;
7 import android.database.sqlite.SQLiteDatabase;
8 import android.view.Menu;
9 import android.view.View;
10 import android.widget.Button;
11 import android.widget.EditText;
12 import android.widget.Toast;
13
14 public class MainActivity extends Activity {
15
16 EditText ed_id;
17 EditText ed_pwd;
18 DBHelper database;
19 @Override
20 protected void onCreate(Bundle savedInstanceState) {
21 super.onCreate(savedInstanceState);
22 setContentView(R.layout.activity_main);
23 ed_id=(EditText)findViewById(R.id.ed_user);
24 ed_pwd=(EditText)findViewById(R.id.ed_pwd);
25 Button btnlogin=(Button)findViewById(R.id.btnlogin);
26 database = new DBHelper(MainActivity.this,"LoginInfo",null,1);//这段代码放到Activity类中才用this
27 btnlogin.setOnClickListener(new View.OnClickListener() {
28
29 @Override
30 public void onClick(View v) {
31 // TODO Auto-generated method stub
32 getUser();
33 }
34 });
35 Button btnreg=(Button)findViewById(R.id.btnreg);
36 btnreg.setOnClickListener(new View.OnClickListener() {
37
38 @Override
39 public void onClick(View v) {
40 // TODO Auto-generated method stub
41 Intent intent=new Intent();
42 intent.setClass(MainActivity.this, UserRegister.class);
43 startActivity(intent);
44 }
45 });
46 }
47 public void getUser()
48 {
49 String sql="select * from user where userid=?";
50 Cursor cursor=database.getWritableDatabase().rawQuery(sql, new String[]{ed_id.getText().toString()});
51 if(cursor.moveToFirst())
52 {
53
54 if(ed_pwd.getText().toString().equals(cursor.getString(cursor.getColumnIndex("userpwd"))))
55 {
56 Toast.makeText(this, "登录成功", 5000).show();
57 }
58 else
59 {
60 Toast.makeText(this, "用户名或者密码错误", 5000).show();
61 }
62 }
63 database.close();
64 }
65 @Override
66 public boolean onCreateOptionsMenu(Menu menu) {
67 // Inflate the menu; this adds items to the action bar if it is present.
68 getMenuInflater().inflate(R.menu.main, menu);
69 return true;
70 }
71
72 }
在后台,我们主要做的就是对用户名和密码的验证。通过前面定义的辅助类来实现。
3.注册页面
注册用户,提供新用户的注册。只要用户名和密码,以及对密码的确认。
1 <?xml version="1.0" encoding="utf-8"?>
2 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 android:gravity="center" >
6
7 <LinearLayout
8 android:layout_width="fill_parent"
9 android:layout_height="200dp"
10 android:layout_alignParentTop="true"
11 android:layout_centerHorizontal="true"
12 android:gravity="center"
13 android:orientation="vertical" >
14
15 <LinearLayout
16 android:id="@+id/lluserreg"
17 android:layout_width="match_parent"
18 android:layout_height="wrap_content"
19 android:layout_gravity="center"
20 android:orientation="horizontal" >
21
22 <TextView
23 android:id="@+id/tv_userreg"
24 android:layout_width="wrap_content"
25 android:layout_height="match_parent"
26 android:layout_gravity="center"
27 android:gravity="center"
28 android:text="@string/tv_loginnum"
29 android:textSize="18sp" />
30
31 <EditText
32 android:id="@+id/ed_userreg"
33 android:layout_width="150dp"
34 android:layout_height="40dp"
35 android:layout_marginLeft="60dp"
36 android:inputType="text"
37 android:textSize="18sp"
38 android:textStyle="normal"
39 android:typeface="normal" >
40
41 <requestFocus />
42 </EditText>
43 </LinearLayout>
44
45 <LinearLayout
46 android:id="@+id/llpwdreg"
47 android:layout_width="match_parent"
48 android:layout_height="wrap_content"
49 android:layout_gravity="center"
50 android:layout_marginTop="10dp"
51 android:orientation="horizontal" >
52
53 <TextView
54 android:id="@+id/tv_pwdreg"
55 android:layout_width="wrap_content"
56 android:layout_height="match_parent"
57 android:gravity="center"
58 android:text="@string/tv_password"
59 android:textSize="18sp" />
60
61 <EditText
62 android:id="@+id/ed_pwdreg"
63 android:layout_width="150dp"
64 android:layout_height="40dp"
65 android:layout_marginLeft="60dp"
66 android:inputType="textPassword"
67 android:textSize="18sp"
68 android:textStyle="normal" />
69
70 </LinearLayout>
71
72 <LinearLayout
73 android:id="@+id/llpwdreg2"
74 android:layout_width="match_parent"
75 android:layout_height="wrap_content"
76 android:layout_gravity="center"
77 android:layout_marginTop="10dp"
78 android:orientation="horizontal" >
79
80 <TextView
81 android:id="@+id/tv_pwdreg2"
82 android:layout_width="wrap_content"
83 android:layout_height="match_parent"
84 android:gravity="center"
85 android:text="@string/tv_conregpwd"
86 android:textSize="18sp" />
87
88 <EditText
89 android:id="@+id/ed_pwdreg2"
90 android:layout_width="150dp"
91 android:layout_height="40dp"
92 android:layout_marginLeft="22dp"
93 android:inputType="textPassword"
94 android:textSize="18sp"
95 android:textStyle="normal" />
96
97 </LinearLayout>
98 <LinearLayout
99 android:layout_width="match_parent"
100 android:layout_height="wrap_content"
101 android:layout_gravity="center"
102 android:layout_marginTop="10dp"
103 android:gravity="center"
104 android:orientation="horizontal" >
105
106 <Button
107 android:id="@+id/btnsub"
108 android:layout_width="wrap_content"
109 android:layout_height="match_parent"
110 android:text="@string/txsubmit" />
111
112 <Button
113 android:id="@+id/btncancel"
114 android:layout_width="wrap_content"
115 android:layout_height="match_parent"
116 android:layout_gravity="center"
117 android:layout_marginLeft="30dp"
118 android:text="@string/txcancel" />
119
120 </LinearLayout>
121 </LinearLayout>
122
123 </RelativeLayout>
界面包括:用户名、密码、确认密码、提交和取消。
1 package com.example.login;
2
3 import android.app.Activity;
4 import android.content.Intent;
5 import android.database.Cursor;
6 import android.os.Bundle;
7 import android.view.View;
8 import android.widget.Button;
9 import android.widget.EditText;
10 import android.widget.Toast;
11
12 public class UserRegister extends Activity {
13
14 EditText edtext;
15 EditText edpwd;
16 EditText edpwd2;
17 protected void onCreate(Bundle savedInstanceState)
18 {
19 super.onCreate(savedInstanceState);
20 setContentView(R.layout.user_add);
21 Button btnsub=(Button)findViewById(R.id.btnsub);
22 edtext=(EditText)findViewById(R.id.ed_userreg);
23 edpwd=(EditText)findViewById(R.id.ed_pwdreg);
24 edpwd2=(EditText)findViewById(R.id.ed_pwdreg2);
25 btnsub.setOnClickListener(new View.OnClickListener() {
26
27 @Override
28 public void onClick(View v) {
29 // TODO Auto-generated method stub
30 setUser();
31 }
32 });
33 Button btncancel=(Button)findViewById(R.id.btncancel);
34 btncancel.setOnClickListener(new View.OnClickListener() {
35
36 @Override
37 public void onClick(View v) {
38 // TODO Auto-generated method stub
39 finish();
40 }
41 });
42
43 }
44 private void setUser()
45 {
46 DBHelper database=new DBHelper(UserRegister.this,"LoginInfo",null,1);
47
48
49 if(edtext.getText().toString().length()<=0||edpwd.getText().toString().length()<=0||edpwd2.getText().toString().length()<=0)
50 {
51 Toast.makeText(this, "用户名或密码不能为空", 5000).show();
52 return;
53 }
54 if(edtext.getText().toString().length()>0)
55 {
56 String sql="select * from user where userid=?";
57 Cursor cursor=database.getWritableDatabase().rawQuery(sql, new String[]{edtext.getText().toString()});
58 if(cursor.moveToFirst())
59 {
60 Toast.makeText(this, "用户名已经存在", 5000).show();
61 return;
62 }
63 }
64 if(!edpwd.getText().toString().equals(edpwd2.getText().toString()))
65 {
66 Toast.makeText(this, "两次输入的密码不同", 5000).show();
67 return;
68 }
69 if(database.AddUser(edtext.getText().toString(), edpwd.getText().toString()))
70 {
71 Toast.makeText(this, "用户注册成功", 5000).show();
72 Intent intent=new Intent();
73 intent.setClass(this, MainActivity.class);
74 startActivity(intent);
75 }
76 else
77 {
78 Toast.makeText(this, "用户注册失败", 5000).show();
79 }
80 database.close();
81 }
82
83 }
后台代码主要完成用户的添加。为了确保用户的唯一性,需要对用户的账号进行验证,看表中是否已经存在相同的账号。同时,还需要确保两次输入密码的一致性。
4.界面截图
5.Sqlite相关知识
SQLiteOpenHelper是SQLiteDatabase的一个帮助类,用来管理数据库的创建和版本的更新。一般是建立一个类继承它,并实现它的onCreate和onUpgrade方法。
方法名 | 方法描述 |
---|---|
SQLiteOpenHelper(Context context,String name,SQLiteDatabase.CursorFactory factory,int version) | 构造方法,一般是传递一个要创建的数据库名称那么参数 |
onCreate(SQLiteDatabase db) | 创建数据库时调用 |
onUpgrade(SQLiteDatabase db,int oldVersion , int newVersion) | 版本更新时调用 |
getReadableDatabase() | 创建或打开一个只读数据库 |
getWritableDatabase() | 创建或打开一个读写数据库 |
SQLiteDatabase类为我们提供了很多种方法,而较常用的方法如下
(返回值)方法名 | 方法描述 |
---|---|
(int) delete(String table,String whereClause,String[] whereArgs) | 删除数据行的便捷方法 |
(long) insert(String table,String nullColumnHack,ContentValues values) | 添加数据行的便捷方法 |
(int) update(String table, ContentValues values, String whereClause, String[] whereArgs) | 更新数据行的便捷方法 |
(void) execSQL(String sql) | 执行一个SQL语句,可以是一个select或其他的sql语句 |
(void) close() | 关闭数据库 |
(Cursor) query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) | 查询指定的数据表返回一个带游标的数据集 |
(Cursor) rawQuery(String sql, String[] selectionArgs) | 运行一个预置的SQL语句,返回带游标的数据集(与上面的语句最大的区别就是防止SQL注入) |