CS185c
Chris Pollett
Oct. 6, 2010
#import <UIKit/UIKit.h> #import "Person.h" @interface PersonTableController : UITableViewController { NSManagedObjectContext *managedObjectContext; NSMutableArray *personArray; } @property (nonatomic, retain) NSManagedObjectContext *managedObjectContext; @property (nonatomic, retain) NSMutableArray *personArray; - (void) fetchRecords; - (void) addPerson:(id)sender; @end
#import "PersonTableController.h" @implementation PersonTableController @synthesize managedObjectContext, personArray; #pragma mark - #pragma mark View lifecycle - (void)viewDidLoad { [super viewDidLoad]; self.title = @"People"; UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addPerson:)]; self.navigationItem.rightBarButtonItem = addButton; [addButton release]; [self fetchRecords]; } - (void)addPerson:(id)sender { Person *person = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:managedObjectContext]; [person setID: @"123456789"]; [person setEmail: @"youhoo@wink.com"]; Person *person2 = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:managedObjectContext]; [person2 setID: @"012345678"]; [person2 setEmail: @"iseeu@wink.com"]; NSError *error; if(![managedObjectContext save:&error]){ //This is a serious error saying the record //could not be saved. Advise the user to //try again or restart the application. } [personArray insertObject:person atIndex:0]; [personArray insertObject:person2 atIndex:1]; [self.tableView reloadData]; } - (void)fetchRecords { // Define our table/entity to use NSEntityDescription *entity = [NSEntityDescription entityForName:@"Person" inManagedObjectContext:managedObjectContext]; // Setup the fetch request NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:entity]; // Define how we will sort the records NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"ID" ascending:NO]; NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; [request setSortDescriptors:sortDescriptors]; [sortDescriptor release]; // Fetch the records and handle an error NSError *error; NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; if (!mutableFetchResults) { // Handle the error. // This is a serious error and should advise the user to restart the application } // Save our fetched data to an array [self setPersonArray: mutableFetchResults]; [mutableFetchResults release]; [request release]; } #pragma mark - #pragma mark Table view data source -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [personArray count]; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease]; } Person *person = [personArray objectAtIndex: [indexPath row]]; Person *previousPerson = nil; if ([personArray count] > ([indexPath row] + 1)) { previousPerson = [personArray objectAtIndex: ([indexPath row] + 1)]; } [cell.textLabel setText: [person ID]]; if (previousPerson) { [cell.detailTextLabel setText: [NSString stringWithFormat:@"2nd %@", [person email]]]; } else { [cell.detailTextLabel setText: [person email]]; } return cell; } #pragma mark - #pragma mark Table view delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic may go here. Create and push another view controller. /* <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil]; // ... // Pass the selected object to the new view controller. [self.navigationController pushViewController:detailViewController animated:YES]; [detailViewController release]; */ } #pragma mark - #pragma mark Memory management - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Relinquish ownership any cached data, images, etc that aren't in use. } - (void)viewDidUnload { // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. // For example: self.myOutlet = nil; } - (void)dealloc { [managedObjectContext release]; [personArray release]; [super dealloc]; } @end
#import#import @interface CoreDataDemoAppDelegate : NSObject { UIWindow *window; NSManagedObjectModel *managedObjectModel; NSManagedObjectContext *managedObjectContext; NSPersistentStoreCoordinator *persistentStoreCoordinator; UINavigationController *navigationController; } @property (nonatomic, retain) IBOutlet UIWindow *window; @property (nonatomic, retain, readonly) NSManagedObjectModel *managedObjectModel; @property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext; @property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator; @property (nonatomic, retain) UINavigationController *navigationController; - (NSString *)applicationDocumentsDirectory; - (void)saveContext; @end
// // CoreDataDemoAppDelegate.m // CoreDataDemo // // Created by Chris Pollett on 10/6/10. // Copyright 2010 San Jose State University. All rights reserved. // #import "CoreDataDemoAppDelegate.h" #import "PersonTableController.h" @implementation CoreDataDemoAppDelegate @synthesize window; @synthesize navigationController; #pragma mark - #pragma mark Application lifecycle -(void)applicationDidFinishLaunching:(UIApplication *)application { PersonTableController *tableController = [[PersonTableController alloc] initWithStyle:UITableViewStylePlain]; tableController.managedObjectContext = [self managedObjectContext]; self.navigationController = [[UINavigationController alloc] initWithRootViewController:tableController]; [tableController release]; [window addSubview: [self.navigationController view]]; [window makeKeyAndVisible]; } - (void)applicationWillResignActive:(UIApplication *)application { /* Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. */ } - (void)applicationDidEnterBackground:(UIApplication *)application { /* Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. If your application supports background execution, called instead of applicationWillTerminate: when the user quits. */ [self saveContext]; } - (void)applicationWillEnterForeground:(UIApplication *)application { /* Called as part of the transition from the background to the inactive state: here you can undo many of the changes made on entering the background. */ } - (void)applicationDidBecomeActive:(UIApplication *)application { /* Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. */ } /** applicationWillTerminate: saves changes in the application's managed object context before the application terminates. */ - (void)applicationWillTerminate:(UIApplication *)application { [self saveContext]; } - (void)saveContext { NSError *error = nil; if (managedObjectContext != nil) { if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. */ NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } } } #pragma mark - #pragma mark Core Data stack /** Returns the managed object context for the application. If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application. */ - (NSManagedObjectContext *)managedObjectContext { if (managedObjectContext != nil) { return managedObjectContext; } NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; if (coordinator != nil) { managedObjectContext = [[NSManagedObjectContext alloc] init]; [managedObjectContext setPersistentStoreCoordinator:coordinator]; } return managedObjectContext; } /** Returns the managed object model for the application. If the model doesn't already exist, it is created from the application's model. */ - (NSManagedObjectModel *)managedObjectModel { if (managedObjectModel != nil) { return managedObjectModel; } NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"CoreDataDemo" ofType:@"momd"]; NSURL *modelURL = [NSURL fileURLWithPath:modelPath]; managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; return managedObjectModel; } /** Returns the persistent store coordinator for the application. If the coordinator doesn't already exist, it is created and the application's store added to it. */ - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { if (persistentStoreCoordinator != nil) { return persistentStoreCoordinator; } NSURL *storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"CoreDataDemo.sqlite"]]; NSError *error = nil; persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. Typical reasons for an error here include: * The persistent store is not accessible; * The schema for the persistent store is incompatible with current managed object model. Check the error message to determine what the actual problem was. If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory. If you encounter schema incompatibility errors during development, you can reduce their frequency by: * Simply deleting the existing store: [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil] * Performing automatic lightweight migration by passing the following dictionary as the options parameter: [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. */ NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } return persistentStoreCoordinator; } #pragma mark - #pragma mark Application's Documents directory /** Returns the path to the application's Documents directory. */ - (NSString *)applicationDocumentsDirectory { return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; } #pragma mark - #pragma mark Memory management - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { /* Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later. */ } - (void)dealloc { [managedObjectContext release]; [managedObjectModel release]; [persistentStoreCoordinator release]; [window release]; [navigationController release]; [super dealloc]; } @end
GET / HTTP/1.0 newline newline
HTTP/1.1 200 OK Date: Wed, 07 Oct 2009 18:11:01 GMT Server: Apache/2.2.0 (Fedora) Last-Modified: Mon, 17 Nov 2008 23:09:56 GMT ETag: "f5678-2723-ad5ef900" Accept-Ranges: bytes Content-Length: 10019 Connection: close Content-Type: text/html ...CS Department homepage
@Override public void onStart() { super.onStart(); ConnectivityManager cMgr = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cMgr.getActiveNetworkInfo(); this.status.setText(netInfo.toString()); }
<uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"> The first is for general networking, the second is for the actual info we have above.
import java.io.*; import java.net.*; public final class MyServer extends Thread { private static final int PORT=8889; private static final int NUM_CONNECT=1; private MyServer() {} public static void main(String args[]) { MyServer myServer = new MyServer(); if(myServer !=null) {myServer.start();} } public void run() { try { ServerSocket server = new ServerSocket(PORT, NUM_CONNECT); Socket client = server.accept(); BufferedReader reader = new BufferedReader( new InputStreamReader(client.getInputStream())); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(client.getOutputStream())); // do some reading and writing } catch(IOException ie) { ie.printStackTrace(); } } }
package org.pollett; import android.app.Activity; import android.os.Bundle; import android.net.*; import android.content.*; import android.util.*; public class MyClient extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.socketButton.setOnClickListener(new OnClickListener)() { public void onClick(final View v) { socketOutput.setText(""); String output = callSocket(ipAddress.getText().toString(), port.getText().toString(), socketInput.getText().toString()); socketOutput.setText(output); } } } private String callSocket(String ip, String port, String socketData) { Socket socket = null; BufferedWriter writer = null; BufferedReader reader =null; String output = null; try{ socket = new Socket(ip, Integer.parseInt(port)); reader = new BufferedReader( new InputStreamReader(socket.getInputStream())); writer = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())); writer.write("hello world"+socketData+"\n"); writer.flush(); output = reader.readLine(); } catch(Exception e){} return output; } }