今天我们来学习一下,关于android数据库持久层框架ormlite的应用,首先这是一个app的登录界面。使用该框架将用户的用户名和电话号码存储到数据库中。app的登录界面提供记住密码的功能。具体界面如下所示。
首先,我们来看关于ormlite框架,在使用中的帮助类,这个帮助类用于每个bean注册以及数据的更新。
package com.example.arcroid.fastrsmapp.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.example.arcroid.fastrsmapp.bean.FixRadioPointBean;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
/**
* 作者:created by qrb_PC
* 日期:创建于 2018/12/9
*/
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String TABLE_NAME = "sqlite_GZCHApp.db";
private Map<String, Dao> daos = new HashMap<String, Dao>();
private DatabaseHelper(Context context)
{
super(context, TABLE_NAME, null, 11);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, User.class);
}catch (SQLException e){
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
try {
Log.d("Db", "onUpgrade");
TableUtils.dropTable(connectionSource, User.class, true);
onCreate(sqLiteDatabase, connectionSource);
}catch (Exception e)
{
e.printStackTrace();
}
}
private static DatabaseHelper instance;
/**
* 单例获取该Helper
*
* @param context
* @return
*/
public static synchronized DatabaseHelper getHelper(Context context){
context = context.getApplicationContext();
if (instance == null)
{
synchronized (DatabaseHelper.class)
{
if (instance == null)
instance = new DatabaseHelper(context);
}
}
return instance;
}
public synchronized Dao getDao(Class clazz) throws SQLException
{
Dao dao = null;
String className = clazz.getSimpleName();
if (daos.containsKey(className))
{
dao = daos.get(className);
}
if (dao == null)
{
dao = super.getDao(clazz);
daos.put(className, dao);
}
return dao;
}
/**
* 释放资源
*/
@Override
public void close()
{
super.close();
for (String key : daos.keySet())
{
Dao dao = daos.get(key);
dao = null;
}
}
}
然后我们来看创建的bean类,这个bean类我们命名为User,ormlite数据库框架和Hibernate极其相似(最近正好使用到这个)。ormlite对bean的每个字段属性进行了标记,比如说主键id.id的自动生成等。来看一下这个bean类,其中有两个字段,分别是username(用户名)、usertel(用户电话号码),以及相应构造方法以及属性。具体代码如下。需要注意的是bean必须有无参数的构造方法。
/**
* 作者:created by qrb_PC
* 日期:创建于 2018/12/23
*/
@DatabaseTable
public class User {
@DatabaseField
private String username;/*用户名称*/
@DatabaseField(id=true)
private String usertel;/*用户电话*/
public User() {
}
public User(String username, String usertel) {
this.username = username;
this.usertel = usertel;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsertel() {
return usertel;
}
public void setUsertel(String usertel) {
this.usertel = usertel;
}
}
好了,写完bean后,我们来看一下dao类,dao类中有一个含Context参数的构造方法,用于在不同的上下文中创建实例对象。该类中还提供了查询与更新创建bean方法,具体如下所示。
/**
* 作者:created by qrb_PC
* 日期:创建于 2018/12/23
*/
public class UserDao {
private Dao<User, String> userDaoOpe;
private DatabaseHelper helper;
public UserDao(Context context)
{
try
{
helper = DatabaseHelper.getHelper(context);
userDaoOpe = helper.getDao(User.class);
} catch (SQLException e)
{
e.printStackTrace();
}
}
public void addOrUpdate(User user)
{
try
{
userDaoOpe.createOrUpdate(user);
} catch (SQLException e)
{
e.printStackTrace();
}
}
public List<User> query(String field, Object val) {
List<User> ret = new ArrayList<>();
try {
ret = userDaoOpe.queryBuilder().where().eq(field, val).query();
} catch (SQLException e) {
e.printStackTrace();
}
return ret;
}
public User get(String id){
try {
return this.userDaoOpe.queryForId(id);
}catch (SQLException e){
e.printStackTrace();
}
return null;
}
}
下面我来看一下登录的activity布局界面。
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
android:orientation="vertical"
android:id="@+id/loginRoot"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="3"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:orientation="vertical"
android:id="@+id/LinearLayout01"
android:gravity="center"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.0">
<RelativeLayout
android:id="@+id/RelativeLayout02"
android:background="@drawable/login_back"
android:layout_marginBottom="15.0px"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="15.0px"
android:layout_marginTop="15.0px"
android:layout_marginRight="15.0px">
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_centerInParent="true"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:id="@+id/layout_login_username"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_height="wrap_content">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:id="@+id/icon_login"
android:layout_marginTop="5.0dip"
android:layout_marginBottom="5.0px"
android:layout_marginLeft="5px"
android:layout_marginStart="8dp"
android:layout_gravity="center_vertical"
android:background="@mipmap/img_login_usr_in"
android:visibility="visible" />
<EditText
android:id="@+id/edit_login_username"
android:focusable="true"
android:background="@drawable/qq_edit_login"
android:paddingLeft="45.0sp"
android:layout_toRightOf="@+id/icon_login"
android:saveEnabled="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5.0dip"
android:layout_marginTop="5.0dip"
android:layout_marginRight="5.0dip"
android:layout_marginBottom="5.0px"
android:hint="请输入用户名"
android:maxLength="10"
android:layout_alignParentTop="true" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:id="@+id/layout_login_password"
android:focusable="true"
android:layout_marginBottom="10dp"
android:focusableInTouchMode="true"
android:layout_below="@+id/layout_login_username"
android:layout_height="wrap_content">
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginTop="5.0dip"
android:layout_marginLeft="5px"
android:layout_marginBottom="5.0px"
android:layout_marginStart="8dp"
android:layout_gravity="center_vertical"
android:background="@mipmap/img_login_usr_password"
android:visibility="visible" />
<EditText
android:id="@+id/edit_login_password"
android:focusable="true"
android:background="@drawable/qq_edit_login"
android:paddingLeft="45.0sp"
android:layout_toRightOf="@+id/icon_login"
android:saveEnabled="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5.0dip"
android:layout_marginTop="5.0dip"
android:layout_marginRight="5.0dip"
android:layout_marginBottom="5.0px"
android:hint="请输入用户电话"
android:maxLength="20"
android:layout_alignParentTop="true" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_marginLeft="20px"
android:layout_marginRight="20px"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="@+id/ck_rem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_alignParentRight="true"
android:text="记住用户名和电话"/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:visibility="gone"
android:layout_height="wrap_content">
<Button
android:layout_width="match_parent"
android:layout_marginLeft="20px"
android:layout_marginTop="5dip"
android:background="@drawable/shape_btn_exit"
android:id="@+id/btn_login_type"
android:text="请选择用户类型"
android:textColor="@color/colorWhite"
android:layout_marginRight="20px"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/btn_login"
android:layout_width="match_parent"
android:textColor="@color/colorWhite"
android:layout_marginTop="5dip"
android:layout_height="wrap_content"
android:layout_marginLeft="20px"
android:background="@drawable/shape_btn_exit"
android:layout_marginRight="20px"
android:text="登陆" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_weight="2"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
在登录的activity中,我们使用SharedPreferences来实现密码记住,具体实现如下所示。
public class LoginActivity extends Activity {
private Button btn_login;
private EditText accountEdit = null;
private EditText passwordEdit = null;
private SharedPreferences pref;
private SharedPreferences.Editor editor;
private CheckBox ck_rem;
private UserDao userDao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
pref = PreferenceManager.getDefaultSharedPreferences(this);
btn_login = (Button) findViewById(R.id.btn_login);
userDao=new UserDao(this);
accountEdit = (EditText) findViewById(R.id.edit_login_username);
passwordEdit = (EditText) findViewById(R.id.edit_login_password);
ck_rem = (CheckBox) findViewById(R.id.ck_rem);
boolean isRemember = pref.getBoolean(ConfUtils.keyRemember_Password, false);
if (isRemember) {
// 将账号和密码都设置到文本框中
String account = pref.getString(ConfUtils.keyUserName, "");
String password = pref.getString(ConfUtils.keyUserTel, "");
accountEdit.setText(account);
passwordEdit.setText(password);
ck_rem.setChecked(true);
}
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String account = accountEdit.getText().toString();
String password = passwordEdit.getText().toString();
if (isMobileNO(password)){
User user=new User(account,password);
userDao.addOrUpdate(user);
editor = pref.edit();
if (ck_rem.isChecked()) { // 检查复选框是否被选中
editor.putBoolean(ConfUtils.keyRemember_Password, true);
editor.putString(ConfUtils.keyUserName, account);
editor.putString(ConfUtils.keyUserTel, password);
} else {
editor.clear();
}
editor.commit();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra(ConfUtils.keyUserTel,password);
startActivity(intent);
finish();
}else{
Toast.makeText(getApplication(), "电话号码有误", Toast.LENGTH_SHORT).show();
}
}
});
}
public boolean isMobileNO(String mobiles) {
Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
Matcher m = p.matcher(mobiles);
return m.matches();
}
}
更多内容,请关注公众号