SQLite简介
Google为Andriod的较大的数据处理提供了SQLite,他在数据存储、管理、维护等各方面都相当出色,功能也非常的强大。SQLite具备下列特点:
1.轻量级
使用 SQLite 只需要带一个动态库,就可以享受它的全部功能,而且那个动态库的尺寸想当小。
2.独立性
SQLite 数据库的核心引擎不需要依赖第三方软件,也不需要所谓的“安装”。
3.隔离性
SQLite 数据库中所有的信息(比如表、视图、触发器等)都包含在一个文件夹内,方便管理和维护。
4.跨平台
SQLite 目前支持大部分操作系统,不至电脑操作系统更在众多的手机系统也是能够运行,比如:Android。
5.多语言接口
SQLite 数据库支持多语言编程接口。
6.安全性
SQLite 数据库通过数据库级上的独占性和共享锁来实现独立事务处理。这意味着多个进程可以在同一时间从同一数据库读取数据,但只能有一个可以写入数据。
SQLite具体应用过程
1、为了能够更好的管理和维护数据库,我们会封装一个继承自SQLiteOpenHelper类的数据库操作类,然后以这个类为基础,再封装我们的业务逻辑方法。
DBHelper.java
public class DBHelper extends SQLiteOpenHelper { private static final String TAG = DBHelper.class.getSimpleName(); /** 数据库名* */ public final static String DATABASE_NAME = "launcher.db"; /** 数据库版本 **/ public final static int DATABASE_VERSION = 9; private static DBHelper instance; private DBHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public static DBHelper getHelper(Context context) { if (instance == null) instance = new DBHelper(context); return instance; } public static void resetDBHelper(Context context) { instance = null; DBHelper.getHelper(context); } @Override public void onCreate(SQLiteDatabase db) { createTable(db, MyAppManager.TABLE_NAME, MyAppManager.mAttrs); createTable(db, Settings.TABLE_NAME, Settings.mAttrs); createTable(db, OrderDB.TABLE_NAME, OrderDB.mAttrs); createTable(db, RechargeDB.TABLE_NAME, RechargeDB.mAttrs); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { updateTable(db); } /** * must be override, if not ,it will throw exception when database degradation */ @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub updateTable(db); } private void updateTable(SQLiteDatabase db) { dropTable(db, MyAppManager.TABLE_NAME); dropTable(db, Settings.TABLE_NAME); dropTable(db, OrderDB.TABLE_NAME); dropTable(db, RechargeDB.TABLE_NAME); onCreate(db); } public static boolean createTable(SQLiteDatabase db, String tableName, TableAttrs attrs) { if (attrs == null) { return false; } Set<String> keys = attrs.keySet(); if (keys.size() <= 0) { return false; } StringBuilder builder = new StringBuilder("create table if not exists "); builder.append(tableName); builder.append(" ("); for (String key : keys) { String attr = attrs.getAtrr(key); builder.append(key); builder.append(" "); builder.append(attr); builder.append(","); } builder.deleteCharAt(builder.length() - 1); builder.append(")"); try { db.execSQL(builder.toString()); } catch (SQLiteException e) { Log.e(TAG, e.getMessage()); return false; } return true; } public static boolean dropTable(SQLiteDatabase db, String table) { try { String sql = "drop table if exists " + table; db.execSQL(sql); return true; } catch (Exception e) { e.printStackTrace(); } return false; } public static boolean tableIsExist(SQLiteDatabase db, String tableName) { boolean result = false; Cursor cursor = null; try { String sql = "select count(*) as c from Sqlite_master where type ='table' and name ='" + tableName.trim() + "' "; cursor = db.rawQuery(sql, null); if (cursor.moveToNext()) { int count = cursor.getInt(0); if (count > 0) { result = true; } } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null) cursor.close(); } return result; } }正如上面所述,数据库第一次创建时onCreate方法会被调用,我们可以执行创建表的语句,当系统发现版本变化之后,会调用onUpgrade/onDowngrade方法,我们可以执行修改表结构等语句。
2、然后,我们需要一个DBManager基类,来封装我们所有的基本业务方法,代码如下:
/** * SQLiteOpenHelper 基本实现类 * * @author meto * */ public class DBManager implements BaseColumns { public static String TAG = "DBManager"; /** * 查询表的记录数 * * @param tableName * @param whereSql * @param orderBy * @param db * @return */ public int getCount(String tableName, String whereSql, String orderBy) { Cursor cursor = null; try { SQLiteDatabase db = getSQLiteDatabase(); cursor = db.query(tableName, null, null, null, null, whereSql, orderBy); int count = cursor.getCount(); return count; } catch (Exception e) { Log.e(TAG, "getcount()=>查询表的记录数异常:" + e.getMessage()); } finally { if (cursor != null) cursor.close(); } return 0; } /** * 查询表的记录集 * * @param tableName * @param whereSql * @param orderBy * @param db * @return */ public Cursor select(String tableName, String whereSql, String[] whereValue, String orderBy) { Cursor cursor = null; try { SQLiteDatabase db = getSQLiteDatabase(); /** * query(table, columns, selection, selectionArgs, groupBy, having,orderBy, limit)方法各参数的含义: * table:表名。相当于select语句from关键字后面的部分。如果是多表联合查询,可以用逗号将两个表名分开。 * columns:要查询出来的列名。相当于select语句select关键字后面的部分。 * selection:查询条件子句,相当于select语句where关键字后面的部分,在条件子句允许使用占位符“?” * selectionArgs:对应于selection语句中占位符的值,值在数组中的位置与占位符在语句中的位置必须一致,否则就会有异常。 * groupBy:相当于select语句group by关键字后面的部分 * having:相当于select语句having关键字后面的部分 orderBy:相当于select语句order by关键字后面的部分,如:personid desc, age asc; * limit:指定偏移量和获取的记录数,相当于select语句limit关键字后面的部分。 */ cursor = db.query(tableName, null, whereSql, whereValue, null, null, orderBy); return cursor; } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "select()=>查询表的记录集:" + e.getMessage()); } return null; } /** * 模糊查找 * * @param whereSql * 查找SQL语句 * @param keywords * 对应查找值 * @return */ public Cursor searhByKeyword(String whereSql, String[] keywords) { try { SQLiteDatabase db = getSQLiteDatabase(); Cursor cursor = db.rawQuery(whereSql, keywords); return cursor; } catch (Exception e) { Log.e(TAG, "select()=>模糊查找异常:" + e.getMessage()); } return null; } /** * 播入记录到表 * * @param tableName * @param mReqParams * @param db * @return */ public boolean insert(String tableName, LinkedHashMap<String, Object> mReqParams) { try { SQLiteDatabase db = getSQLiteDatabase(); ContentValues cv = new ContentValues(); for (String key : mReqParams.keySet()) { Object param = mReqParams.get(key); String value = ""; if (param == null) { value = ""; } else { value = param.toString(); } cv.put(key, value); } Log.e(TAG, "cv= "+cv); long row = db.insert(tableName, null, cv); if (row > 0) { return true; } } catch (Exception e) { Log.e(TAG, "insert()=>播入记录到表异常:" + e.getMessage()); } return false; } public boolean insert(String tableName, ContentValues cv) { boolean bOk = false; try { SQLiteDatabase db = getSQLiteDatabase(); long row = db.insert(tableName, null, cv); if (row > 0) { bOk = true; } } catch (Exception e) { Log.e(TAG, "insert()=>播入记录到表异常:" + e.getMessage()); bOk = false; } return bOk; } public boolean update(String tableName, ContentValues cv, String whereClause, String[] whereArgs) { boolean bOk = false; try { SQLiteDatabase db = getSQLiteDatabase(); long row = db.update(tableName, cv, whereClause, whereArgs); if (row > 0) { bOk = true; } } catch (Exception e) { Log.e(TAG, "insert()=>播入记录到表异常:" + e.getMessage()); bOk = false; } return bOk; } /** * 按条件删除记录 * * @param table * @param numer */ public void deleteBySql(String table, String whereSQL, String[] whereValue) { try { SQLiteDatabase db = getSQLiteDatabase(); db.delete(table, whereSQL, whereValue); } catch (Exception e) { Log.e(TAG, "deleteBySql()=>按条件删除记录异常:" + e.getMessage()); } } /** * CN:清空表记录 * @param table */ public void clearFeedTable(String table) { String sql = "DELETE FROM " + table + ";"; SQLiteDatabase db = getSQLiteDatabase(); db.execSQL(sql); revertSeq(table); } /** * CN:还原自增长 * @param table */ private void revertSeq(String table) { String sql = "update sqlite_sequence set seq=0 where name='" + table + "'"; SQLiteDatabase db = getSQLiteDatabase(); db.execSQL(sql); } /** * 执行SQL语句 * * @param sql */ public void execSQL(String sql) { try { SQLiteDatabase db = getSQLiteDatabase(); db.execSQL(sql); } catch (Exception e) { Log.e(TAG, "execSQL()=>异常:" + e.getMessage()); } } /** * 删除表 * * @param tableName * @return */ public boolean dropTable(String tableName) { return DBHelper.dropTable(getSQLiteDatabase(), tableName); } public Boolean isTableExist(String tableName) { return DBHelper.tabbleIsExist(getSQLiteDatabase(), tableName); } protected boolean createTable(String tableName, TableAttrs attrs) { SQLiteDatabase db = getSQLiteDatabase(); return DBHelper.createTable(db, tableName, attrs); } /** * 方法1:检查某表列是否存在 * * @param db * @param tableName * 表名 * @param columnName * 列名 * @return */ public boolean checkColumnExist(String tableName, String columnName) { SQLiteDatabase db = getSQLiteDatabase(); boolean result = false; Cursor cursor = null; try { // 查询一行 cursor = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 0", null); result = cursor != null && cursor.getColumnIndex(columnName) != -1; } catch (Exception e) { Log.e(TAG, "checkColumnExists1..." + e.getMessage()); } finally { if (null != cursor && !cursor.isClosed()) { cursor.close(); } } return result; } /** * 获取数据库操作句柄 * * @return */ public SQLiteDatabase getSQLiteDatabase() { try { SQLiteDatabase db = DBHelper.getHelper(MyApp.mApplication).getWritableDatabase(); return db; } catch (Exception e) { Log.e(TAG, "getSQLiteDatabase()=>获取数据库操作句柄异常:" + e.getMessage()); } return null; } }
3、当然在此之前,我们可以抽象出一个接口BaseColumns,用来定义自增ID:
public interface BaseColumns { /** * The unique ID for a row. * <P>Type: INTEGER (long)</P> */ public static final String ID = "id"; }
4、然后对于每一个具体的数据库业务模块,只需要继承上面的DBManager并实现自己的相关功能即可。
以节目订购功能OrderDB.java为例:
/** * @author john * @created 2016-8-3 */ public class OrderDB extends DBManager { private static String TAG = "OrderDB"; public static final String TABLE_NAME = "order_table"; public static final String ORDER_ID = "id"; public static final String ORDER_PRODUCTNAME = "productname"; public static final String ORDER_PRODUCTPRICE = "productprice"; public static final String ORDER_BUYTIME = "buytime"; private static OrderDB instance; public static final TableAttrs mAttrs = new TableAttrs() { { addAttr(ORDER_ID, "text"); addAttr(ORDER_PRODUCTNAME, "text"); addAttr(ORDER_PRODUCTPRICE, "text"); addAttr(ORDER_BUYTIME, "text"); } }; /** * singleton * * @return */ public static OrderDB getInstance() { if (instance == null) { instance = new OrderDB(); } return instance; } public List<OrderHistoryVO> getAllOrderHistory() { List<OrderHistoryVO> list = new ArrayList<OrderHistoryVO>(); Cursor cursor = select(TABLE_NAME, null, null, null); if (cursor != null) { while (cursor.moveToNext()) { OrderHistoryVO vo = new OrderHistoryVO(); vo.setId(cursor.getInt(0)); vo.setProductName(cursor.getString(1)); vo.setProductPrice(cursor.getInt(2)); vo.setBuyTime(cursor.getString(3)); list.add(vo); } cursor.close(); } return list; } /** * 更新所有数据到表中去 * * @param list */ public void updateAll(List<OrderHistoryVO> list) { if (list != null && list.size() > 0) { clearFeedTable(TABLE_NAME); int len = list.size(); for (int i = 0; i < len; i++) { OrderHistoryVO vo = list.get(i); LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>(); map.put(ORDER_ID, vo.getId()); map.put(ORDER_PRODUCTNAME, vo.getProductName()); map.put(ORDER_PRODUCTPRICE, vo.getProductPrice()); map.put(ORDER_BUYTIME, vo.getBuyTime()); insert(TABLE_NAME, map); } } } }
5、为了方便我们面向对象的使用数据,我们建一个OrderHistoryVO类,OrderHistoryVO是我们的order_table表对应的JavaBean,对应order_table表中的字段,如下:
/** * @author john * @created 2016-7-19 */ public class OrderHistoryVO implements Parcelable { // "id": 12, // "productname": "Asterix en los Juegos Olímpicos", // "productprice": 10, // "buytime": "2016-07-08 11:45:06.0" private int id; private String productName; private int productPrice; private String buyTime; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public int getProductPrice() { return productPrice; } public void setProductPrice(int productPrice) { this.productPrice = productPrice; } public String getBuyTime() { return buyTime; } public void setBuyTime(String buyTime) { this.buyTime = buyTime; } @Override public int describeContents() { // TODO Auto-generated method stub return 0; } @Override public void writeToParcel(Parcel dest, int flags) { // TODO Auto-generated method stub dest.writeInt(id); dest.writeString(productName); dest.writeInt(productPrice); dest.writeString(buyTime); } public static final Parcelable.Creator<OrderHistoryVO> CREATOR = new Parcelable.Creator<OrderHistoryVO>() { @Override public OrderHistoryVO createFromParcel(Parcel source) { // TODO Auto-generated method stub OrderHistoryVO model = new OrderHistoryVO(); model.id = source.readInt(); model.productName = source.readString(); model.productPrice = source.readInt(); model.buyTime = source.readString(); return model; } @Override public OrderHistoryVO[] newArray(int size) { // TODO Auto-generated method stub return new OrderHistoryVO[size]; } }; }
6、这里我们使用LinkedHashMap创建数据库表,LinkedHashMap是HashMap的一个子类,它保留插入的顺序,如果需要输出的顺序和输入时的相同,那么就选用LinkedHashMap。
LinkedHashMap是Map接口的哈希表和链接列表实现,具有可预知的迭代顺序。此实现提供所有可选的映射操作,并允许使用null值和null键。此类不保证映射的顺序,特别是它不保证该顺序恒久不变。
LinkedHashMap实现与HashMap的不同之处在于,后者维护着一个运行于所有条目的双重链接列表。此链接列表定义了迭代顺序,该迭代顺序可以是插入顺序或者是访问顺序。
注意,此实现不是同步的。如果多个线程同时访问链接的哈希映射,而其中至少一个线程从结构上修改了该映射,则它必须保持外部同步。
根据链表中元素的顺序可以分为:按插入顺序的链表,和按访问顺序(调用get方法)的链表。
默认是按插入顺序排序,如果指定按访问顺序排序,那么调用get方法后,会将这次访问的元素移至链表尾部,不断访问可以形成按访问顺序排序的链表。可以重写removeEldestEntry方法返回true值指定插入元素时移除最老的元素。
LinkedHashMap的实现:TableAttrs.java
public class TableAttrs { private Map<String, String> mValues = new LinkedHashMap<String, String>(); public void addAttr(String name, String attr) { mValues.put(name, attr); } public String getAtrr(String name) { return mValues.get(name); } public Set<String> keySet() { return mValues.keySet(); } }
7、最后就是如何使用这些数据操作方法来显示数据
/** * @author john * @created 2016-7-19 */ public class AccountInfoFragment extends SpecialFragment implements OtherKeyDown, KeyCode { private static final String TAG = AccountInfoFragment.class.getSimpleName(); private View mMainView; private TextView mUserId; private TextView mWallet; private ListView mOrderHistoryListView; private ListView mRechargeHistoryListView; private ImageView orderSelector = null; private ImageView rechargeSelector = null; private LinearLayout mContentLayout=null; private LinearLayout noDataView=null; private TextView noDataTxt; private List<OrderHistoryVO> orderHistoryList; private List<RechargeVO> rechargeList; private List<Map<String, Object>> orderHistoryListData = null; private List<Map<String, Object>> rechargeListData = null; private AccountAdapter orderHistoryAdapter = null; private AccountAdapter rechargeHistoryAdapter = null; private static final int ORDER = 0; private static final int RECHARGE = 1; private static final int INIT_DATA=2; private Context mContext = null; private Handler mHandler=new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub super.handleMessage(msg); switch (msg.what) { case INIT_DATA: if(isAdded()) { initData(); } break; default : break; } } }; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); mContext = getActivity(); new MyThread().start(); } class MyThread extends Thread { @Override public void run() { Looper.prepare(); startLoadDataService(); Looper.loop(); } } protected void startLoadDataService() { // TODO Auto-generated method stub try { OrderDB.getInstance().updateAll(getOrderHistoryList()); RechargeDB.getInstance().updateAll(getRechargeList()); orderHistoryList = OrderDB.getInstance().getAllOrderHistory(); Log.e("john", "startLoadDataService orderHistoryList: "+orderHistoryList); rechargeList = RechargeDB.getInstance().getAllRechargeHistory(); Log.e("john", "startLoadDataService rechargeList: "+rechargeList); if(orderHistoryList==null||orderHistoryList.size()==0) { orderHistoryList=getOrderHistoryList(); } if(rechargeList==null||rechargeList.size()==0) { rechargeList=getRechargeList(); } Log.e("john", "============startLoadDataService================"); } catch (Exception e) { // TODO: handle exception orderHistoryList = null; rechargeList = null; } mHandler.sendEmptyMessage(INIT_DATA); } @SuppressWarnings("unchecked") public List<OrderHistoryVO> getOrderHistoryList() { // TODO Auto-generated method stub List<OrderHistoryVO> orderHistoryList = null; ParseResultVO reVO = ServerManager.obtain().requestOrderHistory(Settings.Obtain().getString(Settings.ORDER_HISTORY_URL_NEW)); if (reVO.getResult() == Constant.ParseData_Success) { orderHistoryList = (List<OrderHistoryVO>) reVO.getObj(); } Log.e("john", "mOrderHistoryList: " + orderHistoryList); return orderHistoryList; } @SuppressWarnings("unchecked") public List<RechargeVO> getRechargeList() { // TODO Auto-generated method stub List<RechargeVO> rechargeList = null; ParseResultVO reVO = ServerManager.obtain().requestChargeHistory(Settings.Obtain().getString(Settings.RECHARGE_URL)); if (reVO.getResult() == Constant.ParseData_Success) { rechargeList = (List<RechargeVO>) reVO.getObj(); } Log.e("john", "mRechargeList: " + rechargeList); return rechargeList; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mMainView = inflater.inflate(R.layout.fragment_account_info, null); mUserId = (TextView) mMainView.findViewById(R.id.user_id); mWallet = (TextView) mMainView.findViewById(R.id.wallet); mOrderHistoryListView = (ListView) mMainView.findViewById(R.id.order_history_list); mRechargeHistoryListView = (ListView) mMainView.findViewById(R.id.recharge_history_list); orderSelector = (ImageView) mMainView.findViewById(R.id.selector1); rechargeSelector = (ImageView) mMainView.findViewById(R.id.selector2); mContentLayout=(LinearLayout) mMainView.findViewById(R.id.account_content); noDataView=(LinearLayout) mMainView.findViewById(R.id.view_no_data); noDataTxt=(TextView) mMainView.findViewById(R.id.no_data_txt); noDataTxt.setText(R.string.tips_loading); mContentLayout.setVisibility(View.GONE); noDataView.setVisibility(View.VISIBLE); return mMainView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Log.e("john", "============onActivityCreated================"); } private void initData() { orderHistoryListData = Collections.synchronizedList(new ArrayList<Map<String, Object>>()); rechargeListData = Collections.synchronizedList(new ArrayList<Map<String, Object>>()); String sn = SystemProperty.systemPropertyGet("persist.sys.sn"); sn = String.format(getResources().getString(R.string.STR_USER_ID), sn); mUserId.setText(sn); if (rechargeList != null&&rechargeList.size()>0) { String data = getResources().getString(R.string.STR_WALLET); data = String.format(data, rechargeList.get(0).getWallet()); mWallet.setText(data); if(orderHistoryList==null||(orderHistoryList!=null&&orderHistoryList.size()==0)) { noDataTxt.setText(R.string.STR_NO_ORDER_HISTORY); noDataView.setVisibility(View.VISIBLE); mContentLayout.setVisibility(View.GONE); } else { noDataView.setVisibility(View.GONE); mContentLayout.setVisibility(View.VISIBLE); } } else { noDataTxt.setText(R.string.STR_NO_ACCOUNT); noDataView.setVisibility(View.VISIBLE); mContentLayout.setVisibility(View.GONE); } setOrderData(); setRechargeData(); orderHistoryAdapter = new AccountAdapter(getActivity(), orderHistoryListData, false); mOrderHistoryListView.setAdapter(orderHistoryAdapter); rechargeHistoryAdapter = new AccountAdapter(getActivity(), rechargeListData, true); mRechargeHistoryListView.setAdapter(rechargeHistoryAdapter); } private void setOrderData() { // TODO Auto-generated method stub if (orderHistoryList != null) { mapData(ORDER); } mOrderHistoryListView.setOnKeyListener(orderKeyListener); mOrderHistoryListView.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { orderSelector.animate().translationY(view.getTop()).setDuration(animFlag ? normalDur : noDur).start(); } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } }); } private void setRechargeData() { // TODO Auto-generated method stub if (rechargeList != null) { mapData(RECHARGE); } mRechargeHistoryListView.setOnKeyListener(rechargeKeyListener); mRechargeHistoryListView.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { rechargeSelector.animate().translationY(view.getTop()).setDuration(animFlag ? normalDur : noDur).start(); } @Override public void onNothingSelected(AdapterView<?> parent) { // TODO Auto-generated method stub } }); } private void mapData(int iType) { switch (iType) { case ORDER: orderHistoryListData.clear(); for(int i=0;i< orderHistoryList.size();i++) { Map<String, Object> map = new HashMap<String, Object>(); map.put("id", orderHistoryList.get(i).getId()); map.put("productName", orderHistoryList.get(i).getProductName()); map.put("productPrice", orderHistoryList.get(i).getProductPrice()); map.put("buyTime", orderHistoryList.get(i).getBuyTime()); orderHistoryListData.add(map); } break; case RECHARGE: rechargeListData.clear(); for (int i =0; i < rechargeList.size(); i++) { Map<String, Object> map = new HashMap<String, Object>(); map.put("id", rechargeList.get(i).getId()); map.put("businessOffice", rechargeList.get(i).getBusinessOffice()); map.put("businessWorker", rechargeList.get(i).getBusinessWorker()); map.put("payment", rechargeList.get(i).getPayment()); map.put("chargeTime", rechargeList.get(i).getChargeTime()); rechargeListData.add(map); } break; default: break; } notifyDataSetChanged(); } private void notifyDataSetChanged() { // TODO Auto-generated method stub if(orderHistoryAdapter!=null) { orderHistoryAdapter.notifyData(orderHistoryListData); } if(rechargeHistoryAdapter!=null) { rechargeHistoryAdapter.notifyData(rechargeListData); } } @Override public void onDestroyView() { super.onDestroyView(); } @Override public void onResume() { // TODO Auto-generated method stub // FpanelManager.getInstance(getActivity()).setFpanelMsgDispName(getResources().getString(R.string.STR_ACCOUNT_INFO)); super.onResume(); } private OnKeyListener orderKeyListener = new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { int iSelect=mOrderHistoryListView.getSelectedItemPosition(); if (event.getAction() == KeyEvent.ACTION_DOWN) { if (isNotAvaliableKey()) { return true; } switch (keyCode) { case KEY_UP: if (orderHistoryListData.size() > 0) { if (iSelect==0) { mOrderHistoryListView.setSelection(mOrderHistoryListView.getCount()-1); } else { mOrderHistoryListView.onKeyDown(keyCode, event); } } return true; case KEY_DOWN: if (orderHistoryListData.size() > 0) { if (iSelect ==mOrderHistoryListView.getCount()-1 ) { mOrderHistoryListView.setSelection(0); } else { mOrderHistoryListView.onKeyDown(keyCode, event); } } return true; case KEY_LEFT: return true; case KEY_RIGHT: if (!mRechargeHistoryListView.hasFocus()) { mOrderHistoryListView.setFocusable(false); mOrderHistoryListView.clearFocus(); mRechargeHistoryListView.setFocusable(true); mRechargeHistoryListView.requestFocus(); rechargeSelector.setVisibility(View.VISIBLE); PropertyValuesHolder pivotX = PropertyValuesHolder.ofFloat("pivotX", 0); PropertyValuesHolder scaleX1 = PropertyValuesHolder.ofFloat("scaleX", 1f, 0f); ObjectAnimator.ofPropertyValuesHolder(orderSelector, pivotX, scaleX1).setDuration(animFlag ? normalDur : noDur).start(); PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 0f, 1f); ObjectAnimator.ofPropertyValuesHolder(rechargeSelector, pivotX, scaleX).setDuration(animFlag ? normalDur : noDur).start(); } return true; case KEY_EXIT: case KEY_BACK: onKeyDown(keyCode, event); return true; } } return false; } }; private OnKeyListener rechargeKeyListener = new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { int iSelect=mRechargeHistoryListView.getSelectedItemPosition(); if (event.getAction() == KeyEvent.ACTION_DOWN) { if (isNotAvaliableKey()) { return true; } switch (keyCode) { case KEY_UP: if (rechargeListData.size() > 0) { if (iSelect==0) { mRechargeHistoryListView.setSelection(mRechargeHistoryListView.getCount()-1); } else { mRechargeHistoryListView.onKeyDown(keyCode, event); } } return true; case KEY_DOWN: if (rechargeListData.size() > 0) { if (iSelect ==mRechargeHistoryListView.getCount()-1) { mRechargeHistoryListView.setSelection(0); } else { mRechargeHistoryListView.onKeyDown(keyCode, event); } } return true; case KEY_LEFT: if (!mOrderHistoryListView.hasFocus()) { mRechargeHistoryListView.setFocusable(false); mRechargeHistoryListView.clearFocus(); mOrderHistoryListView.setFocusable(true); mOrderHistoryListView.requestFocus(); orderSelector.setVisibility(View.VISIBLE); PropertyValuesHolder pivotX = PropertyValuesHolder.ofFloat("pivotX", 0); PropertyValuesHolder scaleX1 = PropertyValuesHolder.ofFloat("scaleX", 1f, 0f); ObjectAnimator.ofPropertyValuesHolder(rechargeSelector, pivotX, scaleX1).setDuration(animFlag ? normalDur : noDur).start(); PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 0f, 1f); ObjectAnimator.ofPropertyValuesHolder(orderSelector, pivotX, scaleX).setDuration(animFlag ? normalDur : noDur).start(); } return true; case KEY_RIGHT: return true; case KEY_EXIT: case KEY_BACK: onKeyDown(keyCode, event); return true; } } return false; } }; @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // TODO Auto-generated method stub setAnimFlag(); switch (keyCode) { case KEY_VOLDOWN: case KEY_VOLUP: case KEY_MUTE: case KeyEvent.KEYCODE_VOLUME_MUTE: return true; case KEY_OK: case KEY_CENTER: case KEY_RIGHT: if (!mOrderHistoryListView.hasFocus()) { getActivity().findViewById(R.id.listview_menu).setFocusable(false); getActivity().findViewById(R.id.listview_menu).clearFocus(); mOrderHistoryListView.setFocusable(true); mOrderHistoryListView.requestFocus(); orderSelector.setVisibility(View.VISIBLE); PropertyValuesHolder pivotX = PropertyValuesHolder.ofFloat("pivotX", 0); PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 0f, 1f); ObjectAnimator.ofPropertyValuesHolder(orderSelector, pivotX, scaleX).setDuration(animFlag ? normalDur : noDur).start(); } return true; case KEY_BACK: case KEY_EXIT: PropertyValuesHolder pivotX1 = PropertyValuesHolder.ofFloat("pivotX", 0); PropertyValuesHolder scaleX1 = PropertyValuesHolder.ofFloat("scaleX", 1f, 0f); if (mOrderHistoryListView.hasFocus()) { mOrderHistoryListView.setFocusable(false); mOrderHistoryListView.clearFocus(); getActivity().findViewById(R.id.listview_menu).setFocusable(true); getActivity().findViewById(R.id.listview_menu).requestFocus(); ((ListView) getActivity().findViewById(R.id.listview_menu)).setSelection(0); ObjectAnimator.ofPropertyValuesHolder(orderSelector, pivotX1, scaleX1).setDuration(animFlag ? normalDur : noDur).start(); } else if(mRechargeHistoryListView.hasFocus()) { mRechargeHistoryListView.setFocusable(false); mRechargeHistoryListView.clearFocus(); getActivity().findViewById(R.id.listview_menu).setFocusable(true); getActivity().findViewById(R.id.listview_menu).requestFocus(); ((ListView) getActivity().findViewById(R.id.listview_menu)).setSelection(0); ObjectAnimator.ofPropertyValuesHolder(rechargeSelector, pivotX1, scaleX1).setDuration(animFlag ? normalDur : noDur).start(); } else { getActivity().finish(); // OSDSettingManager.getInstance(getActivity()).setActivityExitAni(getActivity()); } break; default: break; } return false; } }注意,数据库操作不能放在UI线程,否则会导致ANR。