【Android 应用开发】 Android 相关代码规范 更新中 ...(二)

简介: 【Android 应用开发】 Android 相关代码规范 更新中 ...(二)

三. 数据库模块代码常用结构





1. SQLiteOpenHelper 类





(1) 命令 版本号



类命名 : 一般命令为 XXOpenHelper, 例如 DBOpenHelper;


版本号 : 在类中定义一个常量, 用于保存版本号;



private static final int DATABASE_VERSION = 1;


(2) 单例模式



单例 : SQLiteOpenHelper 类, 在应用中只保存一个对象即可;


-- 私有, 静态化本类成员变量 : 例如该类类名为 DBOpenHelper, 那么定义一个 DBOpenHelper 的成员变量, 注意将改变量设置成静态变量;



private static DbOpenHelper instance;

-- 私有化构造函数 :  将构造函数设置为私有函数;


private DbOpenHelper(Context context) {
  super(context, getUserDatabaseName(), null, DATABASE_VERSION);
  }

-- 共有, 静态 方法获取成员变量 : 使用懒汉模式, 如果 本类类型成员变量 为null, 就调用私有的静态构造方法, 如果不为null, 就直接返回 本类类型静态变量;



public static DbOpenHelper getInstance(Context context) {
  if (instance == null) {
    instance = new DbOpenHelper(context.getApplicationContext());
  }
  return instance;
  }


(3) SQL 语句字段名维护



字段名使用 :


-- SQLiteOpenHelper 中的字段 : 建立数据库需要字段名称;


-- JavaBean 中的字段 : 在代码中经常用到字段名称, 一般规律是 在JavaBean 中的变量名 与 数据库中字段名相同, 字段名在 JavaBean 中需要使用, 用于从 Cursor 中获取对象;


-- Dao 中的字段 : 在插入数据时, 也许要字段名称;




维护字段名称常量 : 个人认为字段名称常量维护在 JavaBean 中最好, 这样就可以将所有的字段名都限制在 JavaBean 类中, 其它位置不用关心字段名称;






(4) SQLiteOpenHelper 代码示例




/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.easemob.chatuidemo.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.easemob.applib.controller.HXSDKHelper;
public class DbOpenHelper extends SQLiteOpenHelper{
  private static final int DATABASE_VERSION = 1;
  private static DbOpenHelper instance;
  private static final String USERNAME_TABLE_CREATE = "CREATE TABLE "
    + UserDao.TABLE_NAME + " ("
    + UserDao.COLUMN_NAME_NICK +" TEXT, "
    + UserDao.COLUMN_NAME_ID + " TEXT PRIMARY KEY);";
  private static final String INIVTE_MESSAGE_TABLE_CREATE = "CREATE TABLE "
    + InviteMessgeDao.TABLE_NAME + " ("
    + InviteMessgeDao.COLUMN_NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + InviteMessgeDao.COLUMN_NAME_FROM + " TEXT, "
    + InviteMessgeDao.COLUMN_NAME_GROUP_ID + " TEXT, "
    + InviteMessgeDao.COLUMN_NAME_GROUP_Name + " TEXT, "
    + InviteMessgeDao.COLUMN_NAME_REASON + " TEXT, "
    + InviteMessgeDao.COLUMN_NAME_STATUS + " INTEGER, "
    + InviteMessgeDao.COLUMN_NAME_ISINVITEFROMME + " INTEGER, "
    + InviteMessgeDao.COLUMN_NAME_TIME + " TEXT); ";
  private DbOpenHelper(Context context) {
  super(context, getUserDatabaseName(), null, DATABASE_VERSION);
  }
  public static DbOpenHelper getInstance(Context context) {
  if (instance == null) {
    instance = new DbOpenHelper(context.getApplicationContext());
  }
  return instance;
  }
  private static String getUserDatabaseName() {
        return  HXSDKHelper.getInstance().getHXId() + "_demo.db";
    }
  @Override
  public void onCreate(SQLiteDatabase db) {
  db.execSQL(USERNAME_TABLE_CREATE);
  db.execSQL(INIVTE_MESSAGE_TABLE_CREATE);
  }
  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  }
  public void closeDB() {
     if (instance != null) {
         try {
             SQLiteDatabase db = instance.getWritableDatabase();
             db.close();
         } catch (Exception e) {
             e.printStackTrace();
         }
         instance = null;
     }
  }
}




2. Dao 类规范



该类作用 : 将对数据库增删查改的操作都放在该类中;






(1) 维护 SQLiteOpenHelper 变量



维护变量 : 在 Dao 类中, 维护该变量, 方法中使用 OpenHelper 快速获取数据库;






(2) 在方法中实时获取 SQLiteDatabase 变量



获取数据库对象 : 如果对数据库进行操作时, 需要在方法中根据需求获取 dbHelper.getWritableDatabase() 或者 dbHelper.getReadableDatabase() 数据库对象;






(3) Dao 代码示例



/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.easemob.chatuidemo.db;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import com.easemob.chatuidemo.Constant;
import com.easemob.chatuidemo.domain.User;
import com.easemob.util.HanziToPinyin;
public class UserDao {
  public static final String TABLE_NAME = "uers";
  public static final String COLUMN_NAME_ID = "username";
  public static final String COLUMN_NAME_NICK = "nick";
  public static final String COLUMN_NAME_IS_STRANGER = "is_stranger";
  private DbOpenHelper dbHelper;
  public UserDao(Context context) {
  dbHelper = DbOpenHelper.getInstance(context);
  }
  /**
  * 保存好友list
  * 
  * @param contactList
  */
  public void saveContactList(List<User> contactList) {
  SQLiteDatabase db = dbHelper.getWritableDatabase();
  if (db.isOpen()) {
    db.delete(TABLE_NAME, null, null);
    for (User user : contactList) {
    ContentValues values = new ContentValues();
    values.put(COLUMN_NAME_ID, user.getUsername());
    if(user.getNick() != null)
      values.put(COLUMN_NAME_NICK, user.getNick());
    db.replace(TABLE_NAME, null, values);
    }
  }
  }
  /**
  * 获取好友list
  * 
  * @return
  */
  public Map<String, User> getContactList() {
  SQLiteDatabase db = dbHelper.getReadableDatabase();
  Map<String, User> users = new HashMap<String, User>();
  if (db.isOpen()) {
    Cursor cursor = db.rawQuery("select * from " + TABLE_NAME /* + " desc" */, null);
    while (cursor.moveToNext()) {
    String username = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_ID));
    String nick = cursor.getString(cursor.getColumnIndex(COLUMN_NAME_NICK));
    User user = new User();
    user.setUsername(username);
    user.setNick(nick);
    String headerName = null;
    if (!TextUtils.isEmpty(user.getNick())) {
      headerName = user.getNick();
    } else {
      headerName = user.getUsername();
    }
    if (username.equals(Constant.NEW_FRIENDS_USERNAME) || username.equals(Constant.GROUP_USERNAME)) {
      user.setHeader("");
    } else if (Character.isDigit(headerName.charAt(0))) {
      user.setHeader("#");
    } else {
      user.setHeader(HanziToPinyin.getInstance().get(headerName.substring(0, 1))
        .get(0).target.substring(0, 1).toUpperCase());
      char header = user.getHeader().toLowerCase().charAt(0);
      if (header < 'a' || header > 'z') {
      user.setHeader("#");
      }
    }
    users.put(username, user);
    }
    cursor.close();
  }
  return users;
  }
  /**
  * 删除一个联系人
  * @param username
  */
  public void deleteContact(String username){
  SQLiteDatabase db = dbHelper.getWritableDatabase();
  if(db.isOpen()){
    db.delete(TABLE_NAME, COLUMN_NAME_ID + " = ?", new String[]{username});
  }
  }
  /**
  * 保存一个联系人
  * @param user
  */
  public void saveContact(User user){
  SQLiteDatabase db = dbHelper.getWritableDatabase();
  ContentValues values = new ContentValues();
  values.put(COLUMN_NAME_ID, user.getUsername());
  if(user.getNick() != null)
    values.put(COLUMN_NAME_NICK, user.getNick());
  if(db.isOpen()){
    db.replace(TABLE_NAME, null, values);
  }
  }
}




目录
相关文章
|
1月前
|
Ubuntu 网络协议 Java
【Android平板编程】远程Ubuntu服务器code-server编程写代码
【Android平板编程】远程Ubuntu服务器code-server编程写代码
|
3月前
|
人工智能 IDE 开发工具
Studio Bot - 让 AI 帮我写 Android 代码
Studio Bot - 让 AI 帮我写 Android 代码
153 1
|
9月前
|
IDE 数据可视化 Java
Android自动生成代码,可视化脚手架之基础信息配置
今天的内容比较简单,大致过一下Electron一些基本用法,虽然说这些比较简单,但又是不得不去了解的,正如做Android的我们,也不是一上来就会的,需要一个循序渐进的过程,下一章,我们再去实际的开发功能。
133 0
|
2月前
|
Ubuntu 网络协议 Linux
【Linux】Android平板上远程连接Ubuntu服务器code-server进行代码开发
【Linux】Android平板上远程连接Ubuntu服务器code-server进行代码开发
49 0
|
3月前
|
安全 算法 JavaScript
安卓逆向 -- 关键代码定位与分析技术
安卓逆向 -- 关键代码定位与分析技术
39 0
|
3月前
|
安全 Android开发 数据安全/隐私保护
代码安全之代码混淆及加固(Android)
代码安全之代码混淆及加固(Android)
40 0
|
4月前
|
安全 Java Android开发
Android App开发之安全加固中反编译、代码混淆、第三方加固以及重签名的讲解及实战(图文解释 简单易懂)
Android App开发之安全加固中反编译、代码混淆、第三方加固以及重签名的讲解及实战(图文解释 简单易懂)
70 0
|
6月前
|
XML Java Android开发
Android 解决使用CocosCreator开发产品上架应用市场代码重复问题
Android 解决使用CocosCreator开发产品上架应用市场代码重复问题
272 0
|
7月前
|
JSON dexposed Java
一文总结 Android 隐私合规代码思路
一文总结 Android 隐私合规代码思路
|
7月前
|
SQL 程序员 Android开发
一行代码,利用 android studio自带的 liveTemplate 快速生成单例模式,程序员偷懒神器
一行代码,利用 android studio自带的 liveTemplate 快速生成单例模式,程序员偷懒神器