程序猿是最懒的生物,开发中从不重复造轮子,实际开发中数据吃就化是必然要处理的一个问题,先总结了几个除处理sqlite外的几个工具类,因为sqlite可以直接用orm,持久化数据有I/O,SharedPreference等等方式。
外置储存卡
- package cn.edu.zafu.utils;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import android.os.Environment;
- /**
- * 外部存儲卡工具类
- * 需要添加权限
- * android.permission.WRITE_EXTERNAL_STORAGE
- * android.permission.MOUNT_UNMOUNT_FILESYSTEMS
- *
- * @author lizhangqu
- * @version 1.0
- *
- */
- public class ExternalStorageUtil {
- /**
- * 是否可写
- *
- * @return 可写性
- */
- public static boolean isExternalStorageWritable() {
- String state = Environment.getExternalStorageState();
- if (Environment.MEDIA_MOUNTED.equals(state)) {
- return true;
- }
- return false;
- }
- /**
- * 是否可读
- *
- * @return 可读性
- */
- public static boolean isExternalStorageReadable() {
- String state = Environment.getExternalStorageState();
- if (Environment.MEDIA_MOUNTED.equals(state)
- || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
- return true;
- }
- return false;
- }
- /**
- * 获得根路径
- *
- * @return 外置内存卡根路径
- */
- public static String getExternalStoragePath() {
- if (isExternalStorageWritable())
- return Environment.getExternalStorageDirectory().getAbsolutePath();
- else
- return null;
- }
- /**
- * 获得下载目录路径
- *
- * @return 外置内存卡下载路径
- */
- public static String getExternalDownloadPath() {
- return Environment.getExternalStoragePublicDirectory(
- Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
- }
- /**
- * 向根路径写文件
- *
- * @param fileName 文件名
- * @param content 上下文
- * @return 是否写入成功
- */
- public static boolean write(String fileName, String content) {
- return write("/", fileName, content);
- }
- /**
- * 向根目录写字节
- *
- * @param fileName 文件名
- * @param bytes 文件字节数组
- * @return 是否写入成功
- */
- public static boolean writeBytes(String fileName, byte[] bytes) {
- return writeBytes("/", fileName, bytes);
- }
- /**
- * 向指定目录的文件中写入字符串,路径以/开始/结尾
- *
- * @param path 相对于根路径的路径,路径以/开始,以/结尾
- * @param fileName 文件名
- * @param content 文件内容
- * @return 是否写入成功
- */
- public static boolean write(String path, String fileName, String content) {
- return writeBytes(path, fileName, content.getBytes());
- }
- /**
- * 向指定目录的文件写入字节数组,路径以/开始/结尾
- *
- * @param path 相对于根路径的路径,路径以/开始,以/结尾
- * @param fileName 文件名
- * @param bytes 字节数组
- * @return
- */
- public static boolean writeBytes(String path, String fileName, byte bytes[]) {
- boolean flag = false;
- if (!path.equals("/")) {
- File dir = new File(getExternalStoragePath() + path);
- if (!dir.exists()) {
- if (!(dir.mkdir() || dir.isDirectory())) {
- // 文件目录创建失败或者不是一个目录
- return false;
- }
- }
- }
- File file = new File(getExternalStoragePath() + path + fileName);
- FileOutputStream fos = null;
- try {
- fos = new FileOutputStream(file, false);
- fos.write(bytes);
- flag = true;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (fos != null) {
- try {
- fos.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return flag;
- }
- /**
- * 从根路径读字节
- *
- * @param fileName 文件名
- * @return 字节数组
- */
- public static byte[] readBytes(String fileName) {
- return readBytes("/", fileName);
- }
- /**
- * 从指定目录读字节,路径以/开始/结尾
- *
- * @param path 相对于根路径的路径,路径以/开始,以/结尾
- * @param fileName 文件名
- * @return 字节数组
- */
- public static byte[] readBytes(String path, String fileName) {
- File file = new File(getExternalStoragePath() + path + fileName);
- if (!file.isFile()) {
- return null;
- } else {
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(file);
- int length = fis.available();
- byte[] buffer = new byte[length];
- fis.read(buffer);
- return buffer;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (fis != null) {
- try {
- fis.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return null;
- }
- }
- /**
- * 从根目录读文本
- *
- * @param fileName 文件名
- * @return 字符串
- */
- public static String read(String fileName) {
- return read("/", fileName);
- }
- /**
- * 从指定目录读文本,路径以/开始/结尾
- *
- * @param path 相对于根路径的路径,路径以/开始,以/结尾
- * @param fileName 文件名
- * @return 字符串
- */
- public static String read(String path, String fileName) {
- try {
- byte[] readBytes = readBytes(path, fileName);
- if (readBytes == null) {
- return null;
- }
- return new String(readBytes, "UTF-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * 从根目录删除
- *
- * @param fileName 文件名
- * @return 是否删除成功
- */
- public static boolean delete(String fileName) {
- return delete("/", fileName);
- }
- /**
- * 从指定目录删除,路径以/开始/结尾
- *
- * @param path 相对于根路径的路径,路径以/开始,以/结尾
- * @param fileName 文件名
- * @return 是否删除成功
- */
- public static boolean delete(String path, String fileName) {
- File file = new File(getExternalStoragePath() + path + fileName);
- if (file.exists())
- return file.delete();
- else
- return true;
- }
- }
内置储存卡
- package cn.edu.zafu.utils;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import android.content.Context;
- /**
- * 內部存儲卡工具类
- *
- * @author lizhangqu
- * @version 1.0
- */
- public class InternalStorageUtil {
- /**
- * 在原文件后追加内容
- *
- * @param context 上下文
- * @param fileName 文件名
- * @param content 追加的文本
- * @return 是否追加成功
- */
- public static boolean append(Context context, String fileName,
- String content) {
- return writeBytes(context, fileName, content.getBytes(), true);
- }
- /**
- * 写入文件,文件存在则覆盖
- *
- * @param context 上下文
- * @param fileName 文件名
- * @param content 写入的文本
- * @return 是否写入成功
- */
- public static boolean write(Context context, String fileName, String content) {
- return writeBytes(context, fileName, content.getBytes(), false);
- }
- /**
- * 写入字节
- *
- * @param context 上下文
- * @param fileName 文件名
- * @param content 写入的字节
- * @return 是否写入成功
- */
- public static boolean writeBytes(Context context, String fileName,
- byte[] content) {
- return writeBytes(context, fileName, content, false);
- }
- /**
- * 写入文件,文件存在时根据参数isAppend判断是否覆盖
- *
- * @param context 上下文
- * @param fileName 文件名
- * @param content 写入的字节
- * @param isAppend 是否追加
- * @return 是否写入成功
- */
- public static boolean writeBytes(Context context, String fileName,
- byte[] content, boolean isAppend) {
- FileOutputStream fout = null;
- boolean flag = false;
- try {
- if (isAppend) {
- fout = context.openFileOutput(fileName, Context.MODE_APPEND);
- } else {
- fout = context.openFileOutput(fileName, Context.MODE_PRIVATE);
- }
- fout.write(content);
- flag = true;
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (fout != null) {
- fout.close();
- fout = null;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return flag;
- }
- /**
- * 读取文件
- *
- * @param context 上下文
- * @param fileName 文件名
- * @return 文件内容的字符串
- */
- public static String read(Context context, String fileName) {
- byte[] buffer = readBytes(context, fileName);
- String result=null;
- try {
- result = new String(buffer, "UTF-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return result;
- }
- /**
- * @param context 上下文
- * @param fileName 文件名
- * @return 字节数组
- */
- public static byte[] readBytes(Context context, String fileName) {
- FileInputStream fin = null;
- byte[] buffer = null;
- try {
- fin = context.openFileInput(fileName);
- int length = fin.available();
- buffer = new byte[length];
- fin.read(buffer);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (fin != null) {
- fin.close();
- fin = null;
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return buffer;
- }
- /**
- * 清除所有文件,当有一个文件未清除时返回false
- *
- * @param context 上下文
- * @return 是否清楚成功
- */
- public static boolean clear(Context context) {
- boolean flag = true;
- String[] files = context.fileList();
- for (String fileName : files) {
- boolean result = context.deleteFile(fileName);
- if (result == false) {
- flag = false;
- }
- }
- return flag;
- }
- /**
- * 根据文件名清除文件
- *
- * @param context 上下文
- * @param fileName 文件名
- * @return 是否删除成功
- */
- public static boolean delete(Context context, String fileName) {
- return context.deleteFile(fileName);
- }
- /**
- * 返回内部存储的绝对路径
- *
- * @param context 上下文
- * @return app内置文件夹路径
- */
- public static String getFileDir(Context context) {
- File filesDir = context.getFilesDir();
- return filesDir.getAbsolutePath();
- }
- }
- package cn.edu.zafu.utils;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.UnsupportedEncodingException;
- import android.content.Context;
- /**
- * assert资源的读取
- *
- * @author lizhangqu
- * @version 1.0
- */
- public class ResouceFileUtil {
- /**
- * 从assert文件夹下读取文本资源
- *
- * @param context 上下文
- * @param fileName 文件名
- * @return 文件内容字符串
- */
- public static String readStringFromAssert(Context context, String fileName) {
- String result = null;
- byte[] buffer = readBytesFromAssert(context, fileName);
- try {
- result = new String(buffer, "UTF-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return result;
- }
- /**
- * 从raw文件夹下读取文本资源
- *
- * @param context 上下文
- * @param rawId raw资源id
- * @return 文件内容字符串
- */
- public static String readStringFromRaw(Context context, int rawId) {
- String result = null;
- byte[] buffer = readBytesFromRaw(context, rawId);
- try {
- result = new String(buffer, "UTF-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return result;
- }
- /**
- * 从assert文件夹下读取文件到字节数组
- *
- * @param context 上下文
- * @param fileName 文件名
- * @return 文件字节数组
- */
- public static byte[] readBytesFromAssert(Context context, String fileName) {
- InputStream is = null;
- byte[] buffer = null;
- try {
- is = context.getAssets().open(fileName);
- int size = is.available();
- buffer = new byte[size];
- is.read(buffer);
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (is != null) {
- try {
- is.close();
- is = null;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return buffer;
- }
- /**
- * 从raw文件夹下读取文件到字节数组
- *
- * @param context 上下文
- * @param rawId raw资源id
- * @return 文件字节数组
- */
- public static byte[] readBytesFromRaw(Context context, int rawId) {
- InputStream is = null;
- byte[] buffer = null;
- try {
- is = context.getResources().openRawResource(rawId);
- int size = is.available();
- buffer = new byte[size];
- is.read(buffer);
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- if (is != null) {
- try {
- is.close();
- is = null;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- return buffer;
- }
- }
SharedPreference的操作
- package cn.edu.zafu.utils;
- import android.content.Context;
- import android.content.SharedPreferences;
- /**
- * SharedPreference方式持久化数据的工具类
- *
- * @author lizhangqu
- * @version 1.0
- */
- public class SharedPreferenceUtil {
- /**
- * 保存键值对
- *
- * @param context 上下文
- * @param fileName 文件名
- * @param key 键
- * @param value 值
- * @return 是否保存成功
- */
- public static boolean set(Context context, String fileName, String key,
- String value) {
- SharedPreferences sharedPreferences = context.getSharedPreferences(
- fileName, Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = sharedPreferences.edit();
- editor.putString(key, value);
- return editor.commit();
- }
- /**
- * 获得键对应的值,如果没有则返回""
- *
- * @param context 上下文
- * @param fileName 文件名
- * @param key 键
- * @return 值,没有则返回""
- */
- public static String get(Context context, String fileName, String key) {
- return get(context, fileName, key, "");
- }
- /**
- * 获得键对应的值,如果没有则返回defaultValue
- *
- * @param context 上下文
- * @param fileName 文件名
- * @param key 键
- * @param defaultValue 默认值
- * @return 值,没有则返回defaultValue
- */
- public static String get(Context context, String fileName, String key,
- String defaultValue) {
- SharedPreferences sharedPreferences = context.getSharedPreferences(
- fileName, Context.MODE_PRIVATE);
- String value = sharedPreferences.getString(key, defaultValue);// 第二个参数为默认值
- return value;
- }
- /**
- * 移除一项
- * @param context 上下文
- * @param fileName 文件名
- * @param key 键
- * @return 是否移除成功
- */
- public static boolean remove(Context context, String fileName, String key) {
- SharedPreferences sharedPreferences = context.getSharedPreferences(
- fileName, Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = sharedPreferences.edit();
- editor.remove(key);
- return editor.commit();
- }
- /**
- * 清除文件内容
- * @param context 上下文
- * @param fileName 文件名
- * @return 是否清除成功
- */
- public static boolean clear(Context context, String fileName) {
- SharedPreferences sharedPreferences = context.getSharedPreferences(
- fileName, Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = sharedPreferences.edit();
- editor.clear();
- return editor.commit();
- }
- /**
- * 某一项是否存在
- * @param context 上下文
- * @param fileName 文件名
- * @param key 键
- * @return 该键对应的值是否存在
- */
- public static boolean contatins(Context context, String fileName,String key) {
- SharedPreferences sharedPreferences = context.getSharedPreferences(
- fileName, Context.MODE_PRIVATE);
- return sharedPreferences.contains(key);
- }
- }
对烦人的findViewById说再见
下面的这个函数参考自一条微博
- public <T extends View> T $(int id) {
- return (T) findViewById(id);
- }
<T extends View>说明这是一个泛型方法,并且这个泛型是View的子类,返回值是泛型T,函数名借鉴JQuery,使用美元符$
实例调用代码
- TextView tv=$(R.id.tv);
为了避免在每个Activity中重复写这个函数,可以写一个自己的MyActivity类继承Activity,实现该方法,以后的所有Activity继承自己的MyActivity类即可。在一定程度上减少了findViewById函数的书写,不得不说程序猿是世界上最懒的生物,总是想尽千方百计偷懒!
LayoutInflate的三种用法
在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById()。不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;而findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等)。 具体作用:
1、对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;
2、对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素。
LayoutInflater 是一个抽象类,在文档中如下声明:
public abstract class LayoutInflater extends Object
获得 LayoutInflater 实例的三种方式:
- 1.LayoutInflater inflater = getLayoutInflater(); //调用Activity的getLayoutInflater()
- 2.LayoutInflater localinflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- 3. LayoutInflater inflater = LayoutInflater.from(context);
其实,这三种方式本质是相同的,从源码中可以看出:
getLayoutInflater():
Activity 的 getLayoutInflater() 方法是调用 PhoneWindow 的getLayoutInflater()方法,看一下该源代码:
- public PhoneWindow(Context context) {
- super(context);
- mLayoutInflater = LayoutInflater.from(context);
- }
可以看出它其实是调用 LayoutInflater.from(context)。
LayoutInflater.from(context):
- public static LayoutInflater from(Context context) {
- LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- if (LayoutInflater ==null) {
- throw new AssertionError("LayoutInflater not found.");
- }
- return LayoutInflater;
- }
可以看出它其实调用 context.getSystemService()。
结论:所以这三种方式最终本质是都是调用的Context.getSystemService()。
inflate 方法 通过 sdk 的 api 文档,可以知道该方法有以下几种过载形式,返回值均是 View 对象,如下:
- public View inflate (int resource, ViewGroup root);
- public View inflate (XmlPullParser parser, ViewGroup root);
- public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot);
- public View inflate (int resource, ViewGroup root, boolean attachToRoot);
- LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
- View view = inflater.inflate(R.layout.custom, (ViewGroup)findViewById(R.id.test));
- //EditText editText = (EditText)findViewById(R.id.content);
- // error
- EditText editText = (EditText)view.findViewById(R.id.content);
对于上面代码,指定了第二个参数 ViewGroup root,当然你也可以设置为 null 值。
注意:
·inflate方法与 findViewById 方法不同;
·inflater 是用来找 res/layout下的 xml 布局文件,并且实例化;
·findViewById() 是找具体 xml 布局文件中的具体 widget 控件(如:Button、TextView 等)。