iphone - Image is not fetching from database -
i stored images in server. used json fetch remote data server. when storing images in local database working. when use json url it's not working. im getting exc_bad_access error.
code:
mysof.h file:
@interface mysof : nsobject{ nsinteger sofaid; nsstring *sofa; nsstring *rating; uiimage *photo; } @property (nonatomic,retain)nsstring *sofa; @property (nonatomic, assign) nsinteger sofaid; @property (nonatomic, retain)nsstring *rating; @property (nonatomic, retain) uiimage *photo; @end
mysof.m file:
@implementation mysof @synthesize sofid; @synthesize sofa; @synthesize rating; @synthesize photo; @end
sofalistsql.h file:
@interface sofalistsql : nsobject { sqlite3 *db; } - (nsmutablearray *) getmysofas; @end
.m file:
@implementation sofalistsql - (nsmutablearray *) getmysofas{ nsmutablearray *sofarray = [[nsmutablearray alloc] init]; nsfilemanager *filemgr = [nsfilemanager defaultmanager]; nserror *err; nsstring *bundlepath = [[nsbundle mainbundle] pathforresource:@"empty" oftype:@"sqlite"]; //nslog(@"bundlepath %@", bundlepath); //call update function check data updated, //if there version difference //update data base required fileds. nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory,nsuserdomainmask, yes); nsstring *documentsdirectory = [paths objectatindex:0]; //nslog(@"docs dir %@", documentsdirectory); nsstring *appfile = [documentsdirectory stringbyappendingpathcomponent:@"app6.sqlite"]; [filemgr copyitematpath:bundlepath topath:appfile error:&err]; nsurl *url = [nsurl urlwithstring:@"http://server.net/projects/mobile/jsonstring.php"]; nslog(@"url %@", url); nserror *error; nsstring *stringfromfileaturl = [[nsstring alloc] initwithcontentsofurl:url encoding:nsutf8stringencoding error:&error]; //nslog(@"response %@", stringfromfileaturl); nsstring *path = [documentsdirectory stringbyappendingpathcomponent:@"app6.sqlite"]; nsarray *userdata = [stringfromfileaturl jsonvalue]; // nsarray *skarray = [[nsarray alloc]init]; nslog(@"userdata %@", userdata); // int = 0; bool notexist = true; (nsarray *skarray in userdata) { (nsdictionary *tuser in skarray) { //if exists in data base id overwrite name if (sqlite3_open([path utf8string], &db) == sqlite_ok) { const char *sql = [[nsstring stringwithformat:@"select id categories id = '%@'",[tuser objectforkey:@"id"]] cstringusingencoding:nsutf8stringencoding]; //nslog(@"check stmt %s", sql); sqlite3_stmt *sqlstatement,*addstmt; if (sqlite3_prepare_v2(db, sql, -1, &sqlstatement, null) == sqlite_ok) { notexist = true; while (sqlite3_step(sqlstatement) == sqlite_row) { notexist = false; mysof *mylist = [[mysof alloc]init]; mylist.sofaid = sqlite3_column_int(sqlstatement, 0); mylist.sofa = [nsstring stringwithutf8string:(char *) sqlite3_column_text(sqlstatement,1)]; mylist.rating = [nsstring stringwithutf8string:(char *) sqlite3_column_text(sqlstatement, 2)]; const char *raw = sqlite3_column_blob(sqlstatement, 3); int rawlen = sqlite3_column_bytes(sqlstatement, 3); nsdata *data = [nsdata datawithbytes:raw length:rawlen]; mylist.photo = [[uiimage alloc] initwithdata:data]; [sofarray addobject:mylist]; } if(notexist){ //nslog(@"cat id not exist"); const char *sqlinsert = [[nsstring stringwithformat:@"insert categories (id, cat_name,order_by) values ('%@', '%@', '%@')", [tuser objectforkey:@"id"], [tuser objectforkey:@"cat_name"],[tuser objectforkey:@"order_by"]] cstringusingencoding:nsutf8stringencoding]; //nslog(@"stmt %s", sqlinsert); if(sqlite3_prepare_v2(db, sqlinsert, -1, &addstmt, null) != sqlite_ok) nsassert1(0, @"error while creating add statement. '%s'", sqlite3_errmsg(db)); if(sqlite_done != sqlite3_step(addstmt)) nsassert1(0, @"error while inserting data. '%s'", sqlite3_errmsg(db)); } } } } } return sofarray; } @end
in viewcontroller.m file:
- (void)viewdidload { [super viewdidload]; // additional setup after loading view. sofalistsql * mysofs =[[sofalistsql alloc] init]; self.sofas = [mysofs getmysofas]; }
button click display images server:
-(void)click:(id)sender{ scrollview=[[uiscrollview alloc]initwithframe:cgrectmake(0,500,320,200)]; scrollview.showsverticalscrollindicator=no; scrollview.showshorizontalscrollindicator=no; scrollview.scrollenabled=yes; int width = 0; // width = width + 20+(i*74); (int = 0; i<[self.sofas count]; i++ ) { nslog(@"index %d",i); // imgview1=[[uibutton alloc]initwithframe:cgrectmake(20+(i*74), 500, 72, 72)]; imgview1=[[uibutton alloc]initwithframe:cgrectmake(20+(i*74), 0, 72, 72)]; width = width + 20+(i*74); [imgview1 settag:i+1]; [imgview1 addtarget:self action:@selector(dbsofaclicked:) forcontrolevents:uicontroleventtouchupinside]; [imgview1 setimage:((mysof *)[self.sofas objectatindex:i]).photo forstate:uicontrolstatenormal]; [scrollview addsubview:imgview1]; // [myscroll addsubview:imgview1]; } [scrollview setcontentsize:cgsizemake(width,imgview1.frame.size.height+20)]; [self.view addsubview:scrollview]; }
jsonstring.php file:
<?php require_once('database_connection.php'); $i = 0; $j = 0; $k = 0; $l = 0; mysql_query('set character set utf8') or die("mysql character set error: ".mysql_error()); $result = array(); $sql=mysql_query("select * categories order id asc") or die(mysql_error()); if(mysql_num_rows($sql) > 0) { while($res=mysql_fetch_array($sql, mysql_assoc)){ $result[0][$i] = $res; $art_sql=mysql_query("select * product cat_id=" .$res['id']. " order id asc") or die(mysql_error()); if (mysql_num_rows($art_sql) > 0){ while($art_res=mysql_fetch_array($art_sql, mysql_assoc)){ //$art_res['art_details'] = (utf8_encode(htmlentities($art_res['art_details']))); //$art_res['art_details'] = htmlentities($art_res['art_details']); //echo $art_res['art_details']; $result[1][$k] = $art_res; //print_r($art_res); $k = $k+1; } } $i= $i+1; } $version_sql = mysql_query("select * version_app order product_id desc limit 1") or die(mysql_error()); $row = mysql_fetch_array($version_sql); $last_version = $row['product_id']; $result['2'][$l] = array('product_id' => $last_version); $l = $l+1; } /*echo "<pre>"; print_r($result); echo "</pre>";exit;*/ $str_enc = json_encode($result); //print_r($str_enc); exit; $str=str_replace('\r','',$str_enc); $str=str_replace('\t','',$str); $str=str_replace('\n','',$str); $str = stripslashes($str); //$str_renc = json_encode(json_decode($str)); echo $str; mysql_close(); ?>
nslog:
userdata ( ( { "cat_name" = table1; id = 1; "order_by" = 1; }, { "cat_name" = table2; id = 2; "order_by" = 2; }, { "cat_name" = test; id = 3; "order_by" = 3; } ), ( { "cat_id" = 1; id = 2; "order_by" = 1; "product_image" = "img.png"; }, { "cat_id" = 1; id = 3; "order_by" = 2; "product_image" = "img1.png"; }, { "cat_id" = 1; id = 4; "order_by" = 3; "product_image" = "img2.png"; }, { "cat_id" = 1; id = 5; "order_by" = 4; "product_image" = "img3.png"; }, { "cat_id" = 1; id = 6; "order_by" = 5; "product_image" = "img4.png"; }, { "cat_id" = 1; id = 7; "order_by" = 6; "product_image" = "img5.png"; }, ) ) array ( ) 2013-08-16 13:19:53.044 app[3395:c07] scroll <uiscrollview: 0x9de7cb0; frame = (0 300; 320 200); clipstobounds = yes; gesturerecognizers = <nsarray: 0x9de60e0>; layer = <calayer: 0x9de4bc0>; contentoffset: {0, 0}>
i stored same table name in local database. , used overwrite database. in local database stored images in blob
type. in array got nothing displaying. app working. images not displaying database.
now you've included json sample, can see problem: json array of 3 arrays, array of categories, array of products, , array of versions. questionable structure (usually array of homogeneous items of same type). rather array of arrays, i'd make dictionary of arrays.
this confusing structure in json manifests in objective-c code. you're trying iterate through userdata
array, can't, because each of 3 item different.
so let me suggest 2 possible fixes. first if stick array of arrays (which i'm not crazy about), cannot iterate through array for
loop, extract 3 arrays contains so:
nsarray *categories = userdata[0]; nsarray *products = userdata[1]; nsarray *versions = userdata[2];
now can iterate through each of 3 arrays.
personally, i'd take step further , change php generates json generate top level dictionary, e.g.
<?php require_once('database_connection.php'); $i = 0; $j = 0; $k = 0; $l = 0; mysql_query('set character set utf8') or die("mysql character set error: ".mysql_error()); $result = array(); $sql=mysql_query("select * categories order id asc") or die(mysql_error()); if(mysql_num_rows($sql) > 0) { while($res=mysql_fetch_array($sql, mysql_assoc)){ $result['categories'][$i] = $res; $art_sql=mysql_query("select * product cat_id=" .$res['id']. " order id asc") or die(mysql_error()); if (mysql_num_rows($art_sql) > 0){ while($art_res=mysql_fetch_array($art_sql, mysql_assoc)){ $result['products'][$k] = $art_res; $k = $k+1; } } $i= $i+1; } $version_sql = mysql_query("select * version_app order product_id desc limit 1") or die(mysql_error()); $row = mysql_fetch_array($version_sql); $last_version = $row['product_id']; $result['versions'][$l] = array('product_id' => $last_version); $l = $l+1; } $str_enc = json_encode($result); // note, these str_replace lines not needed // $str=str_replace('\r','',$str_enc); // $str=str_replace('\t','',$str); // $str=str_replace('\n','',$str); // stripslashes bad idea, though // $str = stripslashes($str); // echoed `$str`, i'll echo @str_enc echo $str_enc; mysql_close(); ?>
and if did that, retrieve 3 arrays with
nsarray *categories = userdata[@"categories"]; nsarray *products = userdata[@"products"]; nsarray *versions = userdata[@"versions"];
it's not mission critical change, it's more logical representation 3 heterogeneous items. idea same: extract 3 arrays json, , can iterate through them, respectively.
a couple of sqlite-related issues leap out @ me
one issue have line of sql says:
select id categories cat_id = '%@'
but proceed try read 4 columns worth of data (even though returned one). , if changed sql return 4 columns of data, should check
sqlite3_column_blob
,sqlite3_column_bytes
calls make sure there populatensdata
.as aside, it's safer not use
stringwithformat
when building sql statement, rather use?
placeholders instead of printf-formatters , usesqlite3_bind_xxx
functions.you
getmysofas
repeatedly opening database, never closing it. have 1sqlite3_close
everysqlite3_open
call. likewise, should have 1sqlite3_finalize
statement eachsqlite3_prepare_v2
line.
beyond have identify source of crash either using exception breakpoint, single-stepping through code in debugger, or putting bunch of nslog
statements in there. see ray wenderlich's series my app crashed, what?. need identify line of code causing problem.
Comments
Post a Comment