Android使用SQLiteDatabase直接存取数据与图像

Android使用SQLiteDatabase直接存取数据与图像的简单方法如下:

package com.test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;

import com.test.R;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class SQLiteDatabaseTest extends Activity {
	/** Called when the activity is first created. */
	private Button btnSave;
	private Button btnLoad;
	private Button btnClear;
	private ImageView imgView;
	private ImageView imgView2;
	private TextView txtView;
	private Bitmap bmp;
	private static SQLiteDatabase db;
	private Context mContext;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		btnSave = (Button) findViewById(R.id.btnSave);
		btnLoad = (Button) findViewById(R.id.btnLoad);
		btnClear = (Button) findViewById(R.id.btnClear);
		imgView = (ImageView) findViewById(R.id.imgView);
		imgView2 = (ImageView) findViewById(R.id.imgView2);
		txtView = (TextView) findViewById(R.id.txtView);
		btnSave.setOnClickListener(new ClickEvent());
		btnLoad.setOnClickListener(new ClickEvent());
		btnClear.setOnClickListener(new ClickEvent());
		imgView2.setImageBitmap(BitmapFactory.decodeResource(getResources(),
				R.drawable.bg));
		mContext = SQLiteDatabaseTest.this;

		// 创建数据库文件
		File path = mContext.getDir("databases", Context.MODE_WORLD_WRITEABLE);
		path = new File(path, "test.db");
		int flag = SQLiteDatabase.OPEN_READWRITE;
		flag = flag | SQLiteDatabase.CREATE_IF_NECESSARY;
		flag = flag | SQLiteDatabase.NO_LOCALIZED_COLLATORS;
                  db = SQLiteDatabase.openDatabase(path.getAbsolutePath(), null, flag);
                  // 创建表
		String sql = "create table if not exists info("
				+ "id integer primary key autoincrement,name varchar(20),"
				+ "time varchar(20),img BLOB)";
                 db.execSQL(sql);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (db.isOpen()) {
		      db.close();
		}
		if(!bmp.isRecycled()){
		     bmp.recycle();
		}
	}

	class ClickEvent implements View.OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (v == btnSave) {
				Cursor c = db.rawQuery("select * from info", null);
				ContentValues values = new ContentValues();
				c.moveToFirst();
				values.put("name", "test" + (c.getCount() + 1));
				SimpleDateFormat sDateFormat = new SimpleDateFormat(
						"yyyy-MM-dd hh:mm:ss");
				String time = sDateFormat.format(new java.util.Date());
				values.put("time", time);
			    Bitmap bmp = BitmapFactory.decodeResource(getResources(),
						R.drawable.bg);
			    
				if (null != bmp) {	
					//在Bitmap上绘制标签
					Bitmap drawBmp = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Config.ARGB_8888);
					Canvas cvs = new Canvas(drawBmp);
					Paint p = new Paint();
					p.setColor(Color.RED);
					p.setTextSize(22);
					cvs.drawBitmap(bmp, 0, 0, p);
					cvs.drawText("test" + (c.getCount() + 1), 10, 20,p);
				    //将绘制后Bitmap转为Byte[]并加入values	
					values.put("img", bmpToByteArray(drawBmp));
					drawBmp.recycle();
				}
				db.insert("info", null, values);
				c.close();
				bmp.recycle();

			} else if (v == btnLoad) {
				Cursor c = db.rawQuery("select * from info", null);
				c.moveToLast();
				if (c.isLast()) {
				       String name = c.getString(c.getColumnIndex("name"));
				       txtView.setText("name:" + name + " 共计:" + c.getCount()
							+ " 条");
				       bmp = cursorToBmp(c, c.getColumnIndex("img"));
				       imgView.setImageBitmap(bmp);
				}
				c.close();

			} else if (v == btnClear) {
				imgView.setImageBitmap(null);
			}

		}

	}

	// Bitmap to byte[]
	public byte[] bmpToByteArray(Bitmap bmp) {
	    // Default size is 32 bytes
	    ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			bos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bos.toByteArray();
	}

	// Cursor to bitmap
	Bitmap cursorToBmp(Cursor c, int columnIndex) {

		byte[] data = c.getBlob(columnIndex);
		try {
			return BitmapFactory.decodeByteArray(data, 0, data.length);
		} catch (Exception e) {
			return null;
		}
	}

}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="fill_parent" 
	android:layout_height="fill_parent"
	android:orientation="horizontal">
  <ImageView 
	android:id="@+id/imgView"
	android:layout_width="640dip" 
	android:layout_height="fill_parent"/>
    
   <LinearLayout 
      android:id="@+id/LinearLayout01"
      android:layout_width="150dip" 
      android:layout_height="fill_parent"
      android:layout_marginLeft="5dip"
      android:layout_marginRight="5dip"
      android:orientation="vertical">
                 <ImageView 
	         android:id="@+id/imgView2"
		android:layout_width="fill_parent" 
		android:layout_height="150dip"
		android:layout_marginTop="10dip"/>
	         <Button 
		    android:id="@+id/btnSave" 
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content" 
		    android:text="保存图像"/>
		<Button 
		    android:id="@+id/btnLoad" 
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content" 
		    android:text="载入图像"/>
		<Button
		    android:id="@+id/btnClear"
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content"
		    android:text="清除图像"/>
		<TextView 
		    android:id="@+id/txtView"
		    android:layout_width="fill_parent"
		    android:layout_height="wrap_content"
		    android:textColor="#FFFFFF"
		    android:textSize="22sp"
		    android:text="..."/>

   </LinearLayout>
	
</LinearLayout>

开发环境:XP3+Eclipse+Android2.2+JDK6.0

测试环境:Android2.2,5寸屏,分辨率640X480

源代码:http://download.csdn.net/detail/xinzheng_wang/4420817

相关推荐