Android之工具类封装

这篇博客介绍了Android开发中常用的三个工具类:ResourceUtils用于方便地从raw和assets目录读取文件内容;ParcelUtils提供便利的从parcel读取和写入特殊类型数据的方法;TimeUtils包含了一系列时间处理功能。通过这些工具类,可以简化Android应用的开发工作。
摘要由CSDN通过智能技术生成

ResourceUtils

Android Resource工具类,可用于从android资源目录的raw和assets目录读取内容,如:
geFileFromAssets(Context context, String fileName) 得到assets目录下某个文件内容
geFileFromRaw(Context context, int resId) 得到raw目录下某个文件内容


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;

/**
 * ResourceUtils
 */
public class ResourceUtils {
   

    private ResourceUtils() {
        throw new AssertionError();
    }

    /**
     * get an asset using ACCESS_STREAMING mode. This provides access to files that have been bundled with an
     * application as assets -- that is, files placed in to the "assets" directory.
     * 
     * @param context
     * @param fileName The name of the asset to open. This name can be hierarchical.
     * @return
     */
    public static String geFileFromAssets(Context context, String fileName) {
        if (context == null || StringUtils.isEmpty(fileName)) {
            return null;
        }

        StringBuilder s = new StringBuilder("");
        try {
            InputStreamReader in = new InputStreamReader(context.getResources().getAssets().open(fileName));
            BufferedReader br = new BufferedReader(in);
            String line;
            while ((line = br.readLine()) != null) {
                s.append(line);
            }
            return s.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * get content from a raw resource. This can only be used with resources whose value is the name of an asset files
     * -- that is, it can be used to open drawable, sound, and raw resources; it will fail on string and color
     * resources.
     * 
     * @param context
     * @param resId The resource identifier to open, as generated by the appt tool.
     * @return
     */
    public static String geFileFromRaw(Context context, int resId) {
        if (context == null) {
            return null;
        }

        StringBuilder s = new StringBuilder();
        try {
            InputStreamReader in = new InputStreamReader(context.getResources().openRawResource(resId));
            BufferedReader br = new BufferedReader(in);
            String line;
            while ((line = br.readLine()) != null) {
                s.append(line);
            }
            return s.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * same to {@link ResourceUtils#geFileFromAssets(Context, String)}, but return type is List<String>
     * 
     * @param context
     * @param fileName
     * @return
     */
    public static List<String> geFileToListFromAssets(Context context, String fileName) {
        if (context == null || StringUtils.isEmpty(fileName)) {
            return null;
        }

        List<String> fileContent = new ArrayList<String>();
        try {
            InputStreamReader in = new InputStreamReader(context.getResources().getAssets().open(fileName));
            BufferedReader br = new BufferedReader(in);
            String line;
            while ((line = br.readLine()) != null) {
                fileContent.add(line);
            }
            br.close();
            return fileContent;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * same to {@link ResourceUtils#geFileFromRaw(Context, int)}, but return type is List<String>
     * 
     * @param context
     * @param resId
     * @return
     */
    public static List<String> geFileToListFromRaw(Context context, int resId) {
        if (context == null) {
            return null;
        }

        List<String> fileContent = new ArrayList<String>();
        BufferedReader reader = null;
        try {
            InputStreamReader in = new InputStreamReader(context.getResources().openRawResource(resId));
            reader = new BufferedReader(in);
            String line = null;
            while ((line = reader.readLine()) != null) {
                fileContent.add(line);
            }
            reader.close();
            return fileContent;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}   

ParcelUtils

Android Parcel工具类,可用于从parcel读取或写入特殊类型数据,如:

    readBoolean(Parcel in) 从pacel中读取boolean类型数据

    readHashMap(Parcel in, ClassLoader loader) 从pacel中读取map类型数据
    writeBoolean(boolean b, Parcel out) 向parcel中写入boolean类型数据        
    writeHashMap(Map<K, V> map, Parcel out, int flags) 向parcel中写入map类型数据
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * ParcelUtils
 */
public class ParcelUtils {
   

    private ParcelUtils() {
        throw new AssertionError();
    }

    /**
     * read boolean
     * 
     * @param in
     * @return
     */
    public static boolean readBoolean(Parcel in) {
        return in.readInt() == 1;
    }

    /**
     * write boolean
     * 
     * @param b
     * @param out
     */
    public static void writeBoolean(boolean b, Parcel out) {
        out.writeInt(b ? 1 : 0);
    }

    /**
     * Read a HashMap from a Parcel, class of key and value are both String
     * 
     * @param in
     * @return
     */
    public static Map<String, String> readHashMapStringAndString(Parcel in) {
        if (in == null) {
            return null;
        }

        int size = in.readInt();
        if (size == -1) {
            return null;
        }

        Map<String, String> map = new HashMap<String, String>();
        for (int i = 0; i < size; i++) {
            String key = in.readString();
            map.put(key, in.readString());
        }
        return map;
    }

    /**
     * Write a HashMap to a Parcel, class of key and value are both String
     * 
     * @param map
     * @param out
     * @param flags
     */
    public static void writeHashMapStringAndString(Map<String, String> map, Parcel out, int flags) {
        if (map != null) {
            out.writeInt(map.size());
            for (Entry<String, String> entry : map.entrySet()) {
                out.writeString(entry.getKey());
                out.writeString(entry.getValue());
            }
        } else {
            out.writeInt(-1);
        }
    }

    /**
     * Read a HashMap from a Parcel, class of key is String, class of Value can parcelable
     * 
     * @param <V>
     * @param in
     * @param loader
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <V extends Parcelable> Map<String, V> readHashMapStringKey(Parcel in, ClassLoader loader) {
        if (in == null) {
            return null;
        }

        int size = in.readInt();
        if (size == -1) {
            return null;
        }

        Map<String, V> map = new HashMap<String, V>();
        for (int i = 0; i < size; i++) {
            String key = in.readString();
            map.put(key, (V)in.readParcelable(loader));
        }
        return map;
    }

    /**
     * Write a HashMap to a Parcel, class of key is String, class of Value can parcelable
     * 
     * @param map
     * @param out
     * @param flags
     */
    public static <V extends Parcelable> void writeHashMapStringKey(Map<String, V> map, Parcel out, int flags) {
        if (map != null)
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
一个简单的基于Android的Sqlite数据库的操作封装,它有如下的好处:便捷地创建表和增添表字段灵活的数据类型处理通过操作对象来insert或者update表记录支持多种查询方式,支持多表自定义的复杂查询,支持分页查询支持事务快速开始:    1. 设计表:@Table(name="t_user") public class UserModel {     @Table.Column(name="user_id",type=Column.TYPE_INTEGER,isPrimaryKey=true)     public Integer userId;     @Table.Column(name="user_name",type=Column.TYPE_STRING,isNull=false)     public String userName;     @Table.Column(name="born_date",type=Column.TYPE_TIMESTAMP)     public Date bornDate;     @Table.Column(name="pictrue",type=Column.TYPE_BLOB)     public byte[] pictrue;     @Table.Column(name="is_login",type=Column.TYPE_BOOLEAN)     public Boolean isLogin;     @Table.Column(name="weight",type=Column.TYPE_DOUBLE)     public Double weight; }2. 初始化对象:SQLiteDatabase db = context.openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null); DbSqlite dbSqlite = new DbSqlite(db); IBaseDao userDAO = DaoFactory.createGenericDao(dbSqlite, UserModel.class);3. 创建表:userDAO.createTable(); 4. Insert 记录:UserModel user = new UserModel(); user.userName = "darcy"; user.isLogin = true; user.weight = 60.5; user.bornDate = new Date(); byte[] picture = {0x1,0x2,0x3,0x4}; user.pictrue = picture; userDAO.insert(user);5. Update 记录:UserModel user = new UserModel(); user.weight = 88.0; userDAO.update(user, "user_name=?", "darcy");6. 查询://单条结果查询 UserModel user = userDAO.queryFirstRecord("user_name=?", "darcy"); //一般查询 List userList = userDAO.query("user_name=? and weight > ?", "darcy" , "60"); //分页查询 PagingList pagingList = userDAO.pagingQuery(null, null, 1, 3);7. 事务支持:DBTransaction.transact(mDb, new DBTransaction.DBTransactionInterface() {         @Override         public void onTransact() {             // to do                 } };8. 更新表(目前只支持添加字段)@Table(name="t_user" , version=2) //修改表版本 public class UserModel {     //members above...     //new columns     @Table.Column(name="new_column_1",type=Column.TYPE_INTEGER)     public Integer newColumn;     @Table.Column(name="new_column_2",type=Column.TYPE_INTEGER)     public Integer newColumn2; } userDAO.updateTable();缺点和不足:还没支持多对一或者一多的关系没支持联合主键没支持表的外键设计其他...实例:SqliteLookup(Android内查看Sqlite数据库利器): https://github.com/YeDaxia/SqliteLookup 标签:SQLiteUtils
Android 开发中,数据库操作是非常常见的任务。为了方便复用和维护,我们可以将数据库操作封装成一个工具类。以下是一个简单的数据库工具类封装示例: ```java public class DatabaseHelper extends SQLiteOpenHelper { private static final String DATABASE_NAME = "my_database.db"; private static final int DATABASE_VERSION = 1; private static DatabaseHelper instance; private SQLiteDatabase database; private DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } public synchronized static DatabaseHelper getInstance(Context context) { if (instance == null) { instance = new DatabaseHelper(context.getApplicationContext()); } return instance; } public synchronized SQLiteDatabase open() { if (database == null || !database.isOpen()) { database = instance.getWritableDatabase(); } return database; } public synchronized void close() { if (database != null) { database.close(); database = null; } } @Override public void onCreate(SQLiteDatabase db) { // 创建数据库表 db.execSQL("CREATE TABLE my_table (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 数据库升级操作 } } ``` 这个工具类继承自 `SQLiteOpenHelper` 类,重写了 `onCreate` 和 `onUpgrade` 方法,用于创建和升级数据库表。同时,这个工具类使用了单例模式和同步锁来保证数据库的安全性和线程安全性。 使用时,可以通过 `getInstance` 方法获取数据库实例,然后调用 `open` 方法打开数据库,进行相关的增删改查操作。最后要记得调用 `close` 方法关闭数据库连接,释放资源。 ```java DatabaseHelper dbHelper = DatabaseHelper.getInstance(context); SQLiteDatabase db = dbHelper.open(); // 执行增删改查操作 dbHelper.close(); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值