Question

I am trying to save the image in imageview alongwith the other fields that user inputs. I wish to store the image in database and it will be retrieved on other page when the data is to be viewed. What changes do i need to make in my "NewPat.java" as well as "PatientInfoDB.java". Here's my code..

public class NewPat extends Activity implements OnClickListener{
//Display pic

    ImageView iv;   
    Intent i;
    final static int cameraData=0;
    Bitmap bmp;
    //from gallery    
    Button buttonLoadImage;
    private static int RESULT_LOAD_IMAGE = 1;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newpat);
        Initialize();
        setCurrentDate();
        addButtonListener();


        //Display pic
        InputStream is=getResources().openRawResource(R.drawable.ic_launcher);
        bmp=BitmapFactory.decodeStream(is);

    }


private void Initialize() {

        //Display pic
        ib=(Button)findViewById(R.id.ibTakePic);
        iv=(ImageView)findViewById(R.id.ivReturnedPic); 


         buttonLoadImage = (Button) findViewById(R.id.bLoadPicture);

        ib.setOnClickListener(this);
     buttonLoadImage.setOnClickListener(this);
}


@Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

        switch (v.getId()) {

        case R.id.bsave:

            //Collecting data from edittexts
            // getting Name
                 first = fname.getText().toString();
                 middle = mname.getText().toString();
                 last = lname.getText().toString();

                //getting the id of selected radio button 
                int genderId = radiogrp.getCheckedRadioButtonId();
                genderButton = (RadioButton) findViewById(genderId);
                 gender = genderButton.getText().toString();

                //Getting DOB
                 date = dob.getText().toString();

                 //getting age
                 age= setage.getText().toString();

                 //getting admission date
                 admm =admitdate.getText().toString();

                 //getting address
                 addr = address.getText().toString();

                 //getting email
                 email=emailid.getText().toString();

                 //getting phone
                 phone = contact.getText().toString();

// How do i collect the image from imageview???? 


                //Inserting in PatientinfoDB
                PatientInfoDB entry = new PatientInfoDB(NewPat.this);
                entry.open();

// here i need to pass the image along with other parameters in database
    entry.createEntry(first,middle,last,gender,date,age,admm,addr,email,phone);
                entry.close();

            break;

            //camera case
        case R.id.ibTakePic:


            Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(takePicture, 0);//zero can be replaced with any action code
            break;


        case R.id.bLoadPicture:

             Intent pickPhoto = new Intent(Intent.ACTION_PICK,
                     android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
          startActivityForResult(pickPhoto , 1);//one can be replaced with any action code              
             break;
        }

    }

Database code

    public class PatientInfoDB {

        public static final String KEY_ROWID = "_id";
        public static final String KEY_FNAME = "pat_fname";
        public static final String KEY_MNAME = "pat_mname";
        public static final String KEY_LNAME="pat_lname";
        public static final String KEY_GENDER="pat_gender";
        public static final String KEY_DOB="pat_dob";
        public static final String KEY_AGE="pat_age";
        public static final String KEY_ADMISSION="pat_admission";
        public static final String KEY_ADDRESS="pat_address";
        public static final String KEY_CONTACT="pat_phone";
        public static final String KEY_EMAILID="pat_email";
        public static final String KEY_PHOTO = "pic_dp"; 


    private static final String DATABASE_NAME = "PatientdataDB";
    private static final String DATABASE_TABLE = "PersonalDetails";

@Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
                    KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    KEY_FNAME + " TEXT NOT NULL, " +
                    KEY_MNAME + " TEXT NOT NULL, " +
                    KEY_LNAME + " TEXT NOT NULL, " +
                    KEY_GENDER + " TEXT NOT NULL, " +
                    KEY_DOB + " TEXT NOT NULL, " +
                    KEY_AGE + " TEXT NOT NULL, " +
                    KEY_ADMISSION + " TEXT NOT NULL, " +
                    KEY_ADDRESS + " TEXT NOT NULL, " +
                    KEY_EMAILID + " TEXT NOT NULL, " +
                    KEY_CONTACT + " TEXT NOT NULL, " +
                    KEY_PHOTO + " BLOB);"
                    );  

        }

public long createEntry(String first, String middle, String last,String gender, String date, String age, String admm, String addr, String email, String phone, byte[] image) {
        // TODO Auto-generated method stub
        ContentValues cv = new ContentValues();

        cv.put(KEY_FNAME, first);
        cv.put(KEY_MNAME, middle);
        cv.put(KEY_LNAME, last);
        cv.put(KEY_GENDER, gender);
        cv.put(KEY_DOB, date);
        cv.put(KEY_AGE, age);
        cv.put(KEY_ADMISSION, admm);
        cv.put(KEY_ADDRESS, addr);
        cv.put(KEY_CONTACT, phone);
        cv.put(KEY_EMAILID, email);
        cv.put(KEY_PHOTO, image);

        //startobv
        //vc.put(KEY_DATETIME, value)

        return ourDatabase.insert(DATABASE_TABLE, null, cv);
    }

OnActivityResult

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK){  
                Uri selectedImage = data.getData();
                iv.setImageURI(selectedImage);
            }

        break; 
        case 1:
            if(resultCode == RESULT_OK){  
                Uri selectedImage = data.getData();
                iv.setImageURI(selectedImage);
            }
        break;
        }


    }

//Page where the pic has to b displayed i added this piece of code

PatientInfoDB entry = new PatientInfoDB(this);
            entry.open();
            Bitmap bm=entry.getPhoto();

        iv.setImageBitmap(bm);

// Added this method in my database i.e. "PatientInfoDB.java"

public Bitmap getPhoto(){
     Cursor c = ourDatabase.rawQuery("SELECT pic_dp FROM PersonalDetails ;", null);
                byte[] byteArray = c.getBlob(0);

                Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    return bm;

}

But i got the error "android.database.CursorIndexOutOfBoundException:Index -1 requested,with a size of 2

Was it helpful?

Solution

Do this to get the bitmap from the imageview:

Bitmap myBitmap= ((BitmapDrawable)image.getDrawable()).getBitmap();

then you need to convert the bitmap to a byte array:

ByteArrayOutputStream stream = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

then you can store it as a blob in the DB

EDIT:

to retrieve the bimap you get the byte array from the db and convert it back to a bitmap

    Cursor c = db.raw......
    byte[] byteArray = c.getBlob(0);

    Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

Now you can just set the ImageView bitmap to the retrieved bitmap.

OTHER TIPS

Instead of storing and retrieving from DB, since your usage is for one time, you should store the image in a public static variable which you can access across whole project.

public static Uri publicSelectedImage; // Write this in NewPat at class level. 

in your onActivityResult() assign value to this variable as following

Uri selectedImage = data.getData();
publicSelectedImage = selectedImage;         // write this line. 

Now from any other activity you can access this variable as following way,

Uri publicImage = NewPat.publicSelectedImage;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top