retrieved data from sqlite database and displaying it on grouped table view - iphone

hii every one
i am brand new to obj c, i have did a sample project where i have 2 screens on the first screen i have six text fields & 2 buttons named save and ViewData ,on click of save data which is entere d in the text field will be get saved in the sqliteData Base ,& on click of the button ViewData it will navigate to a new screen which has a grouped table view, here i am trying to display the data which is stored in the sqlite ,in the grouped table view i have 6 sections i am using following code to display the data in grouped table view,problem is grouped table view is displaing only the last data which is entered ih the text field,,but i need to display all the data which enterd should be shown under that section
appDelegate = (iICS_testAppDelegate *)[[UIApplication sharedApplication] delegate];
for(int intVar=0;intVar < [appDelegate.arrObjects count];intVar++)
{
insertUpdateDelete *InsertRecord = [appDelegate.arrObjects objectAtIndex:intVar];
NSLog(#"InsertRecord:%#",InsertRecord);
NSMutableArray *arrTemp1 = [[NSMutableArray alloc]initWithObjects:InsertRecord.strsixth,nil];
NSMutableArray *arrTemp2 = [[NSMutableArray alloc]initWithObjects:InsertRecord.strfifth,nil];
NSMutableArray *arrTemp3 = [[NSMutableArray alloc]initWithObjects:InsertRecord.strFourth,nil];
NSMutableArray *arrTemp4 = [[NSMutableArray alloc]initWithObjects:InsertRecord.strLogin,nil];
NSMutableArray *arrTemp5 = [[NSMutableArray alloc]initWithObjects:InsertRecord.strMiddleName,nil];
NSMutableArray *arrTemp6 = [[NSMutableArray alloc]initWithObjects:InsertRecord.strFirstName,nil];
NSMutableDictionary *temp =[[NSMutableDictionary alloc]initWithObjectsAndKeys:arrTemp1,#"Item Name",arrTemp2,#"Manufacturer",arrTemp3,#"Weight of Item",arrTemp4,#"Num of Item",arrTemp5,#"Price of Item",arrTemp6,#"MFG Date",nil];
self.tableContents =temp;
[temp release];
NSLog(#"table %#",self.tableContents);
NSLog(#"table with Keys %#",[self.tableContents allKeys]);
self.sortedKeys =[[self.tableContents allKeys] sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"sorted %#",self.sortedKeys);
[arrTemp1 release];
[arrTemp2 release];
[arrTemp3 release];
[arrTemp4 release];
[arrTemp5 release];
[arrTemp6 release];
}
here im assigning the text for the row
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//insertUpdateDelete *InsertRecord = [appDelegate.arrObjects objectAtIndex:indexPath.row];
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
NSArray *listData =[self.tableContents objectForKey:[self.sortedKeys objectAtIndex:[indexPath section]]];
UITableViewCell * cell = [tableView
dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:SimpleTableIdentifier] autorelease];
}
NSUInteger row = [indexPath row];
//cell.textLabel.text = [appDelegate.arrObjects objectAtIndex:row];
cell.textLabel.text = [listData objectAtIndex:row];
return cell;
}
thanks in advance!
This is my snapshopt of grouped table view. I need the data which is entered through the text field shoul be viewed under particular section

Solution for only the last data is displaying,
Instead of NSArray use NSMutableArray.
Solution for wrong field values,
Your problem may be in insertion itself,
NSArray *arrTemp1 = [[NSArray alloc]initWithObjects:InsertRecord.strsixth,nil];
NSArray *arrTemp2 = [[NSArray alloc]initWithObjects:InsertRecord.strfifth,nil];
You are inserting price value into date field, i think so. Please check that.
Change your code as,
NSMutableArray *arrTemp1 = [[NSMutableArray alloc]init];
NSMutableArray *arrTemp2 = [[NSMutableArray alloc]init];
NSMutableArray *arrTemp3 = [[NSMutableArray alloc]init];
NSMutableArray *arrTemp4 = [[NSMutableArray alloc]init];
NSMutableArray *arrTemp5 = [[NSMutableArray alloc]init];
NSMutableArray *arrTemp6 = [[NSMutableArray alloc]init];
for(int intVar=0;intVar < [appDelegate.arrObjects count];intVar++)
{
insertUpdateDelete *InsertRecord = [appDelegate.arrObjects objectAtIndex:intVar];
NSLog(#"InsertRecord:%#",InsertRecord);
[arrTemp1 addObject:InsertRecord.strsixth];
[arrTemp2 addObject:InsertRecord.strfifth];
[arrTemp3 addObject:InsertRecord.strFourth];
[arrTemp4 addObject:InsertRecord.strLogin];
[arrTemp5 addObject:InsertRecord.strMiddleName];
[arrTemp6 addObject:InsertRecord.strMiddleName];
}
NSDictionary *temp =[[NSDictionary alloc]initWithObjectsAndKeys:arrTemp1,#"Item Name",arrTemp2,#"Manufacturer",arrTemp3,#"Weight of Item",arrTemp4,#"Num of Item",arrTemp5,#"Price of Item",arrTemp6,#"MFG Date",nil];
self.tableContents =temp;
[temp release];
NSLog(#"table %#",self.tableContents);
NSLog(#"table with Keys %#",[self.tableContents allKeys]);
self.sortedKeys =[[self.tableContents allKeys] sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"sorted %#",self.sortedKeys);
[arrTemp1 release];
[arrTemp2 release];
[arrTemp3 release];
[arrTemp4 release];
[arrTemp5 release];
[arrTemp6 release];

Related

Why am I seeing a crash when displaying this table view?

I am designing a simple navigation based application for EmployeeContactDirectory. I am displaying the list of Employee. For showing the list of employee, I am using the restfull webservice. I am getting proper response as I want. I have a utility class for Employee Data, class is EmployeeData.h and Employee.m (contains employeeId , employeeFirstName, employeeLastName). My code for parsing
// Code for parsing the response and getting desired field into the dictionary object and add the dictionaries into the array.
-(void)finishedReceivingData:(NSData *)data {
NSData *dataRes = [[restConnection stringData] dataUsingEncoding:NSUTF8StringEncoding];
////////////////Parsing with XPathQuery Start//////////////////////
if (dataRes != NULL) {
employeeData = [[EmployeeData alloc] init];
NSString *xPathQuery = [NSString stringWithFormat:#"/*",employeeData.employeeID];
NSArray *arrayWithObjectList = PerformXMLXPathQuery(dataRes, xPathQuery);
for(NSDictionary *childOfObjectList in arrayWithObjectList){
NSArray *arrayOfDataValueObj = (NSArray *)[childOfObjectList objectForKey:#"nodeChildArray"];
for(NSDictionary *childObjListDict in arrayOfDataValueObj){
NSArray *childObjListDataValue = (NSArray *)[childObjListDict objectForKey:#"nodeChildArray"];
for(NSDictionary *childDict in childObjListDataValue){
if([[childDict objectForKey:#"nodeName"] isEqualToString:#"FName" ])
{
employeeData.employeeFirstName = [childDict objectForKey:#"nodeContent"];
}
if([[childDict objectForKey:#"nodeName"] isEqualToString:#"EmpID"])
{
employeeData.employeeID = [childDict objectForKey:#"nodeContent"];
}
}
//employeeFirstNameArray = [NSArray arrayWithObjects:employeeData, nil];
employeeIDArray = [NSArray arrayWithObjects:employeeData, nil];
dictionaryEmployeeFirstName = [NSDictionary dictionaryWithObject:employeeData.employeeFirstName forKey:#"employeeData"];
dictionaryEmployeeID = [NSDictionary dictionaryWithObject:employeeData.employeeID forKey:#"employeeData"];
tempArray = [NSArray arrayWithObjects:dictionaryEmployeeFirstName, dictionaryEmployeeID, nil];
NSLog(#"size of temp %d",[tempArray count]);
}
}
//[employeeData release];
//employeeData = nil;
}
[self.tableviewEmloyeeList reloadData];
//////////////////////////////Parsing with XPathQuery end//////////
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell..
NSDictionary *dictionaryEmployee = [tempArray objectAtIndex:indexPath.row];
NSArray *firstNameArray = [dictionaryEmployee objectForKey:#"employeeData"];
NSString *cellValue = [firstNameArray objectAtIndex:indexPath.row];
NSLog(#"cellValue %#",cellValue);
cell.textLabel.text = cellValue;
return cell;
}
I am getting the message (Exc_bad_Access) when this line of code comes into the execution flow:
NSDictionary *dictionaryEmployee = [tempArray objectAtIndex:indexPath.row]
The EXC_Bad_Access is at the mail.m file at line nt retVal = UIApplicationMain(argc, argv, nil, nil);
So, Please tell me how can I set the data into the tableview when I am using NSDictionary. When, user clicks on the row of the tableview it will return the id of the selected employee.
Instead of the line
tempArray = [NSArray arrayWithObjects:dictionaryEmployeeFirstName, dictionaryEmployeeID, nil];
try the following,
if( tempArray )
{
[tempArray release];
tempArray = nil;
}
tempArray = [[NSArray arrayWithObjects:dictionaryEmployeeFirstName, dictionaryEmployeeID, nil] retain];
Since it is autoreleased, it might have been out of memory.
you need to implement a tableView delegate method called
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
here you will get the section & row clicked in the table

Array in UITextView

I have an arrayappdeligate.biblearray. I just want to display this array in a textview. This array contains sql datas of 4 types chapterno, verses, genisis and text. i need to extract only the verses and display it in textview how to do this?
It seems biblearray has the objects of type bible. You can get the verses from bible objects like this,
bible *_bible = (bible *)[appDelegate.bibleArray objectAtIndex:0];
textView.text = [_bible verses];
or directly as,
textView.text = [[appDelegate.bibleArray objectAtIndex:0] verses];
If you want to display all the verses in the textView, you can do it like this,
NSArray *allVerses = [appDelegate.bibleArray valueForKey:#"verses"];
textView.text = [allVerses componentsJoinedByString:#"\n\n"];
#"\n\n" adds two new lines between the verses.
You need to do some alteration. Create NSDisctionary instead.
Take a dictionary where you are adding data from database
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
NSMutableArray *chapterno = [[NSMutableArray alloc]init];
NSMutableArray *verses = [[NSMutableArray alloc]init];
NSMutableArray *genisis = [[NSMutableArray alloc]init];
NSMutableArray *text = [[NSMutableArray alloc]init];
//Add data you are getting from database
[chapterno addObject:chapternodata];
[verses addObject:versesdata];
[genisis addObject:genisisdata];
[text addObject:textdata];
[dict setValue:chapterno forKey:#"chapterno"];
[dict setValue:verses forKey:#"verses"];
[dict setValue:genisis forKey:#"genisis"];
[dict setValue:text forKey:#"text"];
[chapterno release];
[verses release];
[genisis release];
[text release];
Take one NSDictionary in AppDelegate say appDict and make it equal to dict
NSMutableArray *arrVerses = [[objAppDel.appDict objectForKey:#"verses"];
txt.text = [arrVerses description];

NSMutableArray, pList, Tableview muddle and meltdown

I have a preferences view which shows a different table view depending on which Segmented Control is clicked.
I hard coded some NSMutableArrays to test basic principles:
prefsIssuesList = [[NSMutableArray alloc] init];
[prefsIssuesList addObject:#"Governance"];
[prefsIssuesList addObject:#"Innovation and technology"];
...etc
prefsIndustriesList = [[NSMutableArray alloc] init];
[prefsIndustriesList addObject:#"Aerospace and defence"];
... etc
prefsServicesList = [[NSMutableArray alloc] init];
[prefsServicesList addObject:#"Audit and assurance"];
...etc
currentArray = [[NSMutableArray alloc] init];
currentArray = self.prefsIssuesList;
Then reload the tableview with currentArray, adding a UITableViewCellAccessoryCheckmark.
Everything works fine.
But now I want to store wether the checkmark is on or off in a pList file, and read this back in.
Ideally want to a plist like this
Root Dictionary
Issues Dictionary
Governance Number 1
Innovation and technology Number 0
etc
I've got as far as working this out
// Designate plist file
NSString *path = [[NSBundle mainBundle] pathForResource: #"issues" ofType:#"plist"];
// Load the file into a Dictionary
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
self.allNames= dict;
[dict release];
NSLog(#"Dict is %#", allNames); // All the data in the pList file
NSMutableArray *issueSection = [allNames objectForKey:#"Issues"];
NSLog(#"Issues is %#", issueSection); // The data is the Issues Section
NSString *issueVal = [issueSection objectForKey:#"Governance"];
NSLog(#"Governance is %#", issueVal); //The value of the Governance key
But what I really want to do is loop through the Issues Dictionary and get the key/value pairs so
key = cell.textLabel.text
value = UITableViewCellAccessoryCheckmark / UITableViewCellAccessoryNone
depending wether it's 1 or 0
I'm assuming that I can still assign one of the three NSMutableArrays to currentArray as I did in the hardcoded version, and use currentArray to reload the tableview.
Then amend this code to build the tableview
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [names objectForKey:key];
static NSString *CellIdentifier = #"Cell";
//UITableViewCell *cell = [self.prefsTableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];
UITableViewCell *cell = [self.prefsTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell=[[[UITableViewCell alloc]
initWithFrame:CGRectZero
reuseIdentifier: CellIdentifier] autorelease];
}
cell.textLabel.text = [nameSection objectAtIndex:row];
return cell;
But my brain has melted, I've spent about six hours today reading up on pLists, NSArrays, NSMutableDisctionaries, standardUserDefaults to little avail.
I've managed to UITableViews inside UINavigationViews, use SegmentedControls, download asynchronous XML, but now I'm finally stuck, or fried, or both. Over what should be fairly simple key/value pairs.
Anyone care to give me some idiot pointers?
Typing it out led to another post with that one little word I needed to get me back on track :)
Use key/value pairs in a pList to stipulate the name of the cell and wether it was selected or not by the user.
plist is based on a structure like this
Root Dictionary
Services Dictionary
Peaches String 1
Pumpkin String 0
Here's how I grabbed three Dictionary arrays from a pList and used the key/value pairs to reload a tableview depending on which segmentControl was touched:
- (void)viewDidLoad {
[super viewDidLoad];
// Designate plist file
NSString *path = [[NSBundle mainBundle] pathForResource: #"issues" ofType:#"plist"];
// Load the file into a Dictionary
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
self.allNames= dict;
[dict release];
// Create the Named Dictionaries from Dictionary in pLIst
NSMutableDictionary *allIssues = [self.allNames objectForKey:#"Issues"];
self.prefsIssuesList = allIssues;
[allIssues release];
NSMutableDictionary *allIndustries = [self.allNames objectForKey:#"Industries"];
self.prefsIndustriesList = allIndustries;
[allIndustries release];
NSMutableDictionary *allServices = [self.allNames objectForKey:#"Services"];
self.prefsServicesList = allServices;
[allServices release];
// Assign the current Dictionary to out placeholder Dictionary
currentDict = [[NSMutableDictionary alloc] init];
currentDict = self.prefsIssuesList;
}
Then styling the table cells
- (UITableViewCell *)tableView:(UITableView *)prefsTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
NSArray *keysArray = [self.currentDict allKeys];
NSString *theKey = [keysArray objectAtIndex:row];
NSString *theValue = [self.currentDict objectForKey: [keysArray objectAtIndex:row]];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.prefsTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell=[[[UITableViewCell alloc]
initWithFrame:CGRectZero
reuseIdentifier: CellIdentifier] autorelease];
}
cell.textLabel.text = theKey;
if (theValue == #"0") {
cell.accessoryType = UITableViewCellAccessoryNone;
}else {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
return cell;
}
The if clause at the end doesn't seem to be working, I'll post that as a new question (unless anyone comments quickly!)
Finally the segmentControls assign the different dictionaries to the placeholder array and reload the tableview
This took me a very long day to figure out (as a noobie) so I hope it helps someone
-(IBAction) segmentedControlIndexChanged{
switch (self.segmentedControl.selectedSegmentIndex) {
case 0:
//currentArray = self.prefsIssuesList;
currentDict = self.prefsIssuesList;
break;
case 1:
//currentArray = self.prefsIndustriesList;
currentDict = self.prefsIndustriesList;
break;
case 2:
//currentArray = self.prefsServicesList;
currentDict = self.prefsServicesList;
break;
default:
//currentArray = self.prefsIssuesList;
currentDict = self.prefsIssuesList;
break;
}
[prefsTableView reloadData];
}
Shout if there's a neater or better way of d

Dealing with editable items in a filtered UITable with an NSMutableArray copy

I have a UITable with a datasource that is set to a 'copy' of the original data. I use this copy to displayed filtered results (either 'All' or only those that are 'checked' with a UISwitch in each row). My logic for doing the filtering is here:
-(void)filterItems {
[tableData removeAllObjects];
if (checkedOrNotSwitch.selectedSegmentIndex == 0) {
[tableData addObjectsFromArray:self.defaultChecklistItemsArray];
} else {
for (NSMutableDictionary *sectionDict in self.defaultChecklistItemsArray) {
NSMutableArray *newItemsArray = [[NSMutableArray alloc] init];
[newItemsArray removeAllObjects];
for (NSMutableDictionary *itemDict in [sectionDict objectForKey:#"categoryItems"]) {
if ([[itemDict objectForKey:#"isComplete"] boolValue]) {
[newItemsArray addObject:itemDict];
}
}
if ([newItemsArray count] > 0) {
NSMutableDictionary *newSectionDict = [[NSMutableDictionary alloc] initWithDictionary:sectionDict];
[newSectionDict setObject:newItemsArray forKey:#"categoryItems"];
[tableData addObject:newSectionDict];
[newSectionDict release];
}
}
}
[checklistTable reloadData];
}
The filtering itself now works correctly. In my custom cell, each row has a UISwitch. The switch runs this function when its changed:
-(IBAction) switchValueChanged{
NSIndexPath *indexPath = [(UITableView *)self.superview indexPathForCell: self];
[self.parentController updateCompletedStatusAtIndexPath:indexPath toStatus:isCompleted.on];
}
The function above is in the class for the tableviewcell itself. The function I call in the superview is this:
-(void)updateCompletedStatusAtIndexPath:(NSIndexPath *)indexPath toStatus:(BOOL)status{
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSMutableDictionary *currentsection = [[NSMutableDictionary alloc] initWithDictionary:[tableData objectAtIndex:section]];
NSMutableArray *itemsArray = [[NSMutableArray alloc] initWithArray:[currentsection objectForKey:#"categoryItems"] copyItems:YES];
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] initWithDictionary:[itemsArray objectAtIndex:row]];
NSLog(#"BOOL = %#\n", (status ? #"YES" : #"NO"));
[tempDict setValue:[NSNumber numberWithBool:status] forKey:#"isComplete"];
[itemsArray replaceObjectAtIndex:row withObject:tempDict];
[currentsection setValue:itemsArray forKey:#"categoryItems"];
[tableData replaceObjectAtIndex:section withObject:currentsection];
[tempDict release];
[itemsArray release];
[currentsection release];
[checklistTable reloadData];
}
Before I implemented the filtering and used the logic above on self.defaultChecklistItemsArray directly, it worked and saved the data when the switch was flipped.
Now when I first enter the app, it loads the array of data from nsuserdefaults. I navigate to the view with the table and it displays the data correctly there with the UISwitches all in the correct position given the data (some on, some off). When I tap one of the switches, then click the segmentedcontrol that does the filtering, the data reverts back to the state it was loaded in, implying that the flipping of the switch did not actually effect the data at all (even though I don't think I did a deep copy anywhere here so I figured it should be doing the right thing). Any suggestions?

iphone detailtext in UITableView question

So, I am able to create an array that populates the fields of the Table, but am having troubles creating the subtext that appears below the main fields. I currently have:
- (void)viewDidLoad {
[super viewDidLoad];
listOfForms = [[NSMutableArray alloc] init];
[listOfForms addObject:#"First Form"];
}
and then:
NSString *cellValue = [listOfDAForms objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
in the cellForRowAtIndexPath portion. Why can't I add:
listOfNames = [[NSMutableArray alloc] init];
[listOfNames addObject:#"Named Form"];
and
NSString *cellSubscript = [listOfNames objectAtIndex:indexPath.row];
cell.detailTextLabel.text = cellSubscript;
in order to make the little subview work? What am I doing wrong?
Be sure to init your cell with the style UITableViewCellStyleSubtitle