[Android Application Development] the Android code specification is being updated...

Source: Internet
Author: User

[Android Application Development] the Android code specification is being updated...

.


Introduction: Common Android code structures, including package specifications, test case specifications, and common writing specifications for database modules;


Reference: A previously written blog[Android Application Development] Application Usage Analysis;

--Application Analysis: Application concept, declaration cycle, data transfer between components, and data cache;

--Source code analysis: Analyze the Application structure Interface source code;

--Example: Customize Application Registration, save the crash log to the file, and listen to the Activity declaration cycle;





I. Package Structure Specification



1. Basic Package, Business Package, and test package


Package infrastructure:

--Base package: Common public packages and classes of applications are placed in this package, such as tool class, SQLiteOpenHelper, configuration class, Application, and base classes of various types;

--Business Package: The actual business package in the application. This package stores the classes and packages related to the app business;

--Test package: Used to store packages related to unit tests and test cases;


Example:




2. Split Java classes into different packages based on their types


UI-related:

--Activity: Stores Activity-related packages;

--Fragment: Stores Fragment-related classes;

--Widget: Stores custom component-related classes;


Adapter Problems:

--Adapter: Various adapters, especially the BaseAdapter subclass;


Java Bean-related: The following two package names often store JavaBean objects;

--Bean:

--Domain:


Tool:

--Utils: Stores tool classes;


Listener Problems:

--Listener: Stores various listeners, such as button-click listeners;


Database Problems:

--Sqlite: Stores database-related packages;


Business-related:

--Engine: Stores business logic-related classes;




II. Application code specification



1. Application Singleton Specification


Singleton attributes: Application itself is the singleton mode. Only one Application object exists in the entire Application;


Implement Application Singleton:

--Define an Application type object: Define a function of the Application type in the Custom Application;

private static QIApplication INSTANCE;
-- Define private constructor:

/*** Constructor construction Application */private QIApplication () {INSTANCE = this ;}
-- Get objects using common and static methods: You can call this method in any class to obtain the Application context object.;

/*** Get Application use this function to obtain data in the Application at any location * @ return */public static QIApplication getInstance () {return INSTANCE ;}



2. Application is used for data transfer and data cache between components


This is explained in the [Android Application Development] Application Usage Analysis blog;

Data transmission between Application components,Application Data Cache;



3. Common Application frameworks


Sample Code:

Public class MyApplication extends Application {private static MyApplication INSTANCE;/** Map set for data transmission */private Map <String, Object> transferMap; /** Map set used to cache data */private Map <String, Object> cacheMap;/*** constructor to Construct Application */private MyApplication () {INSTANCE = this ;} /*** get Application use this function to obtain data in the Application at any location * @ return */public static MyApplication getInstance () {return INSTANCE;} @ Overridepublic void onCreate () {super. onCreate (); // initialize the Map set for data transmission transferMap = new HashMap <String, Object> (); // initialize the Map set for data cache cacheMap = new HashMap <String, Object> ();} /*** get data transfer Map set * @ return * data transfer Map set */public Map <String, Object> getTransferMap () {return transferMap ;} /*** add data elements to the transferMap Set */public void putTransferMapElement (String key, Object object) {transferMap. put (key, object);} public Object getTransferMapElement (String key) {return transferMap. get (key);}/*** remove the corresponding data element from transferMap data */public void removeTransferMapElement (String key) {transferMap. remove (key);}/*** get data cache Map set * @ return * data cache Map set */public Map <String, Object> getCacheMap () {return cacheMap ;}}




Iii. Common Structure of database module code



1. SQLiteOpenHelper class



(1) command version number


Class Name: The General Command isXXOpenHelper, Such as DBOpenHelper;

Version Number: Define a constant in the class to save the version number;

private static final int DATABASE_VERSION = 1;


(2) Singleton Mode


Singleton: SQLiteOpenHelper class. Only one object can be saved in the application;

--Private and static member variables of this class: For example, if the class name is DBOpenHelper, define a member variable of DBOpenHelper and set the change volume to a static variable;

private static DbOpenHelper instance;
-- Private Constructor: Set the constructor to a private function;

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

--Common, static method for getting member variables: The Lazy mode is used. If the member variable of this class type is null, the Private Static constructor is called. If the member variable is not null, the static variables of this class are directly returned;

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


(3) maintenance of SQL statement Field Names


Field name usage:

--Fields in SQLiteOpenHelper: Field name required for database creation;

--Fields in JavaBean: Field names are often used in code. Generally, the variable names in the JavaBean are the same as those in the database. The field names must be used in the JavaBean to obtain objects from the Cursor;

--Fields in Dao: The field name may be required when inserting data;


Maintain field name Constants: I personally think that it is best to maintain the field name constant in JavaBean, so that all field names can be restricted in the JavaBean class, other locations do not care about the field name;



(4) SQLiteOpenHelper sample code


/** * 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";    }@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL(USERNAME_TABLE_CREATE);db.execSQL(INIVTE_MESSAGE_TABLE_CREATE);}@Overridepublic 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 class specification


Function: Add, delete, query, and modify operations to the database in this class;



(1) maintain the SQLiteOpenHelper variable


Maintenance variable: Maintain the variable in the Dao class. Use OpenHelper in the method to quickly obtain the database;



(2) obtain the SQLiteDatabase variable in real time in the Method


Obtain database objects: If you operate a database, you need to obtain the dbHelper. getWritableDatabase () or dbHelper. getReadableDatabase () database object in the method as needed;



(3) Dao code example


/*** 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 License t 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 d Istributed 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. dat Abase. 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 f Inal String COLUMN_NAME_IS_STRANGER = "is_stranger"; private DbOpenHelper dbHelper; public UserDao (Context context) {dbHelper = DbOpenHelper. getInstance (context);}/*** save friend 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) {ContentValue S 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) ;}}/ *** get friend 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 () {Stri Ng 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, 1100000000.get(00000.tar get. 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;}/*** delete a contact * @ param username */public void deleteContact (String username) {SQLiteDatabase db = dbHelper. getWritableDatabase (); if (db. isOpen () {db. delete (TABLE_NAME, COLUMN_NAME_ID + "=? ", New String [] {username}) ;}}/*** save a contact * @ 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 );}}}




.

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.