简体   繁体   中英

Android: Issue in retrieving image from the sqlite database and showing it at runtime

In my Android application user can insert his/her data (name, age, ect.) and also an image as a profile picture. After inserting data user clicks save button. Then inserted data will be saved in the database. In the database profile picture has blob type.

I also need to retrieve user name and profile picture from the database and show them in a table layout.

Here is my code segment for inserting data into database.

case R.id.btnSave:
        personName = etName.getText().toString();
        date_of_birth = tvDOB.getText().toString();
        age = tvAge.getText().toString();

        int selected_rb_ID = genderGrp.getCheckedRadioButtonId();   
        RadioButton rb = (RadioButton) findViewById(selected_rb_ID);
        gender = rb.getText().toString();
        bloodGrp = spiBloodGrp.getSelectedItem().toString();

        // get byte array from image view
        Drawable d = image.getBackground();
        BitmapDrawable bitDw = ((BitmapDrawable) d);
        Bitmap bitmap = bitDw.getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] imageInByte = stream.toByteArray();

        Person person = new Person();
        person.setName(personName);
        person.setDate_of_birth(date_of_birth);
        person.setAge(age);
        person.setGender(gender);
        person.setBloodGrp(bloodGrp);
        String proPic = new String(imageInByte);
        person.setProfilePic(proPic);

        ContentValues values = new ContentValues();

        //values.put(COLUMN_PROFILE_PICTURE, person.getProfilePic().toString());
        values.put(COLUMN_PROFILE_PICTURE, person.getProfilePic());
        values.put(COLUMN_PERSON_NAME, person.getName());
        values.put(COLUMN_DOB, person.getDate_of_birth());
        values.put(COLUMN_AGE, person.getAge());
        values.put(COLUMN_GENDER, person.getGender());
        values.put(COLUMN_BLOODGRP, person.getBloodGrp());

        DBHelper dbHelper = new DBHelper(this);
        dbHelper.openDataBase();
        if(dbHelper.insertIntoDatabase("EMPerson", values)){
            dbHelper.onUpgrade(myDatabase, 1, 2);
            Toast.makeText(getApplicationContext(), "Your Data has been saved successfully", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(getApplicationContext(), "Oops ! Try again", Toast.LENGTH_SHORT).show();
        }
        dbHelper.closeDatabase();

And this is my code segment for showing data in the table layout.

personList = helper.getPersonList();

loadTableLayouts();

This is my loadTableLayouts() method.

private void loadTableLayouts() {

    int thheight = (int) (getResources().getDimension(R.dimen.cellLpH) / getResources()
            .getDisplayMetrics().density);
    int texthead = (int) (getResources().getDimension(R.dimen.boldtext) / getResources()
            .getDisplayMetrics().density);

    TableRow.LayoutParams rowLp = new TableRow.LayoutParams(
            TableRow.LayoutParams.FILL_PARENT, thheight, 1.0f);
    TableRow.LayoutParams cellLp = new TableRow.LayoutParams(
            TableRow.LayoutParams.FILL_PARENT, thheight, 1.0f);
    TableRow th = new TableRow(this);
    th.setLayoutParams(new TableRow.LayoutParams(
            TableRow.LayoutParams.FILL_PARENT,
            TableRow.LayoutParams.FILL_PARENT));

    TextView thPersonName = new TextView(this);
    thPersonName.setTextSize(texthead);
    thPersonName.setTextColor(Color.RED);
    thPersonName.setText("Name");
    thPersonName.setTypeface(null, Typeface.BOLD);
    thPersonName.setPadding(10, 0, 12, 0);
    th.addView(thPersonName, cellLp);

    TextView thProPic = new TextView(this);
    thProPic.setTextSize(texthead);
    thProPic.setTextColor(Color.RED);
    thProPic.setText("Profile Picture");
    thProPic.setTypeface(null, Typeface.BOLD);
    thProPic.setPadding(10, 0, 12, 0);
    th.addView(thProPic, cellLp);

    tblPerson.addView(th, rowLp);

    if (personList.size() > 0) {
        for (int i = 0; i < personList.size(); i++) {
            final TableRow tr = new TableRow(this);
            tr.setTag(i);
            tr.setLayoutParams(new TableRow.LayoutParams(
                    TableRow.LayoutParams.FILL_PARENT,
                    TableRow.LayoutParams.FILL_PARENT));

            final TextView txtPersonName = new TextView(this);
            txtPersonName.setTextSize(1, 12);
            txtPersonName.setTextColor(Color.BLACK);
            txtPersonName.setText("" + personList.get(i).getName());
            txtPersonName.setPadding(10, 0, 12, 0);
            tr.addView(txtPersonName, cellLp);

            final ImageView imgPic = new ImageView(this);
            imgPic.setImageBitmap(convertByteArrayToBitmap(personList
                    .get(i).getProfilePic().getBytes()));
            imgPic.setPadding(10, 0, 12, 0);
            tr.addView(imgPic, cellLp);

            tr.setBackgroundDrawable(getResources().getDrawable(
                    R.drawable.table_row_selector));
            tr.setVisibility(View.VISIBLE);
            tblPerson.addView(tr, rowLp);

        }
    }
}

I use convertByteArrayToBitmap() method to retrieve image from byte array.

// Retrieve image from byte array:
public static Bitmap convertByteArrayToBitmap(
        byte[] byteArrayToBeCOnvertedIntoBitMap) {
    Bitmap bitMapImage = BitmapFactory.decodeByteArray(
            byteArrayToBeCOnvertedIntoBitMap, 0,
            byteArrayToBeCOnvertedIntoBitMap.length);
    return bitMapImage;
}

This is my getPersonList() method.

public ArrayList<Person> getPersonList() {

    ArrayList<Person> personList = new ArrayList<Person>();
    String sql = "SELECT p.PersonName, p.ProfilePicture "
            + "FROM EMPerson p " + "ORDER BY p.PersonName";
    System.out.println(sql);
    ArrayList<?> stringList = selectRecordsFromDB(sql, null);

    for (int i = 0; i < stringList.size(); i++) {
        ArrayList<?> arrayList = (ArrayList<?>) stringList.get(i);
        ArrayList<?> list = arrayList;
        Person person = new Person();
        person.setName((String) list.get(0));
        person.setProfilePic((String) list.get(1));

        personList.add(person);
    }

    return personList;

}

This is my entity class code segment.

public class Person {
private String profilePic;
private String name, date_of_birth, age, gender, bloodGrp;

public String getProfilePic() {
    return profilePic;
}

public void setProfilePic(String imageInByte) {
    this.profilePic = imageInByte;
}

public String getName() {
    return name;
}
    .........

The problem is this shows table layout at run time but it only shows user name. It's not showing the profile picture. Profile picture is empty. Even though, log cat does not showing any error message.

I would be much obliged if anyone would be so kind enough to explain what's going on here and how can I solve this issue.

Cheers

Android/ Java String cannot hold large input streams.

if you add ImageStream to String, it might not be able to handle it.

You may directly take it to Bitmap instead taking to a string, and set it to imageview.

Looking into memory optimization and performance concerns its not correct to save image data in database.

Save it on SDCard either directly or encoding it and save that URL in database. Retrive image dynamically as and then required.

I would suggest you to convert Image to String using Base64.class and save in DataBase Column. And when displaying get the Image String and convert to Image.

  Bitmap bmp = your_bmap_obj;
  OutputStream stream = new FileOutputStream("/sdcard/test.jpg");
  bmp.compress(CompressFormat.JPEG, 100, stream);

Use this method for converting Image to String

public static String getImageString(String filePath) {

    String imageString = "";

    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);

    options.inSampleSize = calculateInSampleSize(options, reqWidth,
            reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    Bitmap bmp = BitmapFactory.decodeFile(filePath, options);

    bmp = Bitmap.createScaledBitmap(bmp, reqWidth, reqHeight, true);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 70, baos); // bm is the bitmap
    // object
    byte[] byte_arr = baos.toByteArray();
    imageString = Base64.encodeBytes(byte_arr);
    return imageString;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM