第一步:新建一个SQLite数据库
public class DBhelper extends SQLiteOpenHelper {
private static DBhelper dBhelper = null;
private static final String DB_Name = "database.db";
private static final int VERSION = 1;
public DBhelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
public DBhelper(Context context, String name) {
// this(context,name,VERSION);
super(context, name, null, VERSION);
}
public DBhelper(Context context, String name, int version) {
this(context, name, null, version);
}
public DBhelper(Context context) {
super(context, DB_Name, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.beginTransaction();
initTables(db);
db.setTransactionSuccessful();
db.endTransaction();
}
public void initTables(SQLiteDatabase db){
/*
* 构建图片链接表
*/
StringBuilder sql = new StringBuilder();
sql.append("CREATE TABLE IF NOT EXISTS IMAGES (")
.append("_id integer primary key,")
//.append("id integer,")
.append("url text")
.append( ");" );
db.execSQL(sql.toString());
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i("db", "db update");
}
public static synchronized DBhelper getInstance(Context context){
if (dBhelper == null) {
dBhelper = new DBhelper(context);
}
return dBhelper;
}
public static synchronized void closeDB(){
if (dBhelper!=null) {
dBhelper.close();
dBhelper = null;
}
}
}
第二步:建一个储存图片的空间,方便管理
public class ImageDB {
private final String TABLENAME = "IMAGES";
private Context context;
public ImageDB(Context context) {
this.context = context;
}
public SQLiteDatabase getWsd() {
return DBhelper.getInstance(context).getWritableDatabase();
}
public SQLiteDatabase getRsd() {
return DBhelper.getInstance(context).getReadableDatabase();
}
/**查*/
public void insert(List<String> urls){
if(urls == null || urls.size() == 0){
return;
}
SQLiteDatabase db = getWsd();
db.beginTransaction();
for (String str : urls) {
insert(str);
}
db.setTransactionSuccessful();
db.endTransaction();
}
/**插*/
public void insert(String url) {
if(TextUtils.isEmpty(url)){
return;
}
SQLiteDatabase db = getWsd();
ContentValues values = new ContentValues();
values.put("url", url);
db.insert(TABLENAME, null, values);
}
/**插*/
public List<String> findAll(){
SQLiteDatabase db = getRsd();
Cursor cursor =db.query(TABLENAME, new String[]{"url"}, null, null, null, null, null);
List<String> list = new ArrayList<String>();
try{
while (cursor.moveToNext()) {
list.add(cursor.getString(cursor.getColumnIndex("url")));
}
} catch (Exception e) {
e.printStackTrace();
}finally{
cursor.close();
}
return list;
}
/**
* 清空表
*
* @param tablename
*/
public void clear() {
SQLiteDatabase db = getWsd();
String sql = "DELETE FROM " + TABLENAME + ";";
db.execSQL(sql);
}
第三步:写一个listview适配器
public class ImageAdapter extends BaseAdapter {
private Context context;
private List<String> data;
public ImageAdapter(Context context,List<String> data) {
setData(data);
this.context = context;
}
public void setData(List<String> data) {
if(data == null){
this.data = new ArrayList<String>();
}else{
this.data = data;
}
}
@Override
public int getCount() {
// TODO Autgenerated method stub
return data.size();
}
@Override
public String getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
/**按照链接中的文件名获取图片*/
public Bitmap getBitmap(int position){
if(!(Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED))){
Toast.makeText(context, "SD卡不存在", Toast.LENGTH_LONG).show();
return null;
}
return BitmapFactory.decodeFile(Const.ALBUM_PATH+getItem(position).substring(getItem(position).lastIndexOf("/") + 1));
}
@Override
public View getView(int position, View view, ViewGroup arg2) {
ViewHolrd holrd = null;
if(view == null){
holrd = new ViewHolrd();
view = View.inflate(context, R.layout.item, null);
holrd.image = (ImageView)view.findViewById(R.id.item_image);
view.setTag(holrd);
}else{
holrd = (ViewHolrd)view.getTag();
}
//获取不到就从网络获取
Bitmap bm = getBitmap(position);
if(bm == null){
bm = ((MainActivity)context).getHttpBitmap(getItem(position));
}
holrd.image.setImageBitmap(bm);
return view;
}
class ViewHolrd{
ImageView image;
}
}
第四步:工具类的一个保存图片的文件夹
public class Const {
/**本地图片的存储位置*/
public final static String ALBUM_PATH = Environment
.getExternalStorageDirectory() + "/download_BankImg/";
}
最后:就是主MianActivity了
public class MainActivity extends Activity {
public static final String HTTP_URI = "http://www.byby8.com:9000/BankPush/appimage";
private List<String> list;
private ImageAdapter adapter;
private ListView listView;
private ImageDB db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.main_list);
fillData();
}
@SuppressWarnings("unchecked")
private void fillData() {
db = new ImageDB(this);
list = new ArrayList<String>();
list = db.findAll();
adapter = new ImageAdapter(this, list);
listView.setAdapter(adapter);
if(list == null || list.size() == 0){//数据库木有就从网络获取
new ImgHttp().execute();
}
}
class ImgHttp extends AsyncTask<String, String, String> {
String result = "";
@Override
protected String doInBackground(String... arg0) {
return ImgViewHttp(HTTP_URI);
}
protected void onPostExecute(String result) {
JSONObject jsonObj;
list = new ArrayList<String>();
try {
jsonObj = new JSONObject(result.toString());
Iterator<String> iter = jsonObj.keys();//因为数据是动态的,解析也是灵活
while (iter.hasNext()) {
list.add(jsonObj.getString(iter.next()));
}
} catch (JSONException e) {
e.printStackTrace();
}
new Thread(){
public void run() {
db.insert(list);//将数据插到数据库
};
}.start();
new ASt(list).execute();//获取图片并存储
}
}
/** 请求三张图片 **/
private String ImgViewHttp(String url) {
/* 建立HTTP Post连线 */
HttpPost httpRequest = new HttpPost(url);
String result = "";
List<BasicNameValuePair> sendData = new ArrayList<BasicNameValuePair>();
// 发出HTTP request
try {
httpRequest
.setEntity(new UrlEncodedFormEntity(sendData, HTTP.UTF_8));
// 取得HTTP response
HttpResponse httpResponse = new DefaultHttpClient()
.execute(httpRequest);
// 若状态码为200 ok
if (httpResponse.getStatusLine().getStatusCode() == 200) {
BufferedReader bufferedreader = null;
InputStream inputstream = null;
HttpEntity httpentity = httpResponse.getEntity();
inputstream = httpentity.getContent();
bufferedreader = new BufferedReader(new InputStreamReader(
inputstream));
String line;
while ((line = bufferedreader.readLine()) != null) {
result += line;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/****** 获取图片 *******/
class ASt extends AsyncTask<String, List<String>, List<String>> {
private List<String> urls;
public ASt(List<String> urls) {
this.urls = urls;
}
@Override
protected List<String> doInBackground(String... objects) {
for (String str : urls) {
getHttpBitmap(str);//把图片都搞回来
}
return urls;
}
@Override
protected void onPostExecute(List<String> result) {
adapter.setData(result);//搞完刷新吧
adapter.notifyDataSetChanged();
}
}
// 获取图片
public Bitmap getHttpBitmap(String data) {
Bitmap bitmap = null;
try {
// 初始化一个URL对象
URL url = new URL(data);
// 获得HTTPConnection网络连接对象
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setConnectTimeout(5 * 1000);
connection.setDoInput(true);
// connection.connect();
// 得到输入流
InputStream is = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
// 将图片保存到文件夹
File myFile = new File(Const.ALBUM_PATH);
if (!myFile.exists()) {
myFile.mkdir();
}
File myCaptureFile = new File(Const.ALBUM_PATH
+ data.substring(data.lastIndexOf("/") + 1));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(myCaptureFile));
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
// 关闭输入流
is.close();
// 关闭连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}