2017-04-18 150 views
0

我是Android Studio的新手,我一直在獲取已存儲到數據庫中的圖像,然後將圖像顯示到GridView中。有沒有一種方法可以獲取存儲在數據庫中的圖像數量,然後逐個顯示它們,每個圖像都位於GridView中的不同單元格中?這是到目前爲止我的代碼:從SQLite數據庫中獲取圖像並將其顯示到GridView Android Studio

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類

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); 
    } 
} 
+0

在數據庫中存儲BLOB是**最糟糕的做法**。改爲存儲**路徑**。 –

+0

這怎麼辦? @Rotwang – Questionnaire

+0

路徑只是普通的字符串。即:「/mnt/sdcard0/somefolder/yourimage.jpg」 –

回答

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); 
    } 
相關問題