情况:在做ostocy-jshop开源系统的时候,需要做一个关于android如何进行服务器图片本地缓存的功能。我使用了如下几个东西。
1,android 本地数据库SQLite
2,android下载网络图片
3,正则截取
4,Bitmap保存到本地
那就一个一个来说说吧
1,android 本地数据库SQLite:我要建立一个本地数据库,用来存放服务器返回的数据,缓存起来,下次就读取这个SQLite数据库了。
看代码先,然后解释
public class DBHelper extends SQLiteOpenHelper { //数据库名称 public static final String DB_NAME="jshopmactive.db"; //商品表名称 public static final String GOODS_TM_NAME="goods_tm"; //创建商品sql private static final String CREATE_GOODS_TM="create table " +"goods_tm(_id integer primary key autoincrement,goodsCategoryTid text,goodsid text,goodsname text,memberprice text,pictureurl text)"; private SQLiteDatabase db; public DBHelper(Context context) { super(context, DB_NAME, null, 3); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { this.db=db; db.execSQL(CREATE_GOODS_TM); } public void createDB(){ db=this.getWritableDatabase(); db.execSQL(CREATE_GOODS_TM); } /** * 插入数据 * @param values * @param tablename */ public void insert(String tablename,ContentValues values){ SQLiteDatabase db=this.getWritableDatabase(); db.insert(tablename, null, values); db.close(); } /** * 查询数据 * @param tablename * @return */ public Cursor query(String tablename){ SQLiteDatabase db=this.getWritableDatabase(); Cursor c=db.query(tablename, null, null, null, null, null, null); return c; } /** * 查询数据 * @param tablename * @return */ public Cursor queryByParam(String tablename,String param){ SQLiteDatabase db=this.getWritableDatabase(); Cursor c=db.rawQuery("select * from "+tablename+" where goodsCategoryTid=?", new String[]{String.valueOf(param)}); return c; } /** * 删除数据 * @param talbename * @param id */ public void delete(String talbename,String id){ if(db==null){ db=this.getWritableDatabase(); db.delete(talbename, "_id=?", new String[]{String.valueOf(id)}); } } /** * 删除所有数据 * @param tablename */ public void deleteAll(String tablename){ if(db==null){ db=this.getWritableDatabase(); db.delete(tablename, null, null); } } /** * 删除数据库表 * @param tablename */ public void DropTable(String tablename){ db=this.getWritableDatabase(); db.execSQL("drop table "+tablename); } /** * 删除数据库 * @param tablename */ public void DropDB(){ db=this.getWritableDatabase(); // db.execSQL("drop database jshopmactive"); onUpgrade(db,3,4); } /** * 关闭数据库连接 */ public void close(){ if(db!=null){ db.close(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("DROP TABLE IF EXISTS "+TABLE_TM_NAME); db.execSQL("DROP TABLE IF EXISTS "+GOODS_CATEGORY_TM_NAME); db.execSQL("DROP TABLE IF EXISTS "+GOODS_TM_NAME); onCreate(db); } }这里主要就是在建立数据表,抽取了一部分代码。
2,android下载网络图片:我通过android访问基于http的服务器方法,获取一个有图片的信息。
看代码
public ArrayList<HashMap<String, Object>> getGoodsList(String goodsCategoryTid) throws IOException { requestjsonstr = this.queryGoodsListForJshop(goodsCategoryTid); if (Validate.StrNotNull(requestjsonstr)) { JSONArray ja = (JSONArray) JSONValue.parse(requestjsonstr); for (int i = 0; i < ja.size(); i++) { HashMap<String, Object> map = new HashMap<String, Object>(); JSONObject jo = (JSONObject) (ja.get(i)); map.put("pictureurl",getPictureurlImg(JshopActivityUtil.BASE_URL+ jo.get("pictureurl").toString())); map.put("goodsname", jo.get("goodsname").toString()); map.put("memberprice", "¥" + jo.get("memberprice").toString()); map.put("goodsid", jo.get("goodsid").toString()); map.put("goodsCategoryTid", goodsCategoryTid); map.put("pictureurlpath", downloadpcurl); goodslists.add(map); } } return goodslists; } private Bitmap getPictureurlImg(String pictureurl) throws IOException { URL url = new URL(pictureurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); InputStream in = conn.getInputStream(); Bitmap bm = BitmapFactory.decodeStream(in); // 保存本地图片 String fileName=savePicturetoDeviceAndReturnFixedUrl(pictureurl); saveOnlinePictureToCard(bm,fileName); in.close(); return bm; }
3,正则截取
/** * 获取网络图片名称 * * @param pictureurl * @return */ private String savePicturetoDeviceAndReturnFixedUrl(String pictureurl) { String regstr = "(http:|https:)\\/\\/[\\S\\.:/]*\\/(\\S*)\\.(jpg|png|gif)"; String postfix = "", filename = "", resultstr = ""; Pattern patternForImg = Pattern.compile(regstr,Pattern.CASE_INSENSITIVE); Matcher matcher = patternForImg.matcher(pictureurl); if (matcher.find()) { filename = matcher.group(2); postfix = matcher.group(3); } return resultstr = filename + "." + postfix; }
4,Bitmap保存到本地
private void saveOnlinePictureToCard(Bitmap bm, String fileName) throws IOException { File dirFile = new File(JshopMParams.SAVEPCPATH); if (!dirFile.exists()) { dirFile.mkdir(); } String onlineFilePath = JshopMParams.SAVEPCPATH +fileName; File myOnlineFile = new File(onlineFilePath); BufferedOutputStream bos = new BufferedOutputStream( new FileOutputStream(myOnlineFile)); bm.compress(Bitmap.CompressFormat.JPEG, 100, bos); bos.flush(); bos.close(); this.downloadpcurl = onlineFilePath; }
详情请见https://github.com/sdywcd/ostocy-jshop 开源项目