从图库/相机中选择图像并在ListView中显示

时间:2015-03-11 07:03:50

标签: android image listview

我想将从图库或相机中选择的图像设置为ListView。选定的图像存储在sqlite db。

以下是我的OnActivityResult类:

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;
        if(resultCode == RESULT_OK) {
            switch (requestCode) {
                case CAMERA_REQUEST:

                    Bundle extras = data.getExtras();

                    if (extras != null) {
                        Bitmap yourImage = extras.getParcelable("data");
                        // convert bitmap to byte
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
                        byte imageInByte[] = stream.toByteArray();
                        Log.e("outputbeforeconversion", imageInByte.toString());
                        // Inserting Contacts
                        Log.d("Insert: ", "Inserting ..");
                        db.addContact(new Contact("Android", imageInByte));
                        Intent i = new Intent(ForSaleAndRentUpload.this,
                                ForSaleAndRentUpload.class);
                        startActivity(i);
                        finish();

                    }
                    break;
                case PICK_FROM_GALLERY:
                    Bundle extras2 = data.getExtras();

                    if (extras2 != null) {
                        Bitmap yourImage = extras2.getParcelable("data");
                        // convert bitmap to byte
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
                        byte imageInByte[] = stream.toByteArray();
                        Log.e("outputbeforeconversion", imageInByte.toString());
                        // Inserting Contacts
                        Log.d("Insert: ", "Inserting ..");
                        db.addContact(new Contact("Android", imageInByte));
                        Intent i = new Intent(ForSaleAndRentUpload.this,
                                ForSaleAndRentUpload.class);
                        startActivity(i);
                        finish();
                    }

                    break;
            }
        }
    }

我有这个对话框帮助我选择直接从图库或相机中选择。当我选择从任何选项中选择图像时,我会进行相同的活动,但ListView为空。

适配器:

public class ContactImageAdapter extends ArrayAdapter<Contact> {

    Context context;
    int layoutResourceId;
    // BcardImage data[] = null;
    ArrayList<Contact> data=new ArrayList<Contact>();
    public ContactImageAdapter(Context context, int layoutResourceId, ArrayList<Contact> data) {
        super(context, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.context = context;
        this.data = data;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        ImageHolder holder = null;

        if(row == null)
        {
            LayoutInflater inflater = ((Activity)context).getLayoutInflater();
            row = inflater.inflate(layoutResourceId, parent, false);

            holder = new ImageHolder();
            holder.txtTitle = (TextView)row.findViewById(R.id.textInvi);
            holder.imgIcon = (ImageView)row.findViewById(R.id.listImageItem);
            row.setTag(holder);
        }
        else
        {
            holder = (ImageHolder)row.getTag();
        }

        Contact picture = data.get(position);
        holder.txtTitle.setText(picture._name);
        //convert byte to bitmap take from contact class

        byte[] outImage=picture._image;
        ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
        Bitmap theImage = BitmapFactory.decodeStream(imageStream);
        holder.imgIcon.setImageBitmap(theImage);
        return row;

    }

    static class ImageHolder
    {
        ImageView imgIcon;
        TextView txtTitle;
    }




}

存储图像的数据库:

public class DataBaseHandler extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "imagedb";
    private static final String TABLE_CONTACTS = "contacts";

    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_IMAGE = "image";


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




    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_IMAGE + " BLOB" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

        // Create tables again
        onCreate(db);

    }

    public void addContact(Contact contact){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact._name); // Contact Name
        values.put(KEY_IMAGE, contact._image); // Contact Phone

        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection

    }

    Contact getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                        KEY_NAME, KEY_IMAGE }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getBlob(2));

        // return contact
        return contact;

    }

    // Getting All Contacts
    public List<Contact> getAllContacts() {
        List<Contact> contactList = new ArrayList<Contact>();
        // Select All Query
        String selectQuery = "SELECT  * FROM contacts ORDER BY name";

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setImage(cursor.getBlob(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }
        // close inserting data from database
        db.close();
        // return contact list
        return contactList;

    }

    // Updating single contact
    public int updateContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName());
        values.put(KEY_IMAGE, contact.getImage());

        // updating row
        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });

    }

    // Deleting single contact
    public void deleteContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
        db.close();
    }

    // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

选择图像时记录:

03-11 07:00:45.622    1773-1773/com.iwillcode.realestate E/Selected Item﹕ 1
03-11 07:00:46.507    1773-1773/com.iwillcode.realestate W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
03-11 07:00:47.476    1773-1796/com.iwillcode.realestate W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-11 07:00:47.477    1773-1796/com.iwillcode.realestate W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa3a76c00, error=EGL_SUCCESS
03-11 07:00:51.252    1773-1796/com.iwillcode.realestate W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-11 07:00:51.252    1773-1796/com.iwillcode.realestate W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa373b080, error=EGL_SUCCESS
03-11 07:00:52.710    1773-1773/com.iwillcode.realestate E/Selected Item﹕ 1
03-11 07:00:53.667    1773-1773/com.iwillcode.realestate W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
03-11 07:00:54.456    1773-1796/com.iwillcode.realestate W/EGL_emulation﹕ eglSurfaceAttrib not implemented
03-11 07:00:54.456    1773-1796/com.iwillcode.realestate W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa3a76c00, error=EGL_SUCCESS

1 个答案:

答案 0 :(得分:0)

工作代码(主要活动)

   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CameraActivity = this;

        imageView = (ListView) findViewById(R.id.image_view);
        database = new ImageDatabase(this);

        //Set OnClick Listener to button view
        captureImage = (Button) findViewById(R.id.capture_image);
        captureImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                isStoragePermissionGranted();
            }
        });

        //long press on image
        imageView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                isStoragePermissionGranted();
                return true;
            }
        });
    }

    private void startDialog() {
        AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(
                CameraActivity);
        myAlertDialog.setTitle("Upload Pictures Option");
        myAlertDialog.setMessage("How do you want to set your picture?");

        myAlertDialog.setPositiveButton("Gallery",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        Intent i = new Intent();
                        i.setType("image/*");
                        i.setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(i.createChooser(i, "Result load Image")
                                , GALLERY_IMAGE);
                    }
                });

        myAlertDialog.setNegativeButton("Camera",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {

                        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(cameraIntent, CAMERA_REQUEST);
                    }
                });
        myAlertDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        //Code for @CAMERA_REQUEST
        if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {

            theImage = (Bitmap) data.getExtras().get("data");
        }

        //Code for @GALLERY_IMAGE
        if (requestCode == GALLERY_IMAGE && resultCode == RESULT_OK) {
            try {
                Uri imageUri = data.getData();
                InputStream imageStream = getContentResolver().openInputStream(imageUri);
                theImage = BitmapFactory.decodeStream(imageStream);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            theImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();

            SQLiteDatabase db = database.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put(ImageDatabase.KEY_IMG_URL, byteArray);
            db.insert(ImageDatabase.TABLE_NAME, null, values);
            //db.update(ImageDatabase.TABLE_NAME, values, null, null);
            db.close();

    }

    public void getTheImage() {

        SQLiteDatabase db = database.getReadableDatabase();

        Cursor cursor = (Cursor) db.rawQuery(" SELECT * FROM " + ImageDatabase.TABLE_NAME,
                null, null);
        if (cursor.moveToFirst()) {
            byte[] imgByte = cursor.getBlob(cursor.getColumnIndex(ImageDatabase.KEY_IMG_URL));
            //cursor.close();
            b = BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);

        }
        //if (cursor != null && !cursor.isClosed()) {
         //   cursor.close();
        //}
        mImageAdapter = new ImageAdapter(this,cursor);
        imageView.setAdapter(mImageAdapter);
    }

    //Storage permission
    public boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                Log.v(TAG, "Permission is granted");
                startDialog();
                return true;
            } else {

                Log.v(TAG, "Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]
                        {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        } else { //permission is automatically granted on sdk<23 upon installation
            Log.v(TAG, "Permission is granted");
            startDialog();
            return true;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        getTheImage();
    }
}

图像适配器

public class ImageAdapter extends CursorAdapter {
    public ImageAdapter(Context context, Cursor c) {
        super(context, c, 0);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        // Inflate a list item view using the layout specified in list_item.xml
        return LayoutInflater.from(context).inflate(R.layout.list_item,parent, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        // Find individual views that we want to modify in the list item layout
        ImageView imageView = (ImageView) view.findViewById(R.id.image);

        byte[] imgByte = cursor.getBlob(cursor.getColumnIndex(ImageDatabase.KEY_IMG_URL));
        Bitmap b = BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
        imageView.setImageBitmap(b);
    }
}

数据库类

公共类ImageDatabase扩展了SQLiteOpenHelper { 公共上下文上下文;

//Database name
public static final String DATABASE_NAME = "imageData";

//Version
public static final int DATABASE_VERSION = 1;

//SQL Table detail;
public static final String TABLE_NAME = "DATA";
public static final String KEY_ID = "_id";
public static final String KEY_IMG_URL = "imagedisplayed";

public ImageDatabase(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.context = context;
    //Toast.makeText(context, "Constructor called", Toast.LENGTH_LONG).show();
}

public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID +
        " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_IMG_URL + " BLOB " + ")";
public static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME + "";

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL(DROP_TABLE);
    onCreate(db);
}

public void deleteEntry(long row) {
    SQLiteDatabase sqLiteDatabase = getWritableDatabase();
    sqLiteDatabase.delete(TABLE_NAME, KEY_ID + "=" + row, null);
}

}

别忘了在清单中提及用户权限代码。