您的位置:首页 > 移动开发 > Android开发

android Sqlite的图片文本本地存储和读取(包括网络获取jason,解析jason,获取网络图片,创建sqlite数据库)

2020-02-17 05:14 405 查看

    

    本地保存图片,而且图片一般是从网络获取,所以需要在获取jason的子线程当中就得把图片的url给解析成BitMap类型

  获取网络图片方法如下:

private Bitmap GetNetBitmap(String url) {
// TODO Auto-generated method stub
URL imageUrl = null; //图片URL
Bitmap bitmap = null; //要返回的Bitmap类型图片
try {
imageUrl = new URL(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setConnectTimeout(5000);
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;

}
                       创建Sqlite数据库(继承SQLiteOpenHelper)

public static final String DATABASE_NAME = "MYDATABASE.db";
public static final String TABLE_NAME = "tiezi";

public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase arg0) {
arg0.execSQL("create table if not exists "
+ TABLE_NAME
+ " (id integer primary key autoincrement," +
"tiezi_title text not null," +
"tiezi_image BLOB," +                      //网络获取的图片保存到sqlite数据库中的格式为BLOB
"tiezi_time text not null, " +
"tiezi_dianjiliang text not null," +
"tiezi_id text not null," +
"tiezi_class text not null);");

}
         声明 保存数据到本地sqlite数据库的 方法       
public DAO(Context context) {
helper = new DatabaseHelper(context);
db = helper.getWritableDatabase();
this.context = context;
}

public void <span style="color:#330099;">saveTiezi</span>(String tiezi_title, Bitmap tiezi_image,
String tiezi_id, String tiezi_dianjiliang, String tiezi_time,
String tiezi_class) {
if (tiezi_image == null) {
return;
}
final ByteArrayOutputStream os = new ByteArrayOutputStream();

tiezi_image.compress(Bitmap.CompressFormat.PNG, 100, os); //将图片格式压缩成PNG格式的,100代表最大质量大小,将字节流保存到<span style="font-family: Arial, Helvetica, sans-serif;">ByteArrayOutputStr                                                                                                                                                    eam </span>中

ContentValues values = new ContentValues();

values.put("tiezi_title", tiezi_title);
values.put("tiezi_image", os.toByteArray());
values.put("tiezi_id", tiezi_id);
values.put("tiezi_dianjiliang", tiezi_dianjiliang);
values.put("tiezi_time", tiezi_time);
values.put("tiezi_class", tiezi_class);

Cursor cur = db.rawQuery("select * from " + DatabaseHelper.TABLE_NAME    //通过tiezi_id判断数据库中是否存在相同的一条数据
+ " where tiezi_id='" + tiezi_id + "'", null);
if (!cur.moveToNext()) {
db.insert("tiezi", null, values);

}

}




    网络获取jason字符串(shiR)

     重写子线程中的run()方法

@Override
public void run() {
// TODO Auto-generated method stub
try {
HttpURLConnection connection = (HttpURLConnection) new URL(pathf)
.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection
.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
connection
.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 BIDUBrowser/6.x Safari/537.36");
connection.setRequestProperty("Connection", "Keep-Alive");

if (connection.getResponseCode() == 200) {// 状态
BufferedReader buf = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String outstr = "";

String line = "";
while ((line = buf.readLine()) != null) {
outstr += line + "\n";
}
if(!outstr.contains("error")){
infos =parsejson(outstr);
Message message = new Message();
message.obj = infos;
message.what=1;
handlerf.sendMessage(message);}

}else{
handlerf.sendEmptyMessage(0);

}

} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

}

解析jason 并存储到数据库中      
private List<ContentListInfo> parsejson(String path) { // json解析
List<ContentListInfo> parsrList =new  ArrayList<ContentListInfo>();
try {

JSONObject jsonObject = new JSONObject(path);
JSONArray info = jsonObject.getJSONArray("list");

for (int i =0; i < info.length(); i++) {
JSONObject object = info.getJSONObject(i);
String title = object.getString("title");
String news_id = object.getString("news_id");
String news_time = object.getString("news_time");
String photo_url = object.getString("photo_url");
String onclick = object.getString("onclick");
Bitmap image = GetNetBitmap(photo_url);

//保存到本地数据库
try {
MainActivity.dao.saveTiezi(title, image, news_id, onclick, news_time,class_id);// 在activity中声明一个static的DAO对象
} catch (Exception e) {
Log.e("bendi", e.toString());
}
ContentListInfo contentListInfo = new ContentListInfo(Integer.parseInt(news_id), image, title, Integer.parseI nt(onclick),news_time);

parsrList.add(contentListInfo);
}
return parsrList;
} catch (Exception e) { // TODO: handle exception
e.printStackTrace();
}
return parsrList;
}



  • 点赞
  • 收藏
  • 分享
  • 文章举报
jeromeyang09 发布了4 篇原创文章 · 获赞 0 · 访问量 7195 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: