从库中选择一个图像并存储并在sqlite数据库中检索它

时间:2016-09-29 13:38:36

标签: android sqlite

我是Android的新手,我对Android中的sqlite有所了解。我知道如何从图库中检索图像。任何人都可以帮我将检索到的图像存储在SQL中并检索吗?

我试图存储和检索。我在这里分享我的代码:

我的数据库处理程序类:

public class DatabaseHandler extends SQLiteOpenHelper
{
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "image";
    private static final String TABLE_NAME = "store";
    private static final String COLUMN_IMAGE = "img";
    private static final String COLUMN_ID = "id";
    private static final String CREATE_TABLE_IMAGE =
            "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +COLUMN_IMAGE + " BLOB NOT NULL " + ")";

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

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        db.execSQL(CREATE_TABLE_IMAGE);
        Log.i("Table..","Created");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
        db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_IMAGE);
        onCreate(db);
    }

    public void insertBitmap(Bitmap bmp)
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
        byte[] buffer=out.toByteArray();

        SQLiteDatabase db = this.getWritableDatabase();

        db.beginTransaction();
        ContentValues values;

        try
        {
            values = new ContentValues();
            values.put("img",buffer);

            db.insert(TABLE_NAME, null, values);
            db.setTransactionSuccessful();
            Log.i("Image..","Inserted..");
        }
        catch (SQLiteException e)
        {
            e.printStackTrace();

        }
        finally
        {
            db.endTransaction();
            // End the transaction.
            db.close();
            // Close database
        }
    }

    public Bitmap getBitmap(int id)
    {
        Bitmap bitmap = null;
        SQLiteDatabase db = this.getReadableDatabase();

        db.beginTransaction();
        try
        {
            String selectQuery = "SELECT * FROM "+ TABLE_NAME+" WHERE id = " + id;
            Cursor cursor = db.rawQuery(selectQuery, null);

            int id_value = cursor.getInt(0);
            POJO pojo = new POJO(id_value);
            Log.i("AUTO ID..",cursor.getString(0));

            if(cursor.getCount() >0)
            {
                while (cursor.moveToNext())
                {
                    byte[] blob = cursor.getBlob(cursor.getColumnIndex(COLUMN_IMAGE));
                    bitmap= BitmapFactory.decodeByteArray(blob, 0, blob.length);
                }

            }
            db.setTransactionSuccessful();
        }
        catch (SQLiteException e)
        {
            e.printStackTrace();

        }
        finally
        {
            db.endTransaction();
            // End the transaction.
            db.close();
            // Close database
        }
        return bitmap;
    }

}

我的活动课程:

public class MainActivity extends AppCompatActivity
{
    DatabaseHandler dbh;
    POJO pojo;
    ImageView imageView;
    TextView textView;
    private static int RESULT_LOAD_IMG = 1;
    String picturePath;
    int id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        imageView = (ImageView) findViewById(R.id.image);
        textView = (TextView)findViewById(R.id.textView);

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMG);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

      try
       {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            {
                if (!Settings.System.canWrite(this) && (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data))
                {
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE}, 2909);

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

                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);

                    assert cursor != null;
                    cursor.moveToFirst();

                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    Bitmap bm = BitmapFactory.decodeFile(picturePath);
                    Log.i("Hii...", "After Cursor..");
                    getImage(bm);

                }
            }


        {
            Toast.makeText(getApplicationContext(), "Something went wrong", Toast.LENGTH_LONG).show();
        }
    }

    public void getImage(Bitmap bm)
    {

        Log.i("Hi..","In getImage");        int id = pojo.getId();
        dbh.insertBitmap(bm);
        imageView.setImageBitmap(dbh.getBitmap(id));
    }
}

POJO课程:

public class POJO {
    int id;

    public POJO (int id1)
    {
        this.id = id1;
    }

    public int getId()
    {
        return id;
    }
}

2 个答案:

答案 0 :(得分:1)

我建议您将图像的URI(作为字符串)存储到数据库中,而不是将字节直接放入数据库中。

这将更加精确和标准。

更新:

首先将图像的URI作为字符串存储到数据库中,以便以后使用它:

String str = imageUri.toString();
databaseHelper.insert(str); 

当您想加载图片时,您可以简单地解码您过去保存的数据库中的URI:

String str = databaseHelper.retrive(someId);
Uri imageUri = Uri.parse(str);  

请注意,imageUri是名为Uri的包装中图像的地址。它只是一种呈现Android框架使用的路径和地址的方式。

答案 1 :(得分:1)

我已经对您的代码进行了一些更改,现在它正在按预期工作。

更改了DatabaseHandler课程:

public class DatabaseHandler extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "image";
    private static final String TABLE_NAME = "store";
    private static final String COLUMN_IMAGE = "img";
    private static final String COLUMN_ID = "id";
    private static final String CREATE_TABLE_IMAGE =
            "CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_IMAGE + " BLOB NOT NULL " + ")";

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_TABLE_IMAGE);
        Log.i("Table..", "Created");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + CREATE_TABLE_IMAGE);
        onCreate(db);
    }

    public long insertBitmap(Bitmap bmp) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
        byte[] buffer = out.toByteArray();

        SQLiteDatabase db = this.getWritableDatabase();

        db.beginTransaction();
        ContentValues values;

        long id = 0;

        try {
            values = new ContentValues();
            values.put("img", buffer);

            id = db.insert(TABLE_NAME, null, values);
            db.setTransactionSuccessful();
            Log.i("Image..", "Inserted..");
        } catch (SQLiteException e) {
            e.printStackTrace();

        } finally {
            db.endTransaction();
            // End the transaction.
            db.close();
            // Close database
        }
        return id;
    }

    public Bitmap getBitmap(int id) {
        Bitmap bitmap = null;
        SQLiteDatabase db = this.getReadableDatabase();

        db.beginTransaction();
        try {
            String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE id = " + id;
            Cursor cursor = db.rawQuery(selectQuery, null);

            if (cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    byte[] blob = cursor.getBlob(cursor.getColumnIndex(COLUMN_IMAGE));
                    bitmap = BitmapFactory.decodeByteArray(blob, 0, blob.length);
                }

            }
            db.setTransactionSuccessful();
        } catch (SQLiteException e) {
            e.printStackTrace();

        } finally {
            db.endTransaction();
            // End the transaction.
            db.close();
            // Close database
        }
        return bitmap;
    }
}

更改了MainActivity课程:

public class MainActivity extends AppCompatActivity
{
    DatabaseHandler dbh;
    POJO pojo;
    ImageView imageView;
    TextView textView;
    private static int RESULT_LOAD_IMG = 1;
    String picturePath;
    int id;
    public final int REQUEST_CODE_FOR_PERMISSIONS = 654;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.image);
        textView = (TextView)findViewById(R.id.textView);

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMG);
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(
                        this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_CODE_FOR_PERMISSIONS);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == RESULT_LOAD_IMG){
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);

            assert cursor != null;
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();
            Bitmap bm = BitmapFactory.decodeFile(picturePath);
            Log.i("Hii...", "After Cursor..");
            getImage(bm);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == REQUEST_CODE_FOR_PERMISSIONS){
            //You need to handle permission results, if user didn't allow them.
        }
    }

    public void getImage(Bitmap bm) {

        Log.i("Hi..", "In getImage "+bm);
        dbh = new DatabaseHandler(this);
        int id = (int) dbh.insertBitmap(bm);
        imageView.setImageBitmap(dbh.getBitmap(id));
    }
}

我在HTC marshmallow设备上测试了这段代码,它运行正常。当我第一次安装这个应用程序时,它会询问我的权限,并且我已经允许这两个权限。