D.Tech Academic
Deep Singh
Pages
Core Java
Web App
Spring
Hibernate
Kotlin
Android
Python
Flutter
Spring Boot
Save and Retrieve image SqliteDatabase Tutorial
Database.java
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.ByteArrayInputStream; import java.sql.Blob; import java.util.ArrayList; import java.util.List; public class Database extends SQLiteOpenHelper { public Database(Context context) { super(context, "image.db", null, 1); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL("create table imagedata (image blob);"); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { sqLiteDatabase.execSQL("drop table if exists imagedata "); onCreate(sqLiteDatabase); } public long storeImage(byte b[]) { ContentValues cv = new ContentValues(); cv.put("image", b); return getWritableDatabase().insert("imagedata", null, cv); } public Bitmap getImage() { Bitmap bp = null; Cursor c = getReadableDatabase().query("imagedata", null, null, null, null, null, null); if (c.moveToNext()) { byte b[] = c.getBlob(0); ByteArrayInputStream bi = new ByteArrayInputStream(b); bp = BitmapFactory.decodeStream(bi); } return bp; } }
DatabaseDemo.java
import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.Toast; import java.io.ByteArrayOutputStream; import java.util.List; public class DatabaseDemo extends AppCompatActivity { Database d; ImageView img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); d = new Database(this); img = findViewById(R.id.pic); } public void addImage(View v) { Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.dd); ByteArrayOutputStream stream = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte imageInByte[] = stream.toByteArray(); long t = d.storeImage(imageInByte); d.close(); if (t > 0) { Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Fail", Toast.LENGTH_SHORT).show(); } } public void getImage(View v) { img.setImageBitmap(d.getImage()); } }
activity_main.xml
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment