Android开发系列之数据存储(一)

  Android开发中,数据存储主要有五种:网络、数据库、SharePreferences、文件以及Content Provider.

  . 数据库

   Android中的数据库最常用的是Sqlite. 使用Sqlite进行数据存储,可分为以下几步:

   . 继承SqliteOpenHelper

   . 整理4个构造方法

   . 重写onCreate与onUpgrade 

public class DownDBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "download.db";
    public static final int DATABASE_VERSION = 1;

    public static final String TABLE_NAME = "down_info";

    // /////////////////// TABLE COLUMN

    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_THREAD_ID = "thread_id";
    public static final String COLUMN_URL = "url";
    public static final String COLUMN_START = "start";
    public static final String COLUMN_END = "end";
    public static final String COLUMN_PROGRESS = "progress";

    // ///////////////////// CONTRUCTOR

    public DownDBHelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
    }

    public DownDBHelper(Context context, String name, int version) {
        this(context, name, null, version);
    }

    public DownDBHelper(Context context, String name) {
        this(context, name, DATABASE_VERSION);
    }

    public DownDBHelper(Context context) {
        this(context, DATABASE_NAME);
    }

    // ////////////// OVERRIDE

    @Override
    public void onCreate(SQLiteDatabase db) {

        String creSQL = "CREATE TABLE IF NOT EXISTS" + TABLE_NAME + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + COLUMN_THREAD_ID + "INTEGER," + COLUMN_URL + " CHAR,"
                + COLUMN_START + " INTEGER," + COLUMN_END + "INTEGER,"
                + COLUMN_PROGRESS + "INTEGER)";

        db.execSQL(creSQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        String dropSQL = "DROP TABLE IF EXISTS " + TABLE_NAME;
        db.execSQL(dropSQL);

        this.onCreate(db);
    }

}
View Code

 

   .数据库语法

   Sqlite以增、删、改、查为例,主要语法如下:

   . 插入 insert into 表名 (表字段1,表字段2,...) values (字段值1,字段值2,...)

   .删除  delete from 表名 where 表字段=字段值 //如果字段值为字符或字符串,要以‘  ’ 引用,如 where name='xiaoming'

   .更新 update 表名 set 表字段1=字段值1,表字段2=字段值2,... where 表字段0=字段值0 //凡字段值为字符或字符串,皆以' '引用

   .查询 select 表字段1,表字段2,... from 表名 where 表字段0=字段值0

   .创建表 create table if not exists 表名 (字段1 字段类型,字段2 字段类型,...)

   .销毁表 drop table if exists 表名

 

public class DBDao {

    private static final String TAG = "DownDao";

    private DownDBHelper mDBHelper;

    public DBDao(Context context) {
        mDBHelper = new DownDBHelper(context);
    }

    /**
     * 插入数据
     * 
     * @param data
     */
    public void insert(DownloadInfo data) {

        String insertSQL = "INSERT INTO " + DownDBHelper.TABLE_NAME + "("
                + DownDBHelper.COLUMN_THREAD_ID + "," + DownDBHelper.COLUMN_URL
                + "," + DownDBHelper.COLUMN_START + ","
                + DownDBHelper.COLUMN_END + "," + DownDBHelper.COLUMN_PROGRESS
                + ")" + " VALUES " + "(" + data.threadID + "," + "'"
                + data.downUrl + "'" + "," + data.startPos + "," + data.endPos
                + "," + data.downProgress + ")";

        SQLiteDatabase db = mDBHelper.getWritableDatabase();
        try {
            db.execSQL(insertSQL);
        } catch (SQLException e) {
            Log.e(TAG, "插入记录失败!" + e.getMessage());
        }
    }

    /**
     * 删除记录(根据URL)
     * 
     * @param url
     */
    public void deleteByUrl(String url) {

        String deleteSQL = "DELETE FROM " + DownDBHelper.TABLE_NAME + " WHERE "
                + DownDBHelper.COLUMN_URL + "=" + "'" + url + "'";

        SQLiteDatabase db = mDBHelper.getWritableDatabase();
        try {
            db.execSQL(deleteSQL);
        } catch (SQLException e) {
            Log.e(TAG, "删除记录失败!" + e.getMessage());
        }
    }

    /**
     * 删除记录(根据THREAD_ID)
     * 
     * @param url
     */
    public void deleteByThread(int threadID) {

        String deleteSQL = "DELETE FROM " + DownDBHelper.TABLE_NAME + " WHERE "
                + DownDBHelper.COLUMN_THREAD_ID + "=" + threadID;

        SQLiteDatabase db = mDBHelper.getWritableDatabase();
        try {
            db.execSQL(deleteSQL);
        } catch (SQLException e) {
            Log.e(TAG, "删除记录失败!" + e.getMessage());
        }
    }

    /**
     * 修改记录(根据URL)
     * 
     * @param url
     * @param newProgress
     */
    public void updateByUrl(String url, int newProgress) {

        String updateSQL = "UPDATE " + DownDBHelper.TABLE_NAME + " SET "
                + DownDBHelper.COLUMN_PROGRESS + "=" + newProgress + " WHERE "
                + DownDBHelper.COLUMN_URL + "=" + "'" + url + "'";

        SQLiteDatabase db = mDBHelper.getWritableDatabase();
        try {
            db.execSQL(updateSQL);
        } catch (SQLException e) {
            Log.e(TAG, "修改记录失败!" + e.getMessage());
        }
    }

    /**
     * 修改记录(根据URL)
     * 
     * @param url
     * @param newProgress
     */
    public void updateByThread(int threadID, int newProgress) {

        String updateSQL = "UPDATE " + DownDBHelper.TABLE_NAME + " SET "
                + DownDBHelper.COLUMN_PROGRESS + "=" + newProgress + " WHERE "
                + DownDBHelper.COLUMN_THREAD_ID + "=" + threadID;

        SQLiteDatabase db = mDBHelper.getWritableDatabase();
        try {
            db.execSQL(updateSQL);
        } catch (SQLException e) {
            Log.e(TAG, "修改记录失败!" + e.getMessage());
        }
    }

    /**
     * 查询单条记录(根据线程)
     * 
     * @param url
     * @param newProgress
     */
    public void queryRaw(int threadID) {

        String querySQL = "SELECT " 
                + DownDBHelper.COLUMN_THREAD_ID + ","
                + DownDBHelper.COLUMN_URL + ","
                + DownDBHelper.COLUMN_START + ","
                + DownDBHelper.COLUMN_END + ","
                + DownDBHelper.COLUMN_PROGRESS
                + " FROM " + DownDBHelper.TABLE_NAME
                + " WHERE " + DownDBHelper.COLUMN_THREAD_ID + "=" + threadID;

        SQLiteDatabase db = mDBHelper.getReadableDatabase();
        try {
            db.execSQL(querySQL);
        } catch (SQLException e) {
            Log.e(TAG, "查询记录失败!" + e.getMessage());
        }
    }
    
    /**
     * 查询单条记录(根据URL)
     * 
     * @param url
     * @param newProgress
     */
    public void queryRaw(String url) {

        String querySQL = "SELECT " 
                + DownDBHelper.COLUMN_THREAD_ID + ","
                + DownDBHelper.COLUMN_URL + ","
                + DownDBHelper.COLUMN_START + ","
                + DownDBHelper.COLUMN_END + ","
                + DownDBHelper.COLUMN_PROGRESS
                + " FROM " + DownDBHelper.TABLE_NAME
                + " WHERE " + DownDBHelper.COLUMN_URL + "=" + "'" + url + "'";

        SQLiteDatabase db = mDBHelper.getReadableDatabase();
        try {
            db.execSQL(querySQL);
        } catch (SQLException e) {
            Log.e(TAG, "查询记录失败!" + e.getMessage());
        }
    }
    
    /**
     * 查询记录
     * 
     * @param url
     * @param newProgress
     */
    public void query() {
        
        String querySQL = "SELECT * " + " FROM " + DownDBHelper.TABLE_NAME;
        
        SQLiteDatabase db = mDBHelper.getReadableDatabase();
        try {
            db.execSQL(querySQL);
        } catch (SQLException e) {
            Log.e(TAG, "查询记录失败!" + e.getMessage());
        }
    }
    
    

}
View Code

 

  .Sharepreferences

  Sharepreferences是一种轻型的数据存储方式,通常用于存储简单的配置信息。

   .取得SharedPreferences对象

   .取出

     .直接调用getInt()/getString()等取出数据

   .写入

     .取得Editor对象

     .调用putInt()/putString()等写入数据

     .调用commit()提交

public class SharePreferenceUtils {

    private static SharedPreferences mSpreference;

    /**
     * 初始化
     * 
     * @param context
     */
    public static void init(Context context) {
        if (mSpreference == null) {
            mSpreference = PreferenceManager
                    .getDefaultSharedPreferences(context);
        }
    }

    /**
     * 添加Int型数据
     * 
     * @param context
     * @param key
     * @param value
     */
    public static void putSpreferenceData_Integer(Context context, String key,
            int value) {
        if (mSpreference == null) {
            init(context);
        }
        mSpreference.edit().putInt(key, value).commit();
    }

    /**
     * 添加String型数据
     * 
     * @param context
     * @param key
     * @param value
     */
    public static void putSpreferenceData_String(Context context, String key,
            String value) {
        if (mSpreference == null) {
            init(context);
        }
        mSpreference.edit().putString(key, value).commit();
    }

    /**
     * 添加Boolean型数据
     * 
     * @param context
     * @param key
     * @param value
     */
    public static void putSpreferenceData_Boolean(Context context, String key,
            boolean value) {
        if (mSpreference == null) {
            init(context);
        }
        mSpreference.edit().putBoolean(key, value).commit();
    }

    /**
     * 添加Float型数据
     * 
     * @param context
     * @param key
     * @param value
     */
    public static void putSpreferenceData_Float(Context context, String key,
            float value) {

        if (mSpreference == null) {
            init(context);
        }
        mSpreference.edit().putFloat(key, value).commit();
    }

    /**
     * 添加Long型数据
     * 
     * @param context
     * @param key
     * @param value
     */
    public static void putSpreferenceData_Long(Context context, String key,
            long value) {
        if (mSpreference == null) {
            init(context);
        }
        mSpreference.edit().putLong(key, value).commit();
    }

    /**
     * 获取Int型数据
     * 
     * @param context
     * @param key
     * @return 默认-1
     */
    public static int getSpreferenceData_Integer(Context context, String key) {
        if (mSpreference == null) {
            init(context);
        }
        return mSpreference.getInt(key, -1);
    }

    /**
     * 获取String型数据
     * 
     * @param context
     * @param key
     * @return 默认 null
     */
    public static String getSpreferenceData_String(Context context, String key) {
        if (mSpreference == null) {
            init(context);
        }
        return mSpreference.getString(key, null);
    }

    /**
     * 获取Boolean型数据
     * 
     * @param context
     * @param key
     * @return 默认 false
     */
    public static boolean getSpreferenceData_Boolean(Context context, String key) {
        if (mSpreference == null) {
            init(context);
        }
        return mSpreference.getBoolean(key, false);
    }

    /**
     * 获取Float型数据
     * 
     * @param context
     * @param key
     * @return 默认 -1f
     */
    public static float getSpreferenceData_Float(Context context, String key) {
        if (mSpreference == null) {
            init(context);
        }
        return mSpreference.getFloat(key, -1f);
    }

    /**
     * 获取Long型数据
     * 
     * @param context
     * @param key
     * @return 默认 -1l
     */
    public static long getSpreferenceData_Long(Context context, String key) {
        if (mSpreference == null) {
            init(context);
        }
        return mSpreference.getLong(key, -1l);
    }

}
View Code

 

 .文件

   文件存储方式在Android开发中几乎是必不可少的,常用的文件磁盘缓存,字符串文件缓存以及xml文件缓存等。

   .文件读写 文件的读写主要有几种:多媒体文件以流的形式,文本文件以字符串的形式等。

   .将流写入文件

/**
     * 将InputStream保存到文件
     * 
     * @param context
     * @param in
     * @param fileLength
     * @param savDir
     * @param savName
     */
    public static void writeStream2File(Context context, InputStream in,
            long fileLength, String savDir, String savName) {

        if (in == null) {
            return;
        }
        if (StringUtils.isEmpty(savDir) || StringUtils.isEmpty(savName)) {
            return;
        }
        if (!canWrite(context, fileLength)) {
            return;
        }
        File dirFile = new File(savDir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File savFile = new File(savDir, savName);
        try {
            if (savFile.exists()) {
                savFile.deleteOnExit();
            }
            savFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(savFile);
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            fos.close();
            fos = null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                    fos = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
View Code

   .将文件转化为流

public InputStream getInputStream(String path) {

   if(StringUtils.isEmpty(path)){

          return null;
    }

    File file = new File(path);
    if(!file.exists) {
        return null;
     }

     return new FileInputStream(file);   
}
View Code

  .将字符串写入文件

/**
     * 将String保存到文件
     * 
     * @param context
     * @param content
     * @param dirPath
     * @param fileName
     * @param append
     *            写入形式:true-追加写入 、false-重新写入
     * @return
     */
    public static boolean writeString2File(Context context, String content,
            String dirPath, String fileName, boolean append) {

        if (StringUtils.isEmpty(content)) {
            return false;
        }
        if (StringUtils.isEmpty(dirPath) || StringUtils.isEmpty(fileName)) {
            return false;
        }
        File file = new File(dirPath, fileName);
        if (!file.exists()) {
            try {
                createNewDir(context, dirPath);
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(file, append);
            fileWriter.write(content);
            fileWriter.close();
            fileWriter = null;
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileWriter != null) {
                    fileWriter.close();
                    fileWriter = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
View Code

  .从文件读取字符串

/**
     * 读取文件
     * 
     * @param context
     * @param filePath
     * @param charsetName
     * @return
     */
    public static StringBuilder readFile(Context context, File file,
            String charsetName) {
        if (file != null && file.exists() && SDCardUtils.sdcardExists()) {
            if (StringUtils.isEmpty(charsetName)) {
                charsetName = "UTF-8";
            }
            StringBuilder fileContent = new StringBuilder();
            BufferedReader reader = null;
            InputStreamReader is = null;
            try {
                is = new InputStreamReader(new FileInputStream(file),
                        charsetName);
                reader = new BufferedReader(is);
                String line = null;
                while ((line = reader.readLine()) != null) {
                    if (!fileContent.toString().equals("")) {
                        fileContent.append("\r\n");
                    }
                    fileContent.append(line);
                }
                is.close();
                reader.close();
                is = null;
                reader = null;
                return fileContent;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (is != null) {
                        is.close();
                        is = null;
                    }
                    if (reader != null) {
                        reader.close();
                        reader = null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
View Code

  .将文件转化为Base64字符串

/**
     * 文件转化Base64 String
     * 
     * @param path
     *            文件完整路径
     * @return
     */
    public static String encodeFileByBase64(Context context, String dirPath,
            String fileName) {

        if (StringUtils.isEmpty(dirPath) || StringUtils.isEmpty(fileName)) {
            return null;
        }
        File file = new File(dirPath, fileName);
        if (!file.exists()) {
            return null;
        }
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        try {
            fis = new FileInputStream(file);
            bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = fis.read(buffer)) >= 0) {
                bos.write(buffer, 0, len);
            }
            String base64String = new String(Base64.encodeToString(
                    bos.toByteArray(), Base64.DEFAULT));
            fis.close();
            bos.close();
            fis = null;
            bos = null;
            return base64String;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                    fis = null;
                }
                if (bos != null) {
                    bos.close();
                    bos = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
View Code

  .将Base64字符串解析到文件

/**
     * Base64编码String解析到文件
     * 
     * @param context
     * @param content
     * @param dirPath
     * @param fileName
     * @return
     */
    public static boolean decode2FileByBase64(Context context, String content,
            String dirPath, String fileName) {

        if (StringUtils.isEmpty(content) || StringUtils.isEmpty(dirPath)
                || StringUtils.isEmpty(fileName)) {
            return false;
        }
        File file = new File(dirPath, fileName);
        try {
            if (file.exists()) {
                file.deleteOnExit();
                file.createNewFile();
            } else {
                createNewDir(context, dirPath);
                file.createNewFile();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        byte[] buffer = Base64.decode(content, Base64.DEFAULT);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(buffer);
            fos.close();
            fos = null;
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    fos = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
View Code

 

     

 

 

 

    

    

    

    

posted @ 2015-02-26 11:20  KipMeister  阅读(250)  评论(0)    收藏  举报