Access Bitmap from SQlite database in Android (1)

Source: Internet
Author: User

MainActivity is as follows:

Package cn.com; import java. io. byteArrayOutputStream; import java. io. inputStream; import java.net. httpURLConnection; import java.net. URL; import cn. db. DBservice; import cn. db. photo; import android. app. activity; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. view; import android. widget. butto N; import android. widget. imageView; public class MainActivity extends Activity {private Button mButton; private Bitmap mBitmap; private ImageView mImageView; private boolean isDownload = true; private boolean isSave = false; private boolean isLoadFromDB = false; private static final int DOWNLOAD_FINISH = 88; private byte [] photoByte; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreat E (savedInstanceState); setContentView (R. layout. main); mButton = (Button) findViewById (R. id. button); mButton. setOnClickListener (new ButtonOnClickListener (); mImageView = (ImageView) findViewById (R. id. imageView);} private class ButtonOnClickListener implements View. onClickListener {public void onClick (View v) {if (isDownload) {new Thread () {public void run () {mBitmap = getBitmap ("http://s12.sinaimg.cn/mid Dle/4b181bd0gbf6cb07c2a1b & 690 "); handler. sendEmptyMessage (DOWNLOAD_FINISH );}}. start () ;}if (isSave) {DBservice service = new DBservice (MainActivity. this); Photo photo = new Photo (1, mBitmap); service. save (photo, photoByte); isLoadFromDB = true; isSave = false; mButton. setText ("loading bitmap from database"); mImageView. setImageBitmap (null); return;} if (isLoadFromDB) {DBservice service = new DBservice (MainActivity. this); Photo photo = s Ervice. find (1); mImageView. setImageBitmap (photo. getPhoto () ;}} Handler handler = new Handler () {public void handleMessage (Message msg) {switch (msg. what) {case DOWNLOAD_FINISH: mImageView. setImageBitmap (mBitmap); mButton. setText ("Save image to SQLite"); isDownload = false; isSave = true; break; default: break ;};}; public Bitmap getBitmap (String imagePath) {try {URL imageUrl = new URL (imagePath); HttpURLConnection Connection = (HttpURLConnection) imageUrl. openConnection (); connection. setConnectTimeout (5000); connection. setRequestMethod ("POST"); if (connection. getResponseCode () == 200) {InputStream inputStream = connection. getInputStream (); photoByte = readResource (inputStream); Bitmap bitmap = BitmapFactory. decodeByteArray (photoByte, 0, photoByte. length); return bitmap ;}} catch (Exception e) {} return null ;}; public Byte [] readResource (InputStream inputStream) {try {ByteArrayOutputStream outputStream = new ByteArrayOutputStream (); byte [] buffer = new byte [1024]; int len = 0; while (len = inputStream. read (buffer ))! =-1) {outputStream. write (buffer, 0, len);} inputStream. close (); outputStream. close (); return outputStream. toByteArray ();} catch (Exception e) {} return null ;}}

DataBaseOpenHelper. java is as follows:

package cn.db;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class DataBaseOpenHelper extends SQLiteOpenHelper {public DataBaseOpenHelper(Context context) {super(context, "testbold.db", null, 1);}@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL("create table test(photoid integer primary key autoincrement,id ingeter(10),photo Blob(20))");}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}}

 

DBservice. java is as follows:

package cn.db;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.graphics.Bitmap;import android.graphics.BitmapFactory;public class DBservice {private DataBaseOpenHelper openHelper;public DBservice(Context context) {openHelper=new DataBaseOpenHelper(context);}public void save(Photo photo,byte [] photoByte){SQLiteDatabase db=openHelper.getWritableDatabase();        db.execSQL("insert into test (id,photo) values(?,?)",new Object[]{photo.getId(),photoByte});        db.close();}public Photo find(int i){SQLiteDatabase db=openHelper.getWritableDatabase();Cursor cursor=db.rawQuery("select * from test where photoid=?", new String[]{String.valueOf(i)});while(cursor.moveToFirst()){int photoid=cursor.getInt(cursor.getColumnIndex("photoid"));byte[] photoByte=cursor.getBlob(cursor.getColumnIndex("photo"));          Bitmap bitmap=BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length); Photo photo=new Photo(photoid, bitmap);return photo;}cursor.close();db.close();return null;}}

Photo. java is as follows:

package cn.db;import android.graphics.Bitmap;public class Photo {private int id;private Bitmap bitmap;public Photo() {}public Photo(int id, Bitmap bitmap) {super();this.id = id;this.bitmap = bitmap;}public int getId() {return id;}public void setId(int id) {this.id = id;}public Bitmap getPhoto() {return bitmap;}public void setPhoto(Bitmap bitmap) {this.bitmap = bitmap;}}

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.