android - Retrieving image from sqlite -


i have created databse contains surveyname , image. image inserted databse bytearray(blob) correctly when m trying retrieve images gives random value. when use if condition finding image returns random value , when use while has resulted infinite loop 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 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.. 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();                 (file file : files)                 {                     if (!file.delete())                     {                         system.out.println("failed 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 want delete file                     //boolean deleted = mypath.delete();                     //log.v("log_tag","deleted: " + mypath.tostring() + deleted);                     //if want convert image 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();                     (int = 0; < 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 database---           public databasemethods open() throws sqlexception            {                  db = dbhelper.getwritabledatabase();               return this;           }            //---closes database---               public void close()            {               dbhelper.close();           }            public void getallrecords()         {             string survey="mobile";             string query="select image image 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 image (surveyname,image)          value('"+survey+"','"+imgdata+"')";         toast.maketext(context,"imageinserted",toast.length_long).show();         db.execsql(query);       }         } 

i have found altaernate solution problem have decoded image using base64 , saved varchar , encoded again. working perfetctly me... 1. 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 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);


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -