Neha Tyagi
Neha Tyagi

Reputation: 3821

Retrieving image from sqlite

I have created a databse that contains surveyname and image. The image is inserted into the databse as bytearray(BLOB) correctly but when i m trying to retrieve the images it gives some random value. when i use if condition for finding the image it returns a random value and when i use while it has resulted into infinite loop with random values.

public class CaptureSignature extends Fragment implements OnClickListener {
     LinearLayout mContent;
        signature mSignature;
        Button mClear, mGetSign, mCancel;
        public static String tempDir;
        public int count = 1;
        public String current = null;
        private Bitmap mBitmap;
        View mView;
        File mypath;
        Context context;

        private String uniqueId;
        private EditText yourName;
       // private DatabaseMethods db;
       // private DatabaseHandler db;
        DatabaseMethods db=new DatabaseMethods(getActivity());
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
        }
        //@Override
        public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        db=new DatabaseMethods(getActivity());
        //db=new DatabaseHandler(getActivity());
        //db.open();

        //Toast toast = Toast.makeText(context,"hj", Toast.LENGTH_SHORT);
        //toast.show();
        }
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View viewFrag = inflater.inflate(R.layout.signature, container, false);
         //this.requestWindowFeature(Window.FEATURE_NO_TITLE);
         // DatabaseMethods db=new DatabaseMethods(this);

         tempDir = Environment.getExternalStorageDirectory() + "/" + getResources().getString(R.string.external_dir) + "/";
         ContextWrapper cw = new ContextWrapper(getActivity());
         File directory = cw.getDir(getResources().getString(R.string.external_dir), Context.MODE_PRIVATE);
         prepareDirectory();
         uniqueId = getTodaysDate() + "_" + getCurrentTime() + "_" + Math.random();
         current = uniqueId + ".png";
         mypath= new File(directory,current);
         Log.e("path"," "+mypath);
         mContent = (LinearLayout)viewFrag. findViewById(R.id.linearLayout);
         mSignature = new signature(getActivity(), null);
         mSignature.setBackgroundColor(Color.WHITE);
         mContent.addView(mSignature, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
         mClear = (Button)viewFrag.findViewById(R.id.clear);
         mGetSign = (Button)viewFrag.findViewById(R.id.getsign);
         mGetSign.setEnabled(false);
         mCancel = (Button)viewFrag.findViewById(R.id.cancel);
         mView = mContent;
         yourName = (EditText)viewFrag.findViewById(R.id.yourName);

            mClear.setOnClickListener(new OnClickListener()
            {       
                public void onClick(View v)
                {
                    Log.v("log_tag", "Panel Cleared");
                    mSignature.clear();
                    mGetSign.setEnabled(false);
                }
            });

            mGetSign.setOnClickListener(new OnClickListener()
            {       
                public void onClick(View v)
                {
                    Log.v("log_tag", "Panel Saved");
                    boolean error = captureSignature();
                    if(!error){
                        mView.setDrawingCacheEnabled(true);
                        mSignature.save(mView);
                        /*Bundle b = new Bundle();
                        b.putString("status", "done");
                        Intent intent = new Intent();
                        intent.putExtras(b);
                        setResult(RESULT_OK,intent);  
                        finish();*/
                    }
                }
            });

            mCancel.setOnClickListener(new OnClickListener()
            {       
                public void onClick(View v)
                {
                    Log.v("log_tag", "Panel Canceled");
                    /*Bundle b = new Bundle();
                    b.putString("status", "cancel");
                    Intent intent = new Intent();
                    intent.putExtras(b);
                    setResult(RESULT_OK,intent);
                    finish();*/
                }
            });
        return viewFrag;
        }

       /* @Override
            protected void onDestroy() {
            Log.w("GetSignature", "onDestory");
            super.onDestroy();
        }*/

        private boolean captureSignature() {

            boolean error = false;
            String errorMessage = "";


            if(yourName.getText().toString().equalsIgnoreCase("")){
                errorMessage = errorMessage + "Please enter your Name\n";
                error = true;
            }  

            if(error){
                Toast toast = Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.TOP, 105, 50);
                toast.show();
            }

            return error;
        }

        private String getTodaysDate() {

            final Calendar c = Calendar.getInstance();
            int todaysDate =     (c.get(Calendar.YEAR) * 10000) +
            ((c.get(Calendar.MONTH) + 1) * 100) +
            (c.get(Calendar.DAY_OF_MONTH));
            Log.w("DATE:",String.valueOf(todaysDate));
            return(String.valueOf(todaysDate));

        }

        private String getCurrentTime() {

            final Calendar c = Calendar.getInstance();
            int currentTime =     (c.get(Calendar.HOUR_OF_DAY) * 10000) +
            (c.get(Calendar.MINUTE) * 100) +
            (c.get(Calendar.SECOND));
            Log.w("TIME:",String.valueOf(currentTime));
            return(String.valueOf(currentTime));

        }


        private boolean prepareDirectory()
        {
            try
            {
                if (makedirs())
                {
                    return true;
                } else {
                    return false;
                }
            } catch (Exception e)
            {
                e.printStackTrace();
                Toast.makeText(context, "Could not initiate File System.. Is Sdcard mounted properly?", 1000).show();
                return false;
            }
        }

        private boolean makedirs()
        {
            File tempdir = new File(tempDir);
            if (!tempdir.exists())
                tempdir.mkdirs();

            if (tempdir.isDirectory())
            {
                File[] files = tempdir.listFiles();
                for (File file : files)
                {
                    if (!file.delete())
                    {
                        System.out.println("Failed to delete " + file);
                    }
                }
            }
            return (tempdir.isDirectory());
        }

        public class signature extends View
        {
            private static final float STROKE_WIDTH = 5f;
            private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
            private Paint paint = new Paint();
            private Path path = new Path();
            Context context;

            private float lastTouchX;
            private float lastTouchY;
            private final RectF dirtyRect = new RectF();

            public signature(Context context, AttributeSet attrs)
            {
                super(context, attrs);
                paint.setAntiAlias(true);
                paint.setColor(Color.BLACK);
                paint.setStyle(Paint.Style.STROKE);
                paint.setStrokeJoin(Paint.Join.ROUND);
                paint.setStrokeWidth(STROKE_WIDTH);
            }

            public void save(View v)
            {
                Log.v("log_tag", "Width: " + v.getWidth());
                Log.v("log_tag", "Height: " + v.getHeight());
                if(mBitmap == null)
                {
                    mBitmap =  Bitmap.createBitmap (mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);;
                }
                Canvas canvas = new Canvas(mBitmap);
                try
                {
                    FileOutputStream mFileOutStream = new FileOutputStream(mypath);
                    v.draw(canvas);
                    mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStream);
                    Log.e("imageinto",""+mBitmap);
                    mFileOutStream.flush();
                    mFileOutStream.close();
                    String url = Images.Media.insertImage(getActivity().getContentResolver(), mBitmap, "title", null);
                    Log.v("log_tag","url: " + url);
                    ByteArrayOutputStream baos=new  ByteArrayOutputStream();
                    mBitmap.compress(Bitmap.CompressFormat.PNG, 90,baos);
                    byte[] byteData=baos.toByteArray();
                    Log.e("imageintobyedata",""+byteData);
                    Bitmap bmp=BitmapFactory.decodeByteArray(byteData,0,byteData.length);
                    Log.e("imageretrieved",""+bmp);
                    db.open();
                    Log.e("after","database open");
                    db.storeImage(byteData);
                    //In case you want to delete the file
                    //boolean deleted = mypath.delete();
                    //Log.v("log_tag","deleted: " + mypath.toString() + deleted);
                    //If you want to convert the image to string use base64 converter

                }
                catch(Exception e)
                {
                    Log.v("log_tag", e.toString());
                }
            }

            public void clear()
            {
                path.reset();
                invalidate();
            }

            @Override
            protected void onDraw(Canvas canvas)
            {
                canvas.drawPath(path, paint);
            }

            @Override
            public boolean onTouchEvent(MotionEvent event)
            {
                float eventX = event.getX();
                float eventY = event.getY();
                mGetSign.setEnabled(true);

                switch (event.getAction())
                {
                case MotionEvent.ACTION_DOWN:
                    path.moveTo(eventX, eventY);
                    lastTouchX = eventX;
                    lastTouchY = eventY;
                    return true;

                case MotionEvent.ACTION_MOVE:

                case MotionEvent.ACTION_UP:

                    resetDirtyRect(eventX, eventY);
                    int historySize = event.getHistorySize();
                    for (int i = 0; i < historySize; i++)
                    {
                        float historicalX = event.getHistoricalX(i);
                        float historicalY = event.getHistoricalY(i);
                        expandDirtyRect(historicalX, historicalY);
                        path.lineTo(historicalX, historicalY);
                    }
                    path.lineTo(eventX, eventY);
                    break;

                default:
                    debug("Ignored touch event: " + event.toString());
                    return false;
                }

                invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
                        (int) (dirtyRect.top - HALF_STROKE_WIDTH),
                        (int) (dirtyRect.right + HALF_STROKE_WIDTH),
                        (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

                lastTouchX = eventX;
                lastTouchY = eventY;

                return true;
            }

            private void debug(String string){
            }

            private void expandDirtyRect(float historicalX, float historicalY)
            {
                if (historicalX < dirtyRect.left)
                {
                    dirtyRect.left = historicalX;
                }
                else if (historicalX > dirtyRect.right)
                {
                    dirtyRect.right = historicalX;
                }

                if (historicalY < dirtyRect.top)
                {
                    dirtyRect.top = historicalY;
                }
                else if (historicalY > dirtyRect.bottom)
                {
                    dirtyRect.bottom = historicalY;
                }
            }

            private void resetDirtyRect(float eventX, float eventY)
            {
                dirtyRect.left = Math.min(lastTouchX, eventX);
                dirtyRect.right = Math.max(lastTouchX, eventX);
                dirtyRect.top = Math.min(lastTouchY, eventY);
                dirtyRect.bottom = Math.max(lastTouchY, eventY);
            }
        }

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

        }
    }


public class DatabaseMethods {
        private static final String databaseName = "Demo11";  
        private static final int databaseVersion = 10;

        private static final String imagestable =  
                "CREATE TABLE IF NOT EXISTS image (SURVEYNAME TEXT,IMAGE BLOB);";  
        private final Context context;   
        private DatabaseHelper DBHelper;  
        private SQLiteDatabase db;  
        Cursor cursor;  
        int count;  
        boolean isProjectNamePresent=false;  
        boolean isProfileNamePresent = false;  

        public DatabaseMethods(Context ctx)   
        {  
            Log.e("inside","database method");
            this.context = ctx;  
            DBHelper = new DatabaseHelper(context);  
        }  

        private static class DatabaseHelper extends SQLiteOpenHelper   
        {  

            public DatabaseHelper(Context context)   
            {  

                super(context, databaseName, null, databaseVersion);  
            }  
            @Override  
            public void onCreate(SQLiteDatabase db)   
            {  
                 Log.e("insideOnCreate","database method1");  
                db.execSQL(imagestable);  
            }  

            @Override  
            public void onUpgrade(SQLiteDatabase db, int oldVersion,int newVersion)   
            {  

                db.execSQL("DROP TABLE IF EXISTS image");  
                onCreate(db);  
            }  

        }      

        //---opens the database---  
        public DatabaseMethods open() throws SQLException   
        {     
            db = DBHelper.getWritableDatabase();  
            return this;  
        }  

        //---closes the database---      
        public void close()   
        {  
            DBHelper.close();  
        } 


        public void getAllRecords()
        {
            String survey="mobile";
            String query="SELECT IMAGE FROM image WHERE SURVEYNAME='"+survey+"'";

            //SQLiteDatabase db=this.getWritableDatabase();
            Cursor c=db.rawQuery(query,null);
            int col=c.getColumnIndex("IMAGE");
            Log.e("columnindex",""+col);
            if(c.moveToFirst())
            {
                byte[] blobData=c.getBlob(col);
                Log.e("cursorimage",""+blobData);
            }
        }


 public void storeImage(byte[] imgData)  
    {  
        String query; 
        String image1=imgData.toString();
        String survey="mobile";
        Log.e("imagename",image1);
        query = "INSERT INTO image (SURVEYNAME,IMAGE) 
        VALUE('"+survey+"','"+imgData+"')";
        Toast.makeText(context,"ImageInserted",Toast.LENGTH_LONG).show();
        db.execSQL(query);  
    }




    }

Upvotes: 0

Views: 731

Answers (3)

Neha Tyagi
Neha Tyagi

Reputation: 3821

I have found the altaernate solution to my problem i have decoded my image using base64 and saved it as varchar and then encoded it again. Its working perfetctly for me... 1. My capture image file

ByteArrayOutputStream baos=new  ByteArrayOutputStream();
                    mBitmap.compress(Bitmap.CompressFormat.PNG, 90,baos);
                    byte[] byteData=baos.toByteArray();
                    String imageEncoded=Base64.encodeToString(byteData,Base64.DEFAULT);
  1. Database file

    private static final String imagestable =
    "CREATE TABLE IF NOT EXISTS image (SURVEYNAME TEXT,IMAGE VARCHAR2(500));";

    public void storeImage(byte[] imgData)
    {
    String query; String image1=imgData.toString(); String survey="mobile"; Log.e("imagename",image1); query = "INSERT INTO image (SURVEYNAME,IMAGE) VALUES ('"+survey+"','"+imgData+"')"; Toast.makeText(context,"ImageInserted",Toast.LENGTH_LONG).show(); db.execSQL(query);
    }

  2. Decoding

    byte[] decodeByteArray=Base64.decode(image,0); Bitmap bmp=BitmapFactory.decodeByteArray(decodeByteArray,0,decodeByteArray.length); Log.e("BITMAPCONVERSION",""+bmp); img.setImageBitmap(bmp);

Upvotes: 2

Vaibhav Ajay Gupta
Vaibhav Ajay Gupta

Reputation: 473

This is an alternate method to do same. Download the image on device and save the path of image in the database and use that path where ever required.

Upvotes: 0

Vijju
Vijju

Reputation: 3508

To get back image from bytes you need to convert bytes to bitmap like :

byte[] imgBytes;
Bitmap bm = BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length);
imageView.setImageBitmap(bm);

// where imgBytes is you bytes from Database

Upvotes: 0

Related Questions