jeudi 27 août 2015

Storing and retrieving image from SQLite - blob

I am trying to show the user profile details in offline mode. The basic info such as Name,Image,Address,Email.

I've read about blob, and saved the image in byte array form in blob.

Now while retrieving I've converted the byte array to bitmap and it is null always. :(

Code snippet :

Image is picked from gallery on button click:

photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                photoPickerIntent.setType("image/*");
                startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);
            }
        });

To pick up image and convert it string and byte array:

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data); 
        try
        { 
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data)
            { 
                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA }; 
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null); 
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                imgPath = cursor.getString(columnIndex);
                cursor.close(); 
                String fileNameSegments[] = imgPath.split("/");
                fileName = fileNameSegments[fileNameSegments.length - 1]; 
                BitmapFactory.Options options = null;
                options = new BitmapFactory.Options();
                options.inSampleSize = 3;
                bitmap = BitmapFactory.decodeFile(imgPath,options);
                ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o); 
                final int REQUIRED_SIZE = 140; 
                int width_tmp = o.outWidth, height_tmp = o.outHeight;
                int scale = 1;
                while (true) {
                    if (width_tmp / 2 < REQUIRED_SIZE
                            || height_tmp / 2 < REQUIRED_SIZE) {
                        break;
                    }
                    width_tmp /= 2;
                    height_tmp /= 2;
                    scale *= 2;
                }

                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize = scale;

                bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2); 
                images.setImageBitmap(BitmapFactory.decodeFile(imgPath)); 
                images.setVisibility(View.VISIBLE); 
                ;

                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                byte_arr = stream.toByteArray();

                encodedString = Base64.encodeToString(byte_arr, Base64.DEFAULT); 
            }
            else
            {
                Toast.makeText(this, "You haven't picked Image",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
        }
    }

Now the basic details and the encoded string are sent to server to save in db. On success am saving the same details in SQLite.

@Override
        protected void onPostExecute(Void aVoid)
        {
            dialog1.dismiss();
            if(code==200)
            {
                Intent intent = new Intent(getApplicationContext(), SuccessfulLogin.class);
                startActivity(intent);
                finish(); 

                DBhelper dbHelper = new DBhelper(Edit.this);
                Employee employee_One = new Employee(byte_arr,  name.getText().toString(), mobile.getText().toString(),address.getText().toString(),birth.getText().toString(),UserID);
//                Employee employee_One = new Employee(byte_arr,  name.getText().toString(), mobile.getText().toString(),address.getText().toString(),city.getText().toString(),birth.getText().toString(),UserID);
                dbHelper.open();
                dbHelper.insertEmpDetails(employee_One);
                dbHelper.close();
                dbHelper.open();
                employee_One = dbHelper.retriveEmpDetails();
                dbHelper.close();
                /*
                Log.e("Edit Profile Details", "Address --" + employee_One.getAddress() + "\n name " + employee_One.getName()
                        + "\n Image " + Arrays.toString(employee_One.getBitmap()) + " \n mobile--" + employee_One.getPhoneNumber()
                        + "\n DOB " + (employee_One.getBirth()) + " \n email--" + employee_One.getEmail());

                Log.e("Profile Values", "Address --" + address.getText().toString() + "\n name " +
                        name.getText().toString() + "\n Image " + Arrays.toString(byte_arr) + " \n mobile--" +mobile.getText().toString());
*/
                Log.e("byte_arr", "" + Arrays.toString(byte_arr));

                Toast.makeText(getBaseContext(), "Details updated successfully..", Toast.LENGTH_LONG).show();
            }
            else
            {
                Toast.makeText(getBaseContext(), "Sorry, Try Again",Toast.LENGTH_LONG).show();
            }
            super.onPostExecute(aVoid);
        }

Am using the same byte array here.

Employee constructor:

public Employee(byte[] b, String n, String k, String a, String bt, String e)
    {
        bmp = b;
        Log.e("\nEmployee bmp", "" + Arrays.toString(this.bmp));
        name = n;
        _phone_number = k;
        _address = a; 
        _birth = bt;
        _email = e;
    }

Retrieving data in offline mode:

if(isNetworkAvailable())
        {
            new DisplayDetails().execute(); 
        }
        else
        {
            DBhelper dbHelper = new DBhelper(ViewProfile.this);

            dbHelper.open();
            employee_One = dbHelper.retriveEmpDetails();
            dbHelper.close();

            Log.e("Profile Details", "Address --" + employee_One.getAddress() + "\n name " +
                    employee_One.getName() + "\n Image " + Arrays.toString(employee_One.getBitmap()) + " \n mobile--" + employee_One.getPhoneNumber());

            name.setText(employee_One.getName());
            address.setText(employee_One.getAddress());
            mobile.setText(employee_One.getPhoneNumber());
            birth.setText(employee_One.getBirth());
            email.setText(employee_One.getEmail());
            byte[] outImage=employee_One.getBitmap();
            ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
            Bitmap theImage = BitmapFactory.decodeStream(imageStream);
            Image.setImageBitmap(theImage);

            /*
            ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
            Bitmap theImage = BitmapFactory.decodeStream(imageStream);
            Image.setImageBitmap(theImage);

            ************

            ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
            Bitmap theImage = BitmapFactory.decodeStream(imageStream);
            Log.e("\nbitmap", "" + theImage +"\n outImage--" + Arrays.toString(outImage));

            ****************

            ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(outImage);
            Bitmap bitmap = BitmapFactory.decodeStream(arrayInputStream);

            ******************

            int intByteCount = outImage.length;
            int[] intColors = new int[intByteCount / 3];
            int intWidth = 2;
            int intHeight = 2;
            final int intAlpha = 255;
            if ((intByteCount / 3) != (intWidth * intHeight)) {
                throw new ArrayStoreException();
            }
            for (int intIndex = 0; intIndex < intByteCount - 2; intIndex = intIndex + 3) {
                intColors[intIndex / 3] = (intAlpha << 24) | (outImage[intIndex] << 16) | (outImage[intIndex + 1] << 8) | outImage[intIndex + 2];
            }
            Bitmap bmpImage = Bitmap.createBitmap(intColors, intWidth, intHeight, Bitmap.Config.ARGB_8888);
            */

        }

I've tried all the commented code.But Failed

Every time I get null in bitmap and image is not assigned to ImageView. At the same time am not able to add more than 6 columns in my table.It is giving various errors if I try to add 7th column.

I don't understand where it is going wrong..

Any kind of help would be much appreciated.

Thank you.

Aucun commentaire:

Enregistrer un commentaire