从SQLite数据库获取图像并将其显示到GridView Android Studio中

时间:2017-04-18 20:35:30

标签: android database image sqlite gridview

我是Android Studio的新手,我在获取已存储到数据库中的图像时遇到了一些麻烦,然后将它们显示到GridView中。有没有办法可以获取存储在数据库中的图像数量,然后逐个显示它们,每个图像都在GridView中的不同单元格中?到目前为止,这是我的代码:

NewsAddImageActivity类

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;

public class NewsAddImageActivity extends AppCompatActivity {
    //public MyDatabaseHelper dbHelper;
    MyDatabaseHelper dbHelper = new MyDatabaseHelper(this);
    private static int RESULT_LOAD_IMG = 1;
    String imgDecodableString;
    Bitmap bitmap;
    int tabNo;
    Tab1Class t1;
    Tab2Class t2;
    Tab3Class t3;
    Cursor cursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_newsaddimage);

        final ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadImagefromGallery(v);
            }
        });

        Button submit = (Button) findViewById(R.id.addButton);
        submit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                dbHelper.addEntry(dbHelper.getBytes(bitmap)); //add image to database


                byte[] image = cursor.getBlob(1); //get image from database as byte 

                dbHelper.getImage(image); //converts byte to bitmap

                if(tabNo==0){
                  //place image in the grid view of tab1
                }else if(tabNo==1) {
                  //place image in the grid view of tab2
                }else if(tabNo==2){
                  //place image in the grid view of tab3
                }

                finish();
                Toast.makeText(getApplicationContext(),"Added",Toast.LENGTH_LONG).show();
            }
        });

        Button cancel = (Button) findViewById(R.id.cancelButton);
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                finish();
                Toast.makeText(getApplicationContext(),"Cancelled",Toast.LENGTH_LONG).show();
            }
        });

    }

    private byte[] imageButtonToByte(ImageButton image){
        Bitmap bitmap=((BitmapDrawable)image.getDrawable()).getBitmap();
        ByteArrayOutputStream stream=new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray=stream.toByteArray();
        return byteArray;
    }


    public void loadImagefromGallery(View view) {
        // Create intent to Open Image applications like Gallery, Google Photos
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) {
                // Get the Image from data

                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                // Get the cursor
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgDecodableString = cursor.getString(columnIndex);
                cursor.close();


                ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton);
                bitmap = ((BitmapDrawable) imageButton.getDrawable()).getBitmap();



                // Set the Image in ImageView after decoding the String
                imageButton.setImageBitmap(BitmapFactory
                        .decodeFile(imgDecodableString));


            } else {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                    .show();
        }

    }

    public void getTab(int num){
        switch(num) {
            case 0: tabNo=0;
            case 1: tabNo=1;
            case 2: tabNo=2;
        }
    }

}

MyDatabaseHelper Class

package com.example.mobilecomputingapplication;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.ByteArrayOutputStream;



public class MyDatabaseHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "ImagesDB";

    // Table Names
    private static final String DB_TABLE = "imageTable";

    // column names
    private static final String KEY_NAME = "image_name";
    private static final String KEY_IMAGE = "image_data";

    // Table create statement
    private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + "("+
            KEY_NAME + " TEXT," +
            KEY_IMAGE + " BLOB);";

    public MyDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        // creating table
        db.execSQL(CREATE_TABLE_IMAGE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // on upgrade drop older tables
        db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);

        // create new table
        onCreate(db);
    }

   /* public void addEntry( String name, byte[] image) throws SQLiteException {
        SQLiteDatabase database = this.getWritableDatabase();
        ContentValues cv = new  ContentValues();
        cv.put(KEY_NAME,    name);
        cv.put(KEY_IMAGE,   image);
        database.insert( DB_TABLE, null, cv );
    }*/

    public void addEntry( byte[] image) throws SQLiteException {
        SQLiteDatabase database = this.getWritableDatabase();
        ContentValues cv = new  ContentValues();
        cv.put(KEY_IMAGE,   image);
        database.insert( DB_TABLE, null, cv );
    }
    // convert from bitmap to byte array
    public static byte[] getBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
        return stream.toByteArray();
    }

    // convert from byte array to bitmap
    public static Bitmap getImage(byte[] image) {
        return BitmapFactory.decodeByteArray(image, 0, image.length);
    }
}

1 个答案:

答案 0 :(得分:0)

你可以创建一个你想要选择保存在db<中的图像位图。不保存图像保存图像的URI(路径),如下所示。在此代码中,所选图像是一个保存所选图像的数组。你应该在Dbhelper中插入图像的方法并传递这样的字符串。

Bitmap bitmap = thumbnails[i];
                       Uri uri = Utility.getImageUri(getContext(),bitmap);
                        byte[] path = Utility.getBytes(bitmap);
                        cnt++;
                        selecteddimages.add(uri);
                        String s = uri.toString();
                        databaseHelper.insertContact(s);




DBHELPER method of insert


   public void insertContact (String name) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("name", name);
         long result=db.insert("images", null, contentValues);
        if (result==-1){
            Toast.makeText(context,"not save",Toast.LENGTH_SHORT).show();
        }else {
                Toast.makeText(context,"save",Toast.LENGTH_SHORT).show();
            }
        }


UTILITIES CLass for getimage URI
   public static byte[] getBytes(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 0, stream);
        return stream.toByteArray();
    }

 public static Uri getImageUri(Context inContext, Bitmap inImage) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "title", null);
        return Uri.parse(path);
    }