Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

android - How can I insert image in a sqlite database

I want to put an image from camera to database using this database code. What should be the code for the save button and the preview button?

public class databases extends SQLiteOpenHelper {
        public static final String data = "student.db";
        public static final String TABLE_NAME = "Student_TABLE";
        public static final String COL_1 = "Fname";
        public static final String COL_2 = "password";
        public static final String COL_3 = "Fathers_name";
        public static final String COL_4 = "Roll";
        public static final String COL_5 = "Image";
        public databases(Context context) {
            super(context, data, null, 1);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("create table " + TABLE_NAME + " (Fname TEXT,password TEXT,Fathers_name TEXT,Roll TEXT PRIMARY KEY,Image BLOB)");
        }

Now This is the activity code containing the respective buttons.

public class home_page extends AppCompatActivity {
Button lout,homepage,showperson,picture;static final int REQUEST_IMAGE_CAPTURE = 1;
TextView showit;
String userid,pwrd,r2,r3,r4;
databases dbss;
    public void getterclass(String m)
    {
        userid=m;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        lout = (Button) findViewById(R.id.out);
        homepage = (Button) findViewById(R.id.home);
        showit=(TextView) findViewById(R.id.showtextdata);
        showperson=(Button)findViewById(R.id.showdata);
        picture=(Button)findViewById(R.id.images);
        dbss=new databases(home_page.this);
        getSupportActionBar().hide();
        homepage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent redirect=new Intent(home_page.this,home_page.class);
                startActivity(redirect);
            }
        });

        lout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent logout=new Intent(home_page.this,log_in.class);
                        startActivity(logout);
            }
        });
        showperson.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Cursor sh=dbss.givedata(userid);
                StringBuffer buf=new StringBuffer();
                buf.append("First name :" + sh.getString(0) + "
");
                buf.append("password :" + sh.getString(1) + "
");
                buf.append("Father's name :" + sh.getString(2) + "
");
                buf.append("Roll :" + sh.getString(3) + "

");
                showit.setText(buf.toString());
            }
        });
        picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
                }
                databases help=new databases(home_page.this);
            }
        });

The getterclass() is nothing but to retrieve the personal information of the user into other activity however that isn't working as well when I try to display the data to in the same activity.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You extract the image as a byte[] and then either convert that to the bytes, as a string of hexadecimal characters and then enclose that string in X' your_hexadecimal_string '

  • e.g. it could be X'FFFEFDFCFBFA9........'

and use that string as the value to insert via native SQL

  • e.g. INSERT INTO your_table (image_column) VALUES(X'FFFEFDFCFBFA9........')

Or you could use the SQliteDatbase insert convenience method, which takes a Contentvalues object as the 3rd parameter. You'd setup the Contentvalues object something along the lines of

ContentValues cv = new Contentvalues();
cv.put("Image",your_image_as_a_byte_array);
db.insert("the_table_name",null,cv);

However, storing images can be troublesome and it is not recommended to store images, especially if they are over about 100k in size on average.

If an image is near to or greater than 2M you will be unable to retrieve that image using the standard Android SQLite API as a CursorWindow has a limitation of 2M. Even at 1M you could perhaps get 1 image within a CursorWindow.

The recommended method is to store the path or part of the path to the image and to retrieve the image via it's path when required.

Example

Saying that (the above), the following is an App that will either store the image in the Database if it is below 100K (public static final int MAX_FILE_SIZE = 100 * 1024;) or store the path and either retrieve the image via the path or the database according to what was stored.

The App has two ListViews with the images descriptions (the rightmost includes the path to the image). Clicking on an item in either displays the image.

e.g.

enter image description here

There are a number of images most over 100k, one funny.png is below 100k :-

enter image description here

The images have been placed into the Raw folder of the Res folder for this example, they are then copied to data/data/files/images folder (where represents the name of the App's package):-

enter image description here

The DatabaseHelper, DBHelper.java is :-

public class DBHelper extends SQLiteOpenHelper {
    public static final String DBNAME = "images.db";
    public static final int DBVERSION = 1;

    // The maximum size of an image that should be stored 100K
    public static final int MAX_FILE_SIZE = 100 * 1024;

    public static final String TB_IMAGE = "image";
    public static final String COL_IMAGE_ID = BaseColumns._ID;
    public static final String COL_IMAGE_PATH = "image_path";
    public static final String COL_IMAGE_NAME = "image_name";
    public static final String COl_IMAGE_DESCRIPTION = "image_description";
    public static final String COL_IMAGE_SIZE = "image_size";
    public static final String COL_IMAGE_IMAGE = "image";

    SQLiteDatabase mDB;

    /**
     * Construct DBHelper, note that it will open the database and
     * thus create it if it doesn't exist
     * @param context   a context from the invoking activity
     */
    public DBHelper(Context context) {
        super(context, DBNAME, null, DBVERSION);
        mDB = this.getWritableDatabase();
    }

    /**
     * Create the table(s)
     * @param db
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        String crtsql = "CREATE TABLE IF NOT EXISTS " + TB_IMAGE +
                "(" +
                COL_IMAGE_ID + " INTEGER PRIMARY KEY, " +
                COL_IMAGE_PATH + " TEXT UNIQUE, " +
                COL_IMAGE_NAME + " TEXT, " +
                COl_IMAGE_DESCRIPTION + " TEXT, " +
                COL_IMAGE_SIZE + " INTEGER, " +
                COL_IMAGE_IMAGE + " BLOB DEFAULT x'00'" +
                ")";
        db.execSQL(crtsql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }

    /**
     * Return a Cursor with all the rows from the image table
     * @return  The Cursor
     */
    public Cursor getImageList() {
        return mDB.query(TB_IMAGE,null,null,null,null,null,null);
    }


    /**
     * Store an image row in the image table, noting that is the image
     *  size is small than the max size that the image will be stored as a blob
     *  otherwise a blob of 1 byte is stored due to the default value.
     * @param path          the path to the image
     * @param description   a description for the image
     * @return              the id (rowid) of the row
     */
    public long addImageFromPath(String path, String description) {

        ContentValues cv = new ContentValues();
        File f = new File(path);
        InputStream is;

        // If the file doesn't exist don't store a row
        if (!f.exists()) {
            return -1;
        }

        // Always store the name, description, path and size
        cv.put(COL_IMAGE_NAME,f.getName());
        cv.put(COl_IMAGE_DESCRIPTION,description);
        cv.put(COL_IMAGE_SIZE,f.length());
        cv.put(COL_IMAGE_PATH,f.getAbsolutePath());

        // If the size is less than the max then get the filestream
        // and convert to a byte[].
        // Note if larger then the max file size the default x'00' blob
        // will be applied
        if (f.length() < MAX_FILE_SIZE) {
            byte[] buffer = new byte[(int) f.length()];
            try {
                is = new FileInputStream(f);
                is.read(buffer);
            } catch (IOException e) {
                e.printStackTrace();
                return -1;
            }
            cv.put(COL_IMAGE_IMAGE,buffer);
        }
        // Do the insert
        return mDB.insert(TB_IMAGE,null,cv);
    }

    /**
     * get the image as a bitmap from the DB if stored, otherwise get it from
     * the file, according to the id.
     * @param id    the id of the row in the image table
     * @return      the bitmap to be returned (note may be empty bitmap)
     */
    public Bitmap getImage(long id) {
        byte[] ba = new byte[0];

        // If the image is stored in the DB then extract and return the bitmap
        if (isStoredAsImage(id)) {
            return getImageAsBitMap(id);
        }
        // If not then get the respective row from the DB
        Cursor csr = mDB.query(
                TB_IMAGE,
                null,
                COL_IMAGE_ID+"=?",
                new String[]{String.valueOf(id)},
                null,
                null,
                null
        );

        // Prepare to convert the path to a file
        String path = ""; //<<<< default to  empty path
        File f = new File(path); //<<< default to empty file
        // If a valid row was found get the path and File from the row
        if (csr.moveToFirst()) {
            path = csr.getString(csr.getColumnIndex(COL_IMAGE_PATH));
            f = new File(path);
        }
        // done with the cursor so close it
        csr.close();

        // If the file exists then return the Bitmap
        if (f.exists()) {
            return BitmapFactory.decodeFile(f.getAbsolutePath());
        }
        // return an empty bitmap
        return BitmapFactory.decodeByteArray(ba,0,ba.length);
    }

    /**
     * Check to see if an image is stored in the DB,
     *  note assumes anything less than 8 bytes isn't an image
     * @param id    the id of the row in the image table
     * @return      true if like an image is stored, otherwise false
     */
    private boolean isStoredAsImage(long id) {
        boolean rv = true;
        byte[] ba = new byte[0];

        // Get the respective row from the image table
        Cursor csr = mDB.query(
                TB_IMAGE,
                null,
                COL_IMAGE_ID+"=?",
                new String[]{String.valueOf(id)},
                null,
                null,
                null
        );

        // If a row was found get the blob into byte array ba
        // if not then ready to return false
        if (csr.moveToFirst()) {
            ba = csr.getBlob(csr.getColumnIndex(COL_IMAGE_IMAGE));
        } else {
            rv = false;
        }
        // If the byte array ba is less then 8 bytes then ready to return false
        if (ba == null || ba.length < 8) {
            rv =  false;
        }
        // done with the Cursor so close it
        csr.close();
        // return the result
        return rv;
    }

    /**
     * get the image (assumes isStoredAsImage is used prior to invocation)
     * @param id    the id of the respective row
     * @return      the bitmap (may be 0 length)
     */
    private Bitmap getImageAsBitMap(long id) {
        byte[] ba = new byte[0];
        Bitmap bmp;
        Cursor csr =mDB.query(
                TB_IMAGE,
                null,
                COL_IMAGE_ID+"=?",
                new String[]{String.valueOf(id)},
                null,
                null,
                null
        );
        if (csr.moveToFirst()) {
            ba = csr.getBlob(csr.getColumnIndex(COL_IMAGE_IMAGE));
        }
        csr.close();
        return BitmapFactory.decodeByteArray(ba,0,ba.length);
    }
} 

The Invoking activity MainActivity.java is :-

public class MainActivity extends AppCompatActivity {

    public static final String IMAGES_DIRECTORY = "images";
    private static File images_file;

    ArrayAdapter<String> mAdapter;
    ListView mListView01, mListView02;
    ArrayList<String> mImages;
    CursorAdapter mCsrAdapter;
    Cursor mCsr;
    ImageView mImageView;
    DBHelper mDBHlpr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // get the View/Viewgroup IDs
        mListView01 = this.findViewById(R.id.listview001); // File List
        mListView02 = this.findViewById(R.id.listview002); // DB List
        mImageView = this.findViewById(R.id.imageview001); // Image display

        // get an instance of the DBHelper
        mDBHlpr = new DBHelper(this);

        // Copy images from raw folder to data/data/<package>/Files/images
        // Also store all the images in the Database (or not depedning upon size)
        getImagesFile(this);
        if (getImagesCount() < 1) {
            loadRawImages();
            storeImagesToDB();
        }
        // Setup the two ListViews to display image name lists
        displayList();
        displayListFromDB();

        // setup the file list so that when an item is clicked the image is displayed
        mListView01.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String imagename = mListView01.getItemAtPosition(i).toString();
                displayImage(imagename);
            }
        });

        // setup the DB list so that when an item is clicked the image is displayed
        mListView02.setOnItemClickListener(new AdapterView.On

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...