近来研究了下android如何制作阅读器,有时间的时候就慢慢的自己实现一个出来。功能包括读取本地txt文件,模拟翻页效果等等。当然,才发现其中的工作量也是蛮大的!把这段时间以来的学习分享下。
这篇文章写的是其中的一个类:BookListActivity
一、获取本地文件以及程序附赠的txt。
1、利用AsyncTask读取本地文件以及程序自带的文本文件,写入到数据库中记录,路径,名称等等。对AsyncTask不懂的同志可以参考这里:http://blog.csdn.net/shensens/article/details/9254839
该部分代码如下
class AsyncSetApprove extends AsyncTask<String, Integer, String>
{
/**
* 获取数据,写入数据库
*/
@Override
protected String doInBackground(String... params) {
if( !isInit )
{
File path = getFilesDir();
String[] strings = getResources().getStringArray(R.array.bookid);// 获取assets目录下的文件列表
for (int i = 0; i < strings.length; i++) {
try {
FileOutputStream out = new FileOutputStream(path + "/" + strings[i]);
BufferedInputStream bufferedIn = new BufferedInputStream(getResources().openRawResource(R.raw.book0 + i));
BufferedOutputStream bufferedOut = new BufferedOutputStream(out);
byte[] data = new byte[2048];
int length = 0;
while ((length = bufferedIn.read(data)) != -1) {
bufferedOut.write(data, 0, length);
}
// 将缓冲区中的数据全部写出
bufferedOut.flush();
// 关闭流
bufferedIn.close();
bufferedOut.close();
sp.edit().putBoolean("isInit", true).commit();
} catch (Exception e) {
e.printStackTrace();
}
}
ArrayList<HashMap<String, String>> insertList = new ArrayList<HashMap<String, String>>();
File[] f1 = path.listFiles();
int len = f1.length;
for (int i = 0; i < len; i++) {
if (f1[i].isFile()) {
if (f1[i].toString().contains(".txt")) {
HashMap<String, String> insertMap = new HashMap<String, String>();
insertMap.put("parent", f1[i].getParent());
insertMap.put("path", f1[i].toString());
insertList.add(insertMap);
}
}
}
SQLiteDatabase bookDB=bookUtil.getWritableDatabase();
bookDB.delete("localbook", "type='" + 2 + "'", null);
for (int i = 0; i < insertList.size(); i++) {
try {
if (insertList.get(i) != null) {
String s = insertList.get(i).get("parent");
String s1 = insertList.get(i).get("path");
String sql1 = "insert into " + "localbook" + " (parent,path" + ", type" + ",now,ready) values('" + s + "','" + s1 + "',2,0,null" + ");";
bookDB.execSQL(sql1);
}
} catch (SQLException e) {
Log.e(TAG, "setApprove SQLException", e)