2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Android SQLiteのDAOを作ってみた

Last updated at Posted at 2015-02-14

#SQLiteのDAOをつくってみた
初投稿なので数年前に書いたコードをザックリと公開します。

Androidのデータベースアクセスオブジェクトです。
検索だけ実装しました

##コード

###使い方

//出力カラムの情報
HashMap<String,String> outputInfo = new HashMap<String,String>();
outputInfo.put("COLUMNS","ID,NAME,AGE");
outputInfo.put("FROM","USER_INFO");


//検索条件の情報
HashMap<String,String> searchInfo = new HashMap<String,String>();
searchInfo.put("WHERE","ID>30 AND ID<50");

//検索
HashMap<String,String> resultMap = selectList(activty,outputInfo,searchInfo);

###DAO定義


public static List<HashMap<String,String>> selectList(Context con , HashMap<String,String> outMap,HashMap<String,String> inMap) {
        
        String SELECT_BASIC = " select "+ outMap.get("COLUMNS") + " from " + inMap.get("FROM");
        if(inMap.get("WHERE") != null) {
            SELECT_BASIC = SELECT_BASIC + " WHERE " + inMap.get("WHERE");
        }
        if(inMap.get("ORDERASC") != null) {
            SELECT_BASIC = SELECT_BASIC + " ORDER BY " + inMap.get("ORDERASC") + " ASC";
        }
        if(inMap.get("ORDERDESC") != null) {
            SELECT_BASIC = SELECT_BASIC +" ORDER BY " +  inMap.get("ORDERDESC") + " DESC";
        }
        Log.d(Systems.GAME_TITLE,""+SELECT_BASIC);
        
        
        DBAdapter dba = new DBAdapter(con);
        SQLiteDatabase db = dba.getWritableDatabase();
        
        String sql = SELECT_BASIC;
        Cursor cursor = null;
        cursor = db.rawQuery(sql,null);
        
        int count = cursor.getCount();
        Log.d(Systems.GAME_TITLE,"SQL_RECORD_COUNT:"+count);
        //取得できなかった場合、nullを返す。
        if(count == 0) {
            return null;
        }
        //結果を格納
        List<HashMap<String,String>> result = new ArrayList<HashMap<String,String>>();
        while(cursor.moveToNext()){
            //Log.d(Systems.GAME_TITLE,"SQL_COLUMNS_COUNT:"+cursor.getColumnCount());
            count = cursor.getColumnCount();
            HashMap<String,String> tmp = new HashMap<String,String>();
            int i = 0;
            while(true){
                if((count) > i){
                    tmp.put(cursor.getColumnName(i),cursor.getString(i));
                    i++;
                }else{
                    break;
                }
            }
            result.add(tmp);
        }
        //db.commit();
        db.close();
        
        return result;
    }

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?