tag:blogger.com,1999:blog-54754610393149732432019-03-19T21:39:33.807-04:00Programmers Sample Guide, help is on the way<i>All one can think and do in a short time is to think what one already knows and to do as one has always done!</i>BetterThanZeronoreply@blogger.comBlogger554125tag:blogger.com,1999:blog-5475461039314973243.post-23995088697254007352019-03-19T21:39:00.000-04:002019-03-19T21:39:33.727-04:00Swift instantiate view controllers from StoryboardYou can use a storyboard object to instantiate the initial view controller or instantiate other view controllers that you want to present programmatically using the identifier. <br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="https://4.bp.blogspot.com/-zFolJj1EX5A/XJGZcwPahmI/AAAAAAAAKMQ/zUe7kxhaJtosF8gwckg_08lgRR8NYORBACLcBGAs/s1600/Screen%2BShot%2B2019-03-19%2Bat%2B9.34.36%2BPM.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img alt="Swift instantiate view controllers from Storyboard" border="0" data-original-height="454" data-original-width="1600" height="179" src="https://4.bp.blogspot.com/-zFolJj1EX5A/XJGZcwPahmI/AAAAAAAAKMQ/zUe7kxhaJtosF8gwckg_08lgRR8NYORBACLcBGAs/s640/Screen%2BShot%2B2019-03-19%2Bat%2B9.34.36%2BPM.png" width="640" /></a></div><pre class="brush: plain"><br />let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)<br /><br />//Get Initial ViewController<br />let mainViewController = mainStoryboard.instantiateInitialViewController()<br /><br />//Get ViewController by Id<br />let mainViewController = mainStoryboard.instantiateViewController(withIdentifier: "myId")<br /><br /></pre>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-30123915864483225972019-03-19T18:36:00.001-04:002019-03-19T21:39:33.746-04:00Image file upload Java Servlet Example<pre class="brush: java"><br /><br />import java.io.File;<br />import java.io.IOException;<br />import java.io.PrintWriter;<br />import java.math.BigInteger;<br />import java.security.SecureRandom;<br />import java.util.Iterator;<br />import java.util.List;<br /><br />import javax.servlet.ServletException;<br />import javax.servlet.http.HttpServlet;<br />import javax.servlet.http.HttpServletRequest;<br />import javax.servlet.http.HttpServletResponse;<br /><br />import org.apache.commons.fileupload.FileItem;<br />import org.apache.commons.fileupload.FileUploadException;<br />import org.apache.commons.fileupload.disk.DiskFileItemFactory;<br />import org.apache.commons.fileupload.servlet.ServletFileUpload;<br />import org.apache.commons.io.FilenameUtils;<br />import org.apache.logging.log4j.LogManager;<br />import org.apache.logging.log4j.Logger;<br /><br />import com.google.gson.JsonObject;<br /><br />public class ImageUpload extends HttpServlet {<br /><br /> private static final long serialVersionUID = 1L;<br /> private Logger logger = null;<br /> <br /> private File tmpDir;<br /> private static final String DESTINATION_DIR_PATH ="/images/new";<br /> private static final String TEMP_DIR_PATH ="/images/temp";<br /> private File destinationDir;<br /><br /> public ImageUpload() {<br /> super();<br /> logger = LogManager.getLogger(ImageUpload.class);<br /> }<br /><br /> protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<br /> //do nothing here ...<br /> }<br /><br /> protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<br /><br /> tmpDir = new File(TEMP_DIR_PATH);<br /> if(!tmpDir.isDirectory()) {<br /> throw new ServletException(TEMP_DIR_PATH + " is not a directory");<br /> }<br /> <br /> destinationDir = new File(DESTINATION_DIR_PATH);<br /> if(!destinationDir.isDirectory()) {<br /> destinationDir.mkdirs();<br /> }<br /> <br /> //PrintWriter to send the JSON response back<br /> PrintWriter out = response.getWriter();<br /> <br /> //set content type and header attributes<br /> response.setContentType("text/html");<br /> response.setHeader("Cache-control", "no-cache, no-store");<br /> response.setHeader("Pragma", "no-cache");<br /> response.setHeader("Expires", "-1");<br /> response.setHeader("Access-Control-Allow-Origin", "*");<br /> response.setHeader("Access-Control-Allow-Methods", "POST");<br /> response.setHeader("Access-Control-Allow-Headers", "Content-Type");<br /> response.setHeader("Access-Control-Max-Age", "86400");<br /><br /> DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();<br /><br /> //Set the size threshold, above which content will be stored on disk.<br /> fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB<br /><br /> //Set the temporary directory to store the uploaded files of size above threshold.<br /> fileItemFactory.setRepository(tmpDir);<br /><br /> ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);<br /> JsonObject myObj = new JsonObject();<br /><br /> File file = null;<br /> String filename = null;<br /><br /> try {<br /><br /> //Parse the request<br /> List items = uploadHandler.parseRequest(request);<br /> Iterator iterator = items.iterator();<br /> while(iterator.hasNext()) {<br /> FileItem item = (FileItem) iterator.next();<br /><br /> //Handle Form Fields<br /> if(item.isFormField()) {<br /> if(item.getFieldName().trim().equalsIgnoreCase("pictureDirectory")){<br /> String pictureDirectory = item.getString().trim();<br /> if(pictureDirectory.trim().equals("")){<br /> pictureDirectory = DESTINATION_DIR_PATH;<br /> destinationDir = new File(DESTINATION_DIR_PATH);<br /> if(!destinationDir.isDirectory()) {<br /> destinationDir.mkdirs();<br /> }<br /> }<br /> }<br /> logger.debug("File Name = "+item.getFieldName()+", Value = "+item.getString());<br /> } <br /><br /> //Handle Uploaded files.<br /> else {<br /> logger.debug("Field Name = " + item.getFieldName()+<br /> ", File Name = " + item.getName()+<br /> ", Content type = " + item.getContentType()+<br /> ", File Size = " + item.getSize());<br /> <br /> //Write file to the ultimate location.<br /> filename = item.getName().trim();<br /> file = new File(destinationDir, filename);<br /> item.write(file);<br /> <br /> //Write the file with a new name<br /> filename = getRandomString() + "." +<br /> FilenameUtils.getExtension(filename);<br /> file = new File(destinationDir, filename);<br /> item.write(file);<br /> }<br /><br /><br /><br /> }<br /><br /> myObj.addProperty("success", true);<br /> myObj.addProperty("picturePath", file.getAbsolutePath());<br /> myObj.addProperty("pictureName", filename);<br /> logger.debug("End...");<br /> <br /> }<br /><br /> catch(FileUploadException ex) {<br /> ex.printStackTrace();<br /> myObj.addProperty("success", false);<br /> } <br /><br /> catch(Exception ex) {<br /> ex.printStackTrace();<br /> myObj.addProperty("success", false);<br /> out.println(myObj.toString());<br /> }<br /><br /> out.println(myObj.toString());<br /> out.close();<br /><br /> }<br /><br /> private String getRandomString() {<br /><br /> SecureRandom random = new SecureRandom();<br /> String randomString = new BigInteger(130, random).toString(32);<br /> return(randomString);<br /> }<br /><br />}<br /><br /></pre>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-5623204920070812172019-03-19T17:11:00.001-04:002019-03-19T21:39:33.759-04:00Binary operator '+' cannot be applied to operands of type 'Int' and 'Double'Just use the Double() function to initialize a Double value with the integer value. <pre class="brush: plain"><br />import UIKit<br /><br />let myInt : Int = 111<br />let myDouble : Double = 222.222<br /><br />//Incorrect addition of Integer and Double<br />print(String(format: "%.9f", myInt + myDouble))<br /><br />//Correct Way to add Integer and Double<br />print(String(format: "%.9f", Double(myInt) + myDouble))<br />//Result = 333.222000000<br /><br /></pre>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-25790157147827049462019-03-19T17:03:00.001-04:002019-03-19T21:39:33.739-04:00Java convert PNG Image to GIF<pre class="brush: java"><br /> private void makeGIFfile(String pngFilePath, String gifFilePath) {<br /><br /> File input = new File(pngFilePath);<br /> File output = new File(gifFilePath);<br /> BufferedImage bufferedImage;<br /><br /> try {<br /> bufferedImage = ImageIO.read(input);<br /> //Create a blank, RGB, same width and height, and a white background<br /> BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),<br /> bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);<br /> newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);<br /><br /> //Write the image file with GIF extension<br /> ImageIO.write(newBufferedImage, "gif", output);<br /><br /> } catch (IOException e) {<br /> e.printStackTrace();<br /> } <br /><br /> }<br /></pre>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-77434736396286967302019-03-19T17:03:00.000-04:002019-03-19T21:39:33.765-04:00Java Rotate and Scale an Image <pre class="brush: java"><br /> private void imageRotateScale(String imageFilePath, String outImagePath) {<br /><br /> File input = new File(imageFilePath);<br /> File output = new File(outImagePath);<br /> BufferedImage bufferedImage;<br /><br /> try {<br /> bufferedImage = ImageIO.read(input);<br /> //Create a blank, RGB, same width and height, and a white background<br /> BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),<br /> bufferedImage.getHeight(), BufferedImage.TYPE_INT_RGB);<br /> newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, Color.WHITE, null);<br /> //Scale the Image by half, Change 0.5 to Whatever Value you want it to Shrink<br /> newBufferedImage = scale(newBufferedImage, (int) Math.round(bufferedImage.getWidth() * 0.5), (int) Math.round(bufferedImage.getHeight() * 0.5));<br /><br /> //Time to Rotate the Image<br /> int w = newBufferedImage.getWidth();<br /> int h = newBufferedImage.getHeight();<br /> AffineTransform scaleTransform = new AffineTransform();<br /> scaleTransform.translate(h/2,w/2);<br /> scaleTransform.rotate(-1 * (Math.PI / 2));<br /> scaleTransform.translate(-w/2,-h/2);<br /> AffineTransformOp scaleOp = new AffineTransformOp(<br /> scaleTransform, AffineTransformOp.TYPE_BILINEAR);<br /> newBufferedImage = scaleOp.filter(newBufferedImage, null);<br /><br /> //Write the output Image file<br /> ImageIO.write(newBufferedImage, "jpg", output);<br /><br /> } catch (IOException e) {<br /> e.printStackTrace(); <br /> } <br /><br /> }<br /><br /><br /> private BufferedImage scale(BufferedImage image, int targetWidth, int targetHeight) {<br /><br /> int type = (image.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;<br /> BufferedImage newImage = image;<br /> BufferedImage scratchImage = null;<br /> Graphics2D g2 = null;<br /><br /> int w = image.getWidth();<br /> int h = image.getHeight();<br /><br /> int prevW = w;<br /> int prevH = h;<br /><br /> do {<br /> if (w > targetWidth) {<br /> w /= 2;<br /> w = (w < targetWidth) ? targetWidth : w;<br /> }<br /><br /> if (h > targetHeight) {<br /> h /= 2;<br /> h = (h < targetHeight) ? targetHeight : h;<br /> }<br /><br /> if (scratchImage == null) {<br /> scratchImage = new BufferedImage(w, h, type);<br /> g2 = scratchImage.createGraphics();<br /> }<br /><br /> g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,<br /> RenderingHints.VALUE_INTERPOLATION_BILINEAR);<br /> g2.drawImage(newImage, 0, 0, w, h, 0, 0, prevW, prevH, null);<br /><br /> prevW = w;<br /> prevH = h;<br /> newImage = scratchImage;<br /> } while (w != targetWidth || h != targetHeight);<br /><br /> if (g2 != null) {<br /> g2.dispose();<br /> }<br /><br /> if (targetWidth != newImage.getWidth() || targetHeight != newImage.getHeight()) {<br /> scratchImage = new BufferedImage(targetWidth, targetHeight, type);<br /> g2 = scratchImage.createGraphics();<br /> g2.drawImage(newImage, 0, 0, null);<br /> g2.dispose();<br /> newImage = scratchImage;<br /> }<br /><br /> return newImage;<br /><br /> }<br /></pre>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-37657785243066888972019-03-19T17:02:00.002-04:002019-03-19T21:39:33.752-04:00Swift Float versus DoubleBoth can be used for Decimal Number Representation. The Float type represents a 32-bit floating-point number, while the Double type represents a 64-bit floating-point number. It is always recommended that we use the Double type rather than the Float type because the Double type has a precision of at least 15 decimal digits whereas the Float type's precision can be as small as six decimal digits. <pre class="brush: plain"><br />import UIKit<br /><br />let myFloat1 : Float = 111.111_111_111<br />let myFloat2 : Float = 222.222_222_222<br />print(String(format: "%.9f", myFloat1 + myFloat2))<br />//Result = 333.333343506<br /><br />let myDouble1 : Double = 111.111_111_111<br />let myDouble2 : Double = 222.222_222_222<br />print(String(format: "%.9f", myDouble1 + myDouble2))<br />//Result = 333.333333333<br /></pre>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-27537846582098540562019-03-19T00:42:00.000-04:002019-03-19T00:42:00.258-04:00How to format a Numeric value in Swift with Currency symbol and Decimal Precision<b>Use NumberFormatter</b> - A formatter that converts between numeric values and their textual representations. <pre class="brush: plain"><br />import UIKit<br /><br />extension Formatter {<br /> static let withDecimalSeparator: NumberFormatter = {<br /> <br /> let formatter = NumberFormatter()<br /> formatter.groupingSeparator = "_"<br /> formatter.decimalSeparator = "."<br /> formatter.minimumFractionDigits = 2<br /> formatter.maximumFractionDigits = 2<br /> formatter.numberStyle = .decimal<br /> <br /> return formatter<br /> }()<br /> <br /> static let withCurrencySeparator: NumberFormatter = {<br /> <br /> let formatter = NumberFormatter()<br /> formatter.currencySymbol = "$"<br /> formatter.decimalSeparator = "."<br /> formatter.minimumFractionDigits = 2<br /> formatter.maximumFractionDigits = 2<br /> formatter.numberStyle = .currency<br /> <br /> return formatter<br /> }()<br />}<br /><br />extension Double {<br /> var formattedWithSeparator1: String {<br /> return Formatter.withDecimalSeparator.string(for: self) ?? ""<br /> }<br /> var formattedWithSeparator2: String {<br /> return Formatter.withCurrencySeparator.string(for: self) ?? ""<br /> }<br />}<br /><br />var myString = "123456.1149"<br />var myDouble : Double = Double(myString) ?? 0<br />print(myDouble.formattedWithSeparator1)<br />//Result = 123_456.11<br />print(myDouble.formattedWithSeparator2)<br />//Result = $123,456.11<br /><br />myString = "123456.1150"<br />myDouble = Double(myString) ?? 0<br />print(myDouble.formattedWithSeparator1)<br />//Result = 123_456.12<br />print(myDouble.formattedWithSeparator2)<br />//Result = $123,456.12<br /></pre>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-91518823964483669122019-03-19T00:29:00.000-04:002019-03-19T00:33:48.629-04:00What is the meaning of underscores in swift numbersWell it's just for <b>code readability</b>. As per Apple developer doc Numeric literals can contain extra formatting to make them easier to read. Both integers and floats can be padded with extra zeros and can contain underscores to help with readability. Neither type of formatting affects the underlying value of the literal. <pre class="brush: plain"><br />let myDouble1 : Double = 123_456.789_123<br />let MyDouble2 : Double = 123456.789123<br />if myDouble1 == MyDouble2 {<br /> print("Yes they are the same!")<br />}<br /></pre>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-11964322461096081732019-03-18T00:24:00.001-04:002019-03-18T00:24:35.440-04:00iOS Swift create button programmatically using Auto Layout Visual Format Language (VFL)<div class="separator" style="clear: both; text-align: center;"><a href="https://2.bp.blogspot.com/-0LlUkbgojzE/XI8ap56gWDI/AAAAAAAAKL8/4jkfjx7AMKMU-x7aBhkzpfPT9vhK7ixkwCLcBGAs/s1600/Simulator%2BScreen%2BShot%2B-%2BiPhone%2BXR%2B-%2B2019-03-18%2Bat%2B00.11.53.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img alt="iOS Swift create button programmatically using Auto Layout Visual Format Language" border="0" data-original-height="740" data-original-width="1600" height="294" src="https://2.bp.blogspot.com/-0LlUkbgojzE/XI8ap56gWDI/AAAAAAAAKL8/4jkfjx7AMKMU-x7aBhkzpfPT9vhK7ixkwCLcBGAs/s640/Simulator%2BScreen%2BShot%2B-%2BiPhone%2BXR%2B-%2B2019-03-18%2Bat%2B00.11.53.png" width="640" /></a></div><div class="separator" style="clear: both; text-align: center;"></div><br /><h3>VFL symbols to describe your layout</h3><ul><li>V Vertical Layout</li><li>H Horizontal Layout</li><li>| superview</li><li>- standard spacing (usually 8 points)</li><li>== equal widths </li><li>-20- non standard spacing (20 points)</li><li><= less than or equal to</li><li>>= greater than or equal to</li><li>@ priority can have any value between 0 and 1000</li></ul><br /><pre class="brush: plain">import UIKit<br /><br />class ViewController: UIViewController {<br /><br /> override func viewDidLoad() {<br /> super.viewDidLoad()<br /> <br /> //Add a button programmatically<br /> addButton1()<br /> <br /> //Add a button programmatically using Auto Layout Visual Format Language (VFL)<br /> addButton2()<br /> <br /> //Add two buttons side by side programmatically using Auto Layout Visual Format Language (VFL)<br /> addButton3()<br /> <br /> //Add two buttons one below another programmatically using Auto Layout Visual Format Language (VFL)<br /> addButton4()<br /> <br /> }<br /> <br /> func addButton1(){<br /> <br /> let button = UIButton(frame: CGRect(x: 100, y: 50, width: 200, height: 50))<br /> button.setTitle("My first Button", for: .normal)<br /> button.setTitleColor(.red, for: .normal)<br /> <br /> button.backgroundColor = UIColor(red: 0.4, green: 1.0, blue: 0.2, alpha: 0.5)<br /> button.layer.cornerRadius = 10;<br /> button.layer.borderWidth = 1<br /> button.layer.borderColor = UIColor.black.cgColor<br /> button.clipsToBounds = true;<br /> <br /> button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)<br /> self.view.addSubview(button)<br /> <br /> }<br /> <br /> func addButton2(){<br /> <br /> let button2 = UIButton()<br /> button2.setTitle("My second Button", for: .normal)<br /> button2.backgroundColor = UIColor.red<br /> self.view.addSubview(button2)<br /> <br /> button2.translatesAutoresizingMaskIntoConstraints = false<br /> var allConstraints: [NSLayoutConstraint] = []<br /> let views = ["view": view!, "button2": button2]<br /> <br /> let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=10)-[button2(200)]-(>=10)-|", metrics: nil, views: views)<br /> allConstraints += horizontalConstraints<br /> button2.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true<br /> <br /> let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(<=120)-[button2(50)]", metrics: nil, views: views)<br /> allConstraints += verticalConstraints<br /> NSLayoutConstraint.activate(allConstraints)<br /> <br /> button2.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)<br /> <br /> }<br /> <br /> func addButton3(){<br /> <br /> let button1 = UIButton()<br /> button1.setTitle("Third Button", for: .normal)<br /> button1.backgroundColor = UIColor.black<br /> self.view.addSubview(button1)<br /> <br /> let button2 = UIButton()<br /> button2.setTitle("Fourth Button", for: .normal)<br /> button2.backgroundColor = UIColor.black<br /> self.view.addSubview(button2)<br /> <br /> button1.translatesAutoresizingMaskIntoConstraints = false<br /> button2.translatesAutoresizingMaskIntoConstraints = false<br /> var allConstraints: [NSLayoutConstraint] = []<br /> let views = ["button1": button1, "button2": button2]<br /> <br /> let horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[button1(200)]-(>=10)-[button2(200)]-|", metrics: nil, views: views)<br /> allConstraints += horizontalConstraints<br /> <br /> let button1verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(<=200)-[button1(50)]", metrics: nil, views: views)<br /> allConstraints += button1verticalConstraints<br /> let button2verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(<=200)-[button2(50)]", metrics: nil, views: views)<br /> allConstraints += button2verticalConstraints<br /> <br /> NSLayoutConstraint.activate(allConstraints)<br /> <br /> button1.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)<br /> button2.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)<br /> <br /> <br /> }<br /> <br /> func addButton4(){<br /> <br /> let button1 = UIButton()<br /> button1.setTitle("Fifth Button", for: .normal)<br /> button1.backgroundColor = UIColor.gray<br /> self.view.addSubview(button1)<br /> <br /> let button2 = UIButton()<br /> button2.setTitle("Sixth Button", for: .normal)<br /> button2.backgroundColor = UIColor.gray<br /> self.view.addSubview(button2)<br /> <br /> button1.translatesAutoresizingMaskIntoConstraints = false<br /> button2.translatesAutoresizingMaskIntoConstraints = false<br /> var allConstraints: [NSLayoutConstraint] = []<br /> let views = ["button1": button1, "button2": button2]<br /> <br /> let button1horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=20)-[button1(200)]-(>=20)-|", metrics: nil, views: views)<br /> allConstraints += button1horizontalConstraints<br /> <br /> let button2horizontalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=20)-[button2(200)]-(>=20)-|", metrics: nil, views: views)<br /> allConstraints += button2horizontalConstraints<br /> <br /> let verticalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-(>=260)-[button1(50)]-(>=20)-[button2(50)]-|", metrics: nil, views: views)<br /> allConstraints += verticalConstraints<br /> <br /> button1.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true<br /> button2.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true<br /> <br /> NSLayoutConstraint.activate(allConstraints)<br /> <br /> button1.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)<br /> button2.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)<br /> <br /> <br /> }<br /> <br /> @objc func buttonAction(sender: UIButton!) {<br /> if let buttonTitle = sender.titleLabel?.text {<br /> print(buttonTitle + " tapped!")<br /> }<br /> }<br /><br />}<br /><br /></pre><b>Reference:</b> <a href="https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage.html" rel="nofollow">Visual Format Language</a>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-42760246637836613952019-03-16T22:46:00.000-04:002019-03-16T22:46:24.604-04:00How to send JSON data post to a REST Web Service using Java TLS with Authorization HeaderWith the increasing popularity of JSON data as transport medium and REST Web Services being used for system to system integration this a very basic requirement these days.<br/><br/><h3>Source for WebServiceHandler.java</h3> <pre class="brush: java"><br />import java.io.BufferedReader;<br />import java.io.InputStreamReader;<br />import java.io.OutputStream;<br />import java.net.URL;<br />import java.nio.charset.StandardCharsets;<br /><br />import javax.net.ssl.HttpsURLConnection;<br />import javax.net.ssl.SSLContext;<br /><br />import com.ebusiness.objects.JsonResponse;<br /><br /><br />public class WebServiceHandler {<br /><br /> public WebServiceHandler() {<br /> }<br /><br /> public JsonResponse makeServiceCall(String url, String username, String password,<br /> String jsonString) {<br /><br /> JsonResponse jsonResponse = new JsonResponse();<br /><br /> try{ <br /><br /> SSLContext sc = SSLContext.getInstance("TLSv1.2"); <br /> sc.init(null, null, new java.security.SecureRandom());<br /><br /> URL myUrl = new URL(url);<br /> HttpsURLConnection conn = (HttpsURLConnection) myUrl.openConnection();<br /> conn.setSSLSocketFactory(sc.getSocketFactory());<br /> conn.setDoOutput(true);<br /> conn.setReadTimeout(30000);<br /> conn.setConnectTimeout(30000);<br /> conn.setUseCaches(false);<br /> conn.setAllowUserInteraction(false);<br /> conn.setRequestMethod("POST");<br /> conn.setRequestProperty("Content-Type", "application/json");<br /> conn.setRequestProperty("Accept-Charset", "UTF-8");<br /><br /> String userCredentials = username.trim() + ":" + password.trim();<br /> String basicAuth = "Basic " + new String(Base64.encodeBytes(userCredentials.getBytes()));<br /> conn.setRequestProperty ("Authorization", basicAuth);<br /><br /> OutputStream os = conn.getOutputStream();<br /> os.write(jsonString.getBytes());<br /> os.flush(); <br /> os.close();<br /><br /> InputStreamReader isr = conn.getResponseCode() == HttpsURLConnection.HTTP_OK ? new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8) : new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8);<br /> BufferedReader reader = new BufferedReader(isr);<br /> String line;<br /> String resultLine = "";<br /> while((line = reader.readLine()) != null) {<br /> resultLine = resultLine + line;<br /> }<br /> reader.close();<br /> jsonResponse.setSuccess(true);<br /> jsonResponse.setResponseData(resultLine);<br /><br /> } catch (Exception ex) {<br /> ex.printStackTrace();<br /> } <br /><br /> return jsonResponse;<br /><br /> }<br /><br />}<br /></pre><h3>Source for JsonResponse.java</h3> <pre class="brush: java"><br />public class JsonResponse {<br /> <br /> private boolean success = false;<br /> private String responseData = "";<br /> <br /> public boolean isSuccess() {<br /> return success;<br /> }<br /> public void setSuccess(boolean success) {<br /> this.success = success;<br /> }<br /> public String getResponseData() {<br /> return responseData;<br /> }<br /> public void setResponseData(String responseData) {<br /> this.responseData = responseData;<br /> }<br /> <br /><br />}<br /></pre>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-44270900901020513912019-03-12T22:55:00.001-04:002019-03-13T10:40:52.209-04:00Check if AS400 (IBMi Power System) Password Expired and Update new Password using JavaYou will need to use the Toolbox for Java/JTOpen. Please dow download <b>jt400.jar</b> from <a href="https://sourceforge.net/projects/jt400/">https://sourceforge.net/projects/jt400/</a>OR find it here in your system IFS path <b>/QIBM/ProdData/HTTP/Public/jt400/lib</b><br /><br /> <h3>Verify password</h3> <pre class="brush: java"><br />private LoginResponse authenticateAS400(String userId, String password) { <br /><br /> LoginResponse response = new LoginResponse();<br /> boolean success = false;<br /><br /> try { <br /> AS400 system = new AS400();<br /> success = system.authenticate(userId.trim().toUpperCase(), password.trim());<br /> } <br /> catch(AS400SecurityException e){<br /> if(e.getReturnCode() == AS400SecurityException.PASSWORD_EXPIRED){<br /> response.setPasswordExpired(true);<br /> }<br /> response.setErrorMessage(e.getMessage());<br /> e.printStackTrace();<br /> } <br /> catch(Exception e){<br /> response.setErrorMessage(e.getMessage());<br /> e.printStackTrace();<br /> } <br /><br /> response.setSuccess(success);<br /><br /> return response;<br /><br /> }<br /></pre><pre class="brush: java"><br />public class LoginResponse {<br /><br /> boolean success = false;<br /> boolean passwordExpired = false;<br /> String errorMessage = "";<br /> <br /> public boolean isSuccess() {<br /> return success;<br /> }<br /> public void setSuccess(boolean success) {<br /> this.success = success;<br /> }<br /> public boolean isPasswordExpired() {<br /> return passwordExpired;<br /> }<br /> public void setPasswordExpired(boolean passwordExpired) {<br /> this.passwordExpired = passwordExpired;<br /> }<br /> public String getErrorMessage() {<br /> return errorMessage;<br /> }<br /> public void setErrorMessage(String errorMessage) {<br /> this.errorMessage = errorMessage;<br /> }<br /> <br /> <br />}<br /></pre> <h3>Updating the password</h3> <pre class="brush: java"><br />AS400 system = new AS400("localhost",userId.trim().toUpperCase());<br />system.changePassword(oldPassword.trim().toUpperCase(), password.trim());<br /><br /></pre>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-53385932201326698022019-03-12T22:54:00.000-04:002019-03-12T22:54:37.901-04:00Android app on Google Play Store available on ZERO (0) devicesYour app gets uploaded thru the Release Manager on <b>Google Play Store</b> successfully. It even displays that its available on the app store on Google Play website but when you try to download from a device its not available. On further checking you will see that on the console it will say <b>available on 0 devices</b>.<br />Another scenario is when the app is already available on the play store but with a new app update its giving you WARNING - <b>Device support removed</b>. Deactivation of this APK will result in your app being available for new installs on fewer types of devices. <br /><div class="separator" style="clear: both; text-align: left;"><a href="https://3.bp.blogspot.com/-Og0o0ne8D6I/XIhHEUr92oI/AAAAAAAAKKk/pDFL6-z1Qcohcs67JTpukcSvFoXRrjTKACLcBGAs/s1600/Screen%2BShot%2B2019-03-12%2Bat%2B7.55.06%2BPM.png" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em;"><img border="0" data-original-height="568" data-original-width="1152" height="313" src="https://3.bp.blogspot.com/-Og0o0ne8D6I/XIhHEUr92oI/AAAAAAAAKKk/pDFL6-z1Qcohcs67JTpukcSvFoXRrjTKACLcBGAs/s640/Screen%2BShot%2B2019-03-12%2Bat%2B7.55.06%2BPM.png" width="640" /></a></div><div class="separator" style="clear: both; text-align: left;"><br /></div>The issue here is device dependency <b>org.apache.directory.studio:org.apache.commons.io:2.4</b><br /><br /><h3>To resolve this make changes to the app build.gradle dependencies and replace this with commons-io:commons-io:2.4</h3><pre class="brush: plain">dependencies {<br /> implementation 'com.android.support.constraint:constraint-layout:1.0.2'<br /> implementation 'com.android.support:design:27.0.2'<br /> <br /> //implementation 'org.apache.directory.studio:org.apache.commons.io:2.4'<br /> implementation 'commons-io:commons-io:2.4'<br /><br /> implementation 'com.google.code.gson:gson:2.2.4'<br /> implementation files('libs/universal-image-loader-1.9.1-with-sources.jar')<br /> implementation 'com.android.support:cardview-v7:27.0.+'<br /> implementation 'com.android.support:recyclerview-v7:27.0.+'<br />}<br /></pre>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-3272973503251408802019-03-11T23:19:00.002-04:002019-03-11T23:19:40.151-04:00Java Round UP to 2 Decimals<h3>TestRounding.java Source</h3><pre class="brush: java"><br />import java.math.BigDecimal;<br /><br />public class TestRounding {<br /><br /> public TestRounding() {<br /> }<br /><br /> public static void main(String[] args) {<br /> <br /> BigDecimal totalWeight = new BigDecimal("80.94999999999999");<br /> totalWeight = totalWeight.setScale(2, BigDecimal.ROUND_HALF_UP);<br /> System.out.println(totalWeight.toString());<br /> //Result = 80.95<br /> <br /> totalWeight = new BigDecimal("80.955000000001");<br /> totalWeight = totalWeight.setScale(2, BigDecimal.ROUND_HALF_UP);<br /> System.out.println(totalWeight.toString());<br /> //Result = 80.96<br /><br /> }<br /><br />}<br /></pre>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-23140585517478387152019-03-11T23:03:00.001-04:002019-03-11T23:03:26.764-04:00How to send a PDF file to an OUTQ in AS400 (IBMi Power System)To print a PDF document directly thru AS400 you can use the Toolbox for Java/JTOpen. Also please make sure that the printer connected to that Output Queue is PDF capable that can directly take a PDF data stream and print it. <br/> <br/>You can download <b>jt400.jar</b> from <a href="https://sourceforge.net/projects/jt400/">https://sourceforge.net/projects/jt400/</a>OR find it here in your system IFS path <b>/QIBM/ProdData/HTTP/Public/jt400/lib</b><br/> <br/><h3>PrintPDFAS400.java Source</h3><pre class="brush: java"><br />package com.mysamplecode;<br /><br />import java.io.FileInputStream;<br />import java.io.InputStream;<br />import java.net.URL;<br />import java.net.URLConnection;<br />import java.util.Properties;<br /><br />import com.ibm.as400.access.AS400;<br />import com.ibm.as400.access.OutputQueue;<br />import com.ibm.as400.access.PrintObject;<br />import com.ibm.as400.access.PrintParameterList;<br />import com.ibm.as400.access.SpooledFileOutputStream;<br /><br />public class PrintPDFAS400 {<br /><br /> static Properties props;<br /><br /> public static void main(String[] args) {<br /><br /> String filePath = null;<br /> String outputQueue = null;<br /><br /> PrintPDFAS400 printPDF = new PrintPDFAS400();<br /> if (args.length < 2)<br /> {<br /> System.err.println("Usage: java " + printPDF.getClass().getName() +<br /> " File_Path Output_Queue");<br /> System.exit(1);<br /> }<br /><br /> filePath = args[0].trim();<br /> outputQueue = args[1].trim();<br /> printPDF.sendToPrinter(filePath, outputQueue);<br /><br /> }<br /><br /> public boolean sendToPrinter(String filePath, String outputQueue){<br /><br /> boolean printed = false; <br /><br /> try {<br /><br /> props = new Properties();<br /> props.load(new FileInputStream("properties/as400connection.properties"));<br /><br /> //Connect to AS400<br /> AS400 as400 = new AS400(props.getProperty("iSeries").trim(), props.getProperty("userId").trim(), props.getProperty("password").trim());<br /><br /> //Get Access to Output Queue<br /> String outputQueuePath = "/QSYS.LIB/QGPL.LIB/" + outputQueue.trim() + ".OUTQ";<br /> OutputQueue outQ = new OutputQueue(as400, outputQueuePath);<br /><br /> //Parms for Spool file<br /> PrintParameterList parms = new PrintParameterList();<br /> parms.setParameter(PrintObject.ATTR_COPIES, 1);<br /> parms.setParameter(PrintObject.ATTR_OUTPUT_QUEUE, outQ.getPath());<br /> SpooledFileOutputStream osSpool = new SpooledFileOutputStream(as400, parms, null, null);<br /><br /> InputStream fisPDF = null;<br /><br /> //PDF needs to be downloaded from the WEB link<br /> if (filePath.toLowerCase().indexOf("http") == 0) {<br /> URL url = new URL(filePath);<br /> URLConnection urlConnect = url.openConnection();<br /> if (urlConnect.getContentType().equalsIgnoreCase("application/pdf")) {<br /> fisPDF = url.openStream();<br /> }<br /> }<br /><br /> //PDF is stored locally on the server<br /> else {<br /> fisPDF = new FileInputStream(filePath);<br /> }<br /><br /> byte[] buf = new byte[2048];<br /> int bytesRead;<br /> do {<br /> bytesRead = fisPDF.read(buf);<br /> if (bytesRead != -1) {<br /> osSpool.write(buf, 0, bytesRead);<br /> }<br /> }<br /> while (bytesRead != -1);<br /> osSpool.flush();<br /> osSpool.close();<br /> fisPDF.close();<br /> printed = true; <br /><br /> }<br /> catch (Exception e)<br /> {<br /> System.out.println("Exception occured while creating the spooled file.");<br /> e.printStackTrace();<br /> }<br /><br /> return printed;<br /><br /> }<br /><br /><br />}<br /><br /></pre><h3>as400connection.properties Source</h3><pre class="brush: plain"><br />iSeries=192.168.100.123<br />userId=SAMPLE<br />password=******<br /></pre>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-17094300570925937522019-03-11T00:15:00.001-04:002019-03-11T23:05:43.678-04:00Get Job Status by Subsystem, Job Name or User Profile in AS400 (IBMi Power System)This information is very useful if you want to keep an eye on long running server jobs for status updates, may be check for jobs on message wait. <br/>Here is how you can do it with a very simple SQL <br/><br/><h3>OS version 7.2 or higher</h3> <pre class="brush: sql"><br />SELECT JOB_NAME, JOB_TYPE, JOB_STATUS,SUBSYSTEM, <br /> AUTHORIZATION_NAME JOB_USER, <br /> ELAPSED_CPU_PERCENTAGE AS PERCENT <br /> FROM TABLE(QSYS2.ACTIVE_JOB_INFO(JOB_NAME_FILTER => '*ALL')) A <br /> where SUBSYSTEM = 'QSERVER' <br /> ORDER BY SUBSYSTEM, ELAPSED_CPU_PERCENTAGE DESC <br /></pre><h3>OS version 7.1 or lower</h3> <pre class="brush: sql"><br />SELECT JOB_NAME, JOB_TYPE, JOB_STATUS,SUBSYSTEM, <br /> AUTHORIZATION_NAME JOB_USER, <br /> ELAPSED_CPU_PERCENTAGE AS PERCENT <br /> FROM TABLE(QSYS2.ACTIVE_JOB_INFO('NO', '', '*ALL', '')) A <br /> where SUBSYSTEM = 'QSERVER' <br /> ORDER BY SUBSYSTEM, ELAPSED_CPU_PERCENTAGE DESC <br /></pre><h3>Let's say you want to check for a specific job status</h3><pre class="brush: sql"><br />SELECT JOB_NAME, JOB_TYPE, JOB_STATUS,SUBSYSTEM, <br /> AUTHORIZATION_NAME JOB_USER, <br /> ELAPSED_CPU_PERCENTAGE AS PERCENT <br /> FROM TABLE(QSYS2.ACTIVE_JOB_INFO(JOB_NAME_FILTER => '*ALL')) A <br /> where SUBSYSTEM = 'QSERVER' <br /> and JOB_STATUS in ('MSGW','TIMW') <br /> ORDER BY SUBSYSTEM, ELAPSED_CPU_PERCENTAGE DESC <br /></pre> <h3>Let's say you want to check for a specific job status by a certain user</h3><pre class="brush: sql"><br />SELECT JOB_NAME, JOB_TYPE, JOB_STATUS,SUBSYSTEM, <br /> AUTHORIZATION_NAME JOB_USER, <br /> ELAPSED_CPU_PERCENTAGE AS PERCENT <br /> FROM TABLE(QSYS2.ACTIVE_JOB_INFO(JOB_NAME_FILTER => '*ALL')) A <br /> where (SUBSYSTEM = 'QSERVER' and <br /> AUTHORIZATION_NAME like '%QUSER%' ) <br /> and JOB_STATUS in ('MSGW','TIMW') <br /> ORDER BY SUBSYSTEM, ELAPSED_CPU_PERCENTAGE DESC <br /></pre> <h3>Here is the Result SET</h3><pre class="brush: plain"><br />JOB_NAME JOB_TYPE JOB_STATUS SUBSYSTEM PERCENT <br />103929/QUSER/QPWFSERVSO PJ TIMW QSERVER .0 <br />120560/QUSER/QPWFSERVSO PJ TIMW QSERVER .0 <br />123371/QUSER/QPWFSERVSO PJ TIMW QSERVER .0 <br />124578/QUSER/QZLSFILET PJ TIMW QSERVER .0 <br /></pre> BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-43070311927369067582019-03-07T23:22:00.001-05:002019-03-08T23:45:55.570-05:00How to find out what Stored Procedures exist in AS400 (IBMi Power System) and Retrieve SQL Source <h3>Query Stored Procedures</h3><table><tbody><tr><td valign="top" width="65%">Well you can always use the System i Navigator as shown on the right here to view this info, generate SQL and do much more. But for a quick check there is a <b>VIEW, named PROCEDURES,</b> exists in the system that can simply be queried using STRSQL. <br/><br/><b>Select * from PROCEDURES</b> <br/><br/>If you want to look for procedures in a specific schema (library) then use filter <br/><br/><b>SELECT * FROM PROCEDURES WHERE PROCSCHEMA = '$libName'</b> <br/><br/> </td><td width="35%"><a href="https://3.bp.blogspot.com/-omYoaail1n0/XIHCsMNe7UI/AAAAAAAAKJ4/GyoGBw1XRXIM3yvx90l7RtIlQpcLWOVVgCLcBGAs/s1600/Procedures.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="902" data-original-width="700" height="320" src="https://3.bp.blogspot.com/-omYoaail1n0/XIHCsMNe7UI/AAAAAAAAKJ4/GyoGBw1XRXIM3yvx90l7RtIlQpcLWOVVgCLcBGAs/s320/Procedures.PNG" width="248" /></a></td></tr></tbody></table> <br/><br/>The actual TABLE behind all this is <b>SYSROUTINE</b> and you can choose to directly query that as well. Here is the SQL source for the PROCEDURES view. <pre class="brush: sql"><br />CREATE VIEW PROCEDURES AS <br />SELECT VARCHAR(ROUTINE_SCHEMA , 18) AS PROCSCHEMA , VARCHAR(ROUTINE_NAME , 18) AS PROCNAME , <br />VARCHAR(ROUTINE_DEFINER , 18) AS DEFINER , VARCHAR('' , 18) AS PKGSCHEMA , <br />VARCHAR(EXTERNAL_NAME , 254) AS PROC_LOCATION, <br />TRANSLATE(SUBSTR (PARAMETER_STYLE, 1, 1),'G',' ') AS PARM_STYLE , <br />SUBSTR(EXTERNAL_LANGUAGE, 1, 8) AS "LANGUAGE" , SUBSTR('U', 1, 1) AS STAYRESIDENT , <br />VARCHAR('', 254) AS RUNOPTS , SUBSTR('Y', 1, 1) AS FENCED , <br />VARCHAR(LONG_COMMENT , 254) AS REMARKS , MAX_DYNAMIC_RESULT_SETS AS RESULT_SETS <br />FROM QSYS2.SYSROUTINE <br />WHERE ROUTINE_TYPE = 'PROCEDURE' <br />AND LENGTH(ROUTINE_NAME) < 19 <br /></pre> <h3>Retrieve Stored Procedures SQL source</h3>Now if you want to retrieve the SQL source for any specific Stored Procedure that is also very easy. Create a new member in the source physical file. Just save that as empty and then use this SQL <pre class="brush: sql"><br />CALL GENERATE_SQL('$procedure_name', <br />'$object_lib', <br />'PROCEDURE', <br />'$source_file', <br />'$source_lib', <br />'$member_name ',<br />STATEMENT_FORMATTING_OPTION=>'0') <br /></pre> <br />BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-76440665286738719892019-03-06T21:33:00.000-05:002019-03-06T21:33:10.024-05:00Large json/XML data POST unable to reach Tomcat server job Nowadays it’s a common practice to use json or xml as data transfer between systems or say between a mobile app and the backend server. Well it happened a few days back that some of our POST data requests weren’t showing up on the backend for processing. It took a while for me to figure out that Tomcat has default maximum POST data size limits and anything over that gets rejected. <br /><br />You can change the <b>maxPostSize</b> parameter in the <b>HTTP Connector</b> of the <b>server.xml</b> config. This parameter specifies the maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The limit can be disabled by setting this attribute to a value less than zero. If not specified, this attribute is set to 2097152 (2 megabytes). Note that the FailedRequestFilter can be used to reject requests that exceed this limit. <br /><br /> <h4>Sample Connector Config with increased data size</h4><pre class="brush: xml"><br /><Connector port="8080" protocol="HTTP/1.1" <br /> connectionTimeout="20000" <br /> maxPostSize="6291456" <br /> redirectPort="8443"/> <br /></pre><h4>Reference</h4><ul><li><a href="https://tomcat.apache.org/tomcat-8.0-doc/config/http.html">Apache Tomcat 8 Configuration Reference</a></li></ul><br /> BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-20784221014128860742013-08-05T20:16:00.000-04:002019-03-06T00:38:26.091-05:00iOS UISearchBar with UITableView example<b>UISearchBar</b> class provides a text field for entering text, a search button, a bookmark button, and a cancel button. With the help of the <b>UISearchBarDelegate</b> protocol you can implement the actions that will perform search on a database locally or send a request to the remote server when text is entered or buttons are clicked. In this example we implement the search bar to find a country by its name. The search request is sent to the remote server where a Java Servlet performs a simple query over the MySQL database to return a JSON array that is then displayed to the user using the Table view.<br /><br /><table><tbody><tr><td><a href="https://1.bp.blogspot.com/-PAR9Cx_QoZ4/UgA9Ded2sxI/AAAAAAAADZ0/cxcPnc8r81A/s1600/iOS+UISearchBar+with+UITableView+example.png" imageanchor="1"><img alt="iOS UISearchBar with UITableView example" border="0" height="400" src="https://1.bp.blogspot.com/-PAR9Cx_QoZ4/UgA9Ded2sxI/AAAAAAAADZ0/cxcPnc8r81A/s400/iOS+UISearchBar+with+UITableView+example.png" width="225" /></a></td><td><a href="https://1.bp.blogspot.com/-Fpx_c1Mrvok/UgA9G1JnqMI/AAAAAAAADZ8/W3ZGGscPtbE/s1600/iOS+UISearchBar+query+with+results+in+TableView.png" imageanchor="1"><img alt="iOS UISearchBar query with results in TableView" border="0" height="400" src="https://1.bp.blogspot.com/-Fpx_c1Mrvok/UgA9G1JnqMI/AAAAAAAADZ8/W3ZGGscPtbE/s400/iOS+UISearchBar+query+with+results+in+TableView.png" width="225" /></a></td><td><a href="https://3.bp.blogspot.com/-YyK2lCvUH9U/UgA9MQMb_1I/AAAAAAAADaE/3lzdEttfLFo/s1600/iOS+UISearchBar+query+with+No+Results.png" imageanchor="1"><img alt="iOS UISearchBar query with No Results" border="0" height="400" src="https://3.bp.blogspot.com/-YyK2lCvUH9U/UgA9MQMb_1I/AAAAAAAADaE/3lzdEttfLFo/s400/iOS+UISearchBar+query+with+No+Results.png" width="225" /></a></td></tr></tbody></table><h4>Java Servlet backend for remote search - CountrySearch.java</h4><pre class="brush: java">package com.as400samplecode;<br /><br />import java.io.IOException;<br />import java.io.PrintWriter;<br />import java.sql.Connection;<br />import java.sql.PreparedStatement;<br />import java.sql.ResultSet;<br />import java.sql.SQLException;<br />import java.util.ArrayList;<br /><br />import javax.naming.Context;<br />import javax.naming.InitialContext;<br />import javax.servlet.ServletException;<br />import javax.servlet.http.HttpServlet;<br />import javax.servlet.http.HttpServletRequest;<br />import javax.servlet.http.HttpServletResponse;<br />import javax.sql.DataSource;<br /><br />import com.as400samplecode.util.Country;<br />import com.google.gson.Gson;<br />import com.google.gson.JsonObject;<br /><br />public class CountrySearch extends HttpServlet {<br /> <br /> private static final long serialVersionUID = 1L;<br /> <br /> public CountrySearch() {<br /> super();<br /> }<br /><br /> protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<br /> doPost(request,response);<br /> }<br /><br /> protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<br /><br /> PrintWriter out = response.getWriter();<br /> <br /> //check of query data is sent<br /> String queryString = request.getParameter("queryString");<br /> if(queryString == null){<br /> queryString = "";<br /> }<br /> <br /> //get list of countries and prepare JSON array to send back<br /> ArrayList<Country> countryList = new ArrayList<Country>();<br /> Connection conn = null; <br /> PreparedStatement stmt = null; <br /> String sql = null;<br /> <br /> try { <br /> Context ctx = (Context) new InitialContext().lookup("java:comp/env");<br /> conn = ((DataSource) ctx.lookup("jdbc/mysql")).getConnection(); <br /><br /> sql = "Select * from country where code <> 'CIV' "; <br /> if(!queryString.trim().equals("")){<br /> sql += "and lcase(name) like ?";<br /> }<br /> <br /> stmt = conn.prepareStatement(sql);<br /> if(!queryString.trim().equals("")){<br /> stmt.setString(1, "%" + queryString.trim().toLowerCase() + "%" );<br /> }<br /> <br /> ResultSet rs = stmt.executeQuery(); <br /> while(rs.next()){ <br /> <br /> Country country = new Country();<br /> country.setCode(rs.getString("code").trim());<br /> country.setName(rs.getString("name").trim());<br /> countryList.add(country);<br /> <br /> } <br /> rs.close(); <br /> <br /> stmt.close(); <br /> stmt = null; <br /> conn.close(); <br /> conn = null; <br /> <br /> } <br /> catch(Exception e){<br /> e.printStackTrace();<br /> } <br /><br /> finally { <br /> <br /> if (stmt != null) { <br /> try { <br /> stmt.close(); <br /> } catch (SQLException sqlex) { <br /> // ignore -- as we can't do anything about it here <br /> } <br /><br /> stmt = null; <br /> } <br /><br /> if (conn != null) { <br /> try { <br /> conn.close(); <br /> } catch (SQLException sqlex) { <br /> // ignore -- as we can't do anything about it here <br /> } <br /><br /> conn = null; <br /> } <br /> } <br /> <br /> Gson gson = new Gson();<br /> JsonObject myObj = new JsonObject();<br /> myObj.add("countryList", gson.toJsonTree(countryList));<br /> myObj.addProperty("success", true);<br /> out.println(myObj.toString());<br /><br /> }<br /> <br />}<br /></pre><br /><h4>Interface file for the App Delegate - MySearchBarAppDelegate.h</h4><pre class="brush: oc">#import <UIKit/UIKit.h><br /><br />@class MySearchBarViewController;<br /><br />@interface MySearchBarAppDelegate : UIResponder <UIApplicationDelegate><br /><br />@property (strong, nonatomic) UIWindow *window;<br /><br />@property (strong, nonatomic) MySearchBarViewController *viewController;<br /><br />@end<br /></pre><br /><h4>Implementation file for the App Delegate - MySearchBarAppDelegate.m</h4><pre class="brush: oc">#import "MySearchBarAppDelegate.h"<br />#import "MySearchBarViewController.h"<br /><br />@implementation MySearchBarAppDelegate<br /><br />- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions<br />{<br /> self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];<br /> self.viewController = [[MySearchBarViewController alloc]<br /> initWithNibName:@"MySearchBarViewController" bundle:nil];<br /> self.window.rootViewController = self.viewController;<br /> [self.window makeKeyAndVisible];<br /> return YES;<br />}<br /><br />@end<br /></pre><br /><h4>Interface file for the UISearchBar View Controller - MySearchBarViewController.h</h4><pre class="brush: oc">#import <UIKit/UIKit.h><br /><br />@interface MySearchBarViewController : UIViewController <UISearchBarDelegate,<br /> UITableViewDelegate,UITableViewDataSource><br /><br />@property (nonatomic, strong) UISearchBar *mySearchBar;<br />@property (nonatomic, strong) UITableView *myTableView;<br />@property (nonatomic, strong) NSMutableArray *countryList;<br /><br />@property (nonatomic, strong) NSString *queryString;<br /><br />@end<br /></pre><br /><h4>Implementation file for the UISearchBar View Controller - MySearchBarViewController.m</h4><pre class="brush: oc">#import "MySearchBarViewController.h"<br /><br />@interface MySearchBarViewController ()<br /><br />@end<br /><br />@implementation MySearchBarViewController<br /><br />@synthesize mySearchBar;<br />@synthesize myTableView;<br />@synthesize countryList;<br />@synthesize queryString;<br /><br />- (void)viewDidLoad<br />{<br /> [super viewDidLoad];<br /> <br /> //create a search bar and add to the top of the screen<br /> CGRect myFrame = CGRectMake(self.view.bounds.origin.x, self.view.bounds.origin.y,<br /> self.view.bounds.size.width, 44.0f);<br /> self.mySearchBar = [[UISearchBar alloc] initWithFrame:myFrame];<br /> //set the delegate to self so we can listen for events<br /> self.mySearchBar.delegate = self;<br /> //display the cancel button next to the search bar<br /> self.mySearchBar.showsCancelButton = YES;<br /> //add the search bar to the view<br /> [self.view addSubview:self.mySearchBar];<br /> <br /> //set the frame for the table view<br /> myFrame.origin.y += 44;<br /> myFrame.size.height = self.view.bounds.size.height - 44;<br /> self.myTableView = [[UITableView alloc] initWithFrame:myFrame<br /> style:UITableViewStylePlain];<br /> //set the table view delegate and the data source<br /> self.myTableView.delegate = self;<br /> self.myTableView.dataSource = self;<br /> //set table view resize attribute<br /> self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth |<br /> UIViewAutoresizingFlexibleHeight;<br /> //set background view and color<br /> self.myTableView.backgroundColor = [UIColor whiteColor];<br /> self.myTableView.backgroundView = nil;<br /> //add table view to the main view<br /> [self.view addSubview:self.myTableView];<br /> <br /> //execute the search without any query to display all countries<br /> [self handleSearch:self.mySearchBar];<br />}<br /><br />//search button was tapped<br />- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {<br /> [self handleSearch:searchBar];<br />}<br /><br />//user finished editing the search text<br />- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {<br /> [self handleSearch:searchBar];<br />}<br /><br />//do our search on the remote server using HTTP request<br />- (void)handleSearch:(UISearchBar *)searchBar {<br /> <br /> //check what was passed as the query String and get rid of the keyboard<br /> NSLog(@"User searched for %@", searchBar.text);<br /> self.queryString = searchBar.text;<br /> [searchBar resignFirstResponder];<br /> <br /> //setup the remote server URI<br /> NSString *hostServer = @"http://demo.mysamplecode.com/Servlets_JSP/";<br /> NSString *myUrlString = [NSString stringWithFormat:@"%@CountrySearch",hostServer];<br /> <br /> //pass the query String in the body of the HTTP post<br /> NSString *body;<br /> if(self.queryString){<br /> body = [NSString stringWithFormat:@"queryString=%@", self.queryString];<br /> }<br /> NSURL *myUrl = [NSURL URLWithString:myUrlString];<br /> <br /> //make the HTTP request<br /> NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:myUrl];<br /> [urlRequest setTimeoutInterval:60.0f];<br /> [urlRequest setHTTPMethod:@"POST"];<br /> [urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];<br /> <br /> NSOperationQueue *queue = [[NSOperationQueue alloc] init];<br /> [NSURLConnection<br /> sendAsynchronousRequest:urlRequest<br /> queue:queue<br /> completionHandler:^(NSURLResponse *response,<br /> NSData *data,<br /> NSError *error) {<br /> //we got something in reponse to our request lets go ahead and process this<br /> if ([data length] >0 && error == nil){<br /> [self parseResponse:data];<br /> }<br /> else if ([data length] == 0 && error == nil){<br /> NSLog(@"Empty Response, not sure why?");<br /> }<br /> else if (error != nil){<br /> NSLog(@"Not again, what is the error = %@", error);<br /> }<br /> }];<br /> <br />}<br /><br />//parse our JSON response from the server and load the NSMutableArray of countries<br />- (void) parseResponse:(NSData *) data {<br /> <br /> NSString *myData = [[NSString alloc] initWithData:data<br /> encoding:NSUTF8StringEncoding];<br /> NSLog(@"JSON data = %@", myData);<br /> NSError *error = nil;<br /> <br /> id jsonObject = [NSJSONSerialization<br /> JSONObjectWithData:data<br /> options:NSJSONReadingAllowFragments<br /> error:&error];<br /> if (jsonObject != nil && error == nil){<br /> NSLog(@"Successfully deserialized...");<br /> <br /> NSNumber *success = [jsonObject objectForKey:@"success"];<br /> if([success boolValue] == YES){<br /> <br /> self.countryList = [jsonObject objectForKey:@"countryList"];<br /> dispatch_async(dispatch_get_main_queue(), ^{<br /> [self.myTableView reloadData];<br /> });<br /> }<br /> else {<br /> [self.navigationController popToRootViewControllerAnimated:YES];<br /> }<br /> }<br /> <br />}<br /><br />//number of rows in a given section of a table view<br />- (NSInteger)tableView:(UITableView *)tableView<br /> numberOfRowsInSection:(NSInteger)section{<br /> <br /> NSInteger numberOfRows = 0;<br /> //get the count from the array<br /> if ([tableView isEqual:self.myTableView]){<br /> numberOfRows = self.countryList.count;<br /> }<br /> //if user searched for something and found nothing just add a row to display a message<br /> if(numberOfRows == 0 && [self.queryString length] > 0){<br /> numberOfRows = 1;<br /> }<br /> NSLog(@"Rows: %i", numberOfRows);<br /> return numberOfRows;<br />}<br /><br /><br />//asks the data source for a cell to insert in a particular location of the table view<br />- (UITableViewCell *) tableView:(UITableView *)tableView<br /> cellForRowAtIndexPath:(NSIndexPath *)indexPath{<br /> <br /> UITableViewCell *myCellView = nil;<br /> <br /> if ([tableView isEqual:self.myTableView]){<br /> <br /> static NSString *TableViewCellIdentifier = @"CountryCells";<br /> //create a reusable table-view cell object located by its identifier<br /> myCellView = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier];<br /> if (myCellView == nil){<br /> myCellView = [[UITableViewCell alloc]<br /> initWithStyle:UITableViewCellStyleValue1<br /> reuseIdentifier:TableViewCellIdentifier];<br /> }<br /> <br /> //if there are countries to display<br /> if(self.countryList.count > 0){<br /> NSDictionary *countryInfo = [self.countryList objectAtIndex:indexPath.row];<br /> NSLog(@"Country Info = %@",countryInfo);<br /> <br /> NSString *countryCode = [countryInfo valueForKey:@"code"];<br /> NSString *countryName = [countryInfo valueForKey:@"name"];<br /> myCellView.textLabel.text = [NSString stringWithFormat:@"%@",countryName];<br /> myCellView.detailTextLabel.text = countryCode;<br /> }<br /> //display message to user<br /> else {<br /> myCellView.textLabel.text = @"No Results found, try again!";<br /> myCellView.detailTextLabel.text = @"";<br /> }<br /> <br /> //set the table view cell style<br /> [myCellView setSelectionStyle:UITableViewCellSelectionStyleNone];<br /> <br /> }<br /> return myCellView;<br />}<br /><br />//user tapped on the cancel button<br />- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {<br /> NSLog(@"User canceled search");<br /> [searchBar resignFirstResponder];<br />}<br /><br /><br />- (void)didReceiveMemoryWarning<br />{<br /> [super didReceiveMemoryWarning];<br /> // Dispose of any resources that can be recreated.<br />}<br /><br />@end<br /></pre><h4>Reference</h4><ul><li><a href="http://developer.apple.com/library/ios/#documentation/uikit/reference/UISearchBar_Class/Reference/Reference.html">iOS UISearchBar Class</a></li></ul><br />BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-58168661319627527122013-07-08T23:32:00.000-04:002019-03-06T00:38:53.149-05:00Android JSON stream data parsing example using Gson<table><tbody><tr><td valign="top">If the request to the Web service is a simple JSON object, then you can convert the HTTP response to a String object and from there convert it to a Java Object using the Google JSON parser. But sometimes you might come across a huge data set that is being sent from the back-end server and you have to parse that information to either display it or save it to the Sqlite database for later use resulting in Java out of memory heap issues if you take the first approach.<br /><br />Well in a situation like that the best solution is to implement a stream parser with the help of <b>Gson JsonReader and JsonWriter classes</b>. These classes operate on a JSON document as a sequence of tokens that are traversed in depth-first order. Because the streams operate on one token at a time, they impose minimal memory overhead. Here is example that implements both these classes and displays a list of countries sent to the mobile app from a MySql database using a Java Servlet. </td><td><a href="https://3.bp.blogspot.com/-PPrUA_pcNyI/Udtx6v7MlvI/AAAAAAAADZA/6X2Qu-FcHtA/s1600/Android+JSON+stream+data+parsing+example+using+Gson.png" imageanchor="1"><img alt="Android JSON stream data parsing example using Gson" border="0" src="https://3.bp.blogspot.com/-PPrUA_pcNyI/Udtx6v7MlvI/AAAAAAAADZA/6X2Qu-FcHtA/s320/Android+JSON+stream+data+parsing+example+using+Gson.png" /></a></td></tr></tbody></table><h4>Sample JSON data returned from the Java Servlet</h4><pre class="brush: plain">{"countryList":[{"code":"ABW","name":"Aruba","continent":"North<br />America"},{"code":"AFG","name":"Afghanistan","continent":"Asia"},{"code":"AGO","name":"<br />Angola","continent":"Africa"},{"code":"AIA","name":"Anguilla","continent":"North<br />America"},{"code":"ALB","name":"Albania","continent":"Europe"},{"code":"AND","name":"<br />Andorra","continent":"Europe"},{"code":"ANT","name":"Netherlands<br />Antilles","continent":"North America"},{"code":"ARE","name":"United Arab<br />Emirates","continent":"Asia"},{"code":"ARG","name":"Argentina","continent":"South<br />America"},{"code":"ARM","name":"Armenia","continent":"Asia"},{"code":"ASM","name":"<br />American Samoa","continent":"Oceania"},{"code":"ATA","name":"Antarctica","continent":"Antarctica"},<br />{"code":"ATF","name":"French Southern territories","continent":"Antarctica"},{"code":"ATG","name":"Antigua and<br />Barbuda","continent":"North America"},{"code":"AUS","name":"Australia1","continent":"Oceania"},<br />...<br />...<br /></pre><br /><h4>Source for Java Servlet using JsonWriter class - CountryJSONData.java</h4><pre class="brush: java">package com.as400samplecode;<br /><br />import java.io.IOException;<br />import java.io.PrintWriter;<br />import java.sql.Connection;<br />import java.sql.PreparedStatement;<br />import java.sql.ResultSet;<br />import java.sql.SQLException;<br /><br />import javax.naming.Context;<br />import javax.naming.InitialContext;<br />import javax.servlet.ServletException;<br />import javax.servlet.http.HttpServlet;<br />import javax.servlet.http.HttpServletRequest;<br />import javax.servlet.http.HttpServletResponse;<br />import javax.sql.DataSource;<br /><br />import com.as400samplecode.util.Country;<br />import com.google.gson.Gson;<br />import com.google.gson.stream.JsonWriter;<br /><br />public class CountryJSONData extends HttpServlet {<br /> <br /> private static final long serialVersionUID = 1L;<br /> <br /> public CountryJSONData() {<br /> super();<br /> }<br /><br /> protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<br /> doPost(request,response);<br /> }<br /><br /> protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<br /><br /> PrintWriter out = response.getWriter();<br /> <br /> <br /> Connection conn = null; <br /> PreparedStatement stmt = null; <br /> String sql = null;<br /> <br /> try { <br /> Context ctx = (Context) new InitialContext().lookup("java:comp/env");<br /> conn = ((DataSource) ctx.lookup("jdbc/mysql")).getConnection(); <br /><br /> Gson gson = new Gson();<br /> JsonWriter jsonWriter = new JsonWriter(out);<br /> jsonWriter.beginObject();<br /> <br /> sql = "Select * from country where code <> 'CIV'"; <br /> stmt = conn.prepareStatement(sql);<br /> ResultSet rs = stmt.executeQuery(); <br /> <br /> jsonWriter.name("countryList");<br /> jsonWriter.beginArray();<br /> while(rs.next()){ <br /> <br /> Country country = new Country();<br /> country.setCode(rs.getString("code").trim());<br /> country.setName(rs.getString("name").trim());<br /> country.setContinent(rs.getString("continent").trim());<br /> gson.toJson(country, Country.class, jsonWriter);<br /> <br /> } <br /> jsonWriter.endArray();<br /> <br /> rs.close(); <br /> stmt.close(); <br /> stmt = null; <br /> <br /> conn.close(); <br /> conn = null; <br /> <br /> jsonWriter.name("success").value(true);<br /> jsonWriter.endObject();<br /> jsonWriter.close();<br /><br /> } <br /> catch(Exception e){<br /> e.printStackTrace();<br /> } <br /><br /> finally { <br /> <br /> if (stmt != null) { <br /> try { <br /> stmt.close(); <br /> } catch (SQLException sqlex) { <br /> // ignore -- as we can't do anything about it here <br /> } <br /><br /> stmt = null; <br /> } <br /><br /> if (conn != null) { <br /> try { <br /> conn.close(); <br /> } catch (SQLException sqlex) { <br /> // ignore -- as we can't do anything about it here <br /> } <br /><br /> conn = null; <br /> } <br /> } <br /><br /> }<br /> <br />}<br /></pre><br /><h4>Source for Country Object - Country.java</h4><pre class="brush: java">package com.as400samplecode;<br /><br />public class Country {<br /> <br /> String code = null;<br /> String name = null;<br /> String continent = null;<br /> String region = null;<br /> Double lifeExpectancy = null;<br /> Double gnp = null;<br /> <br /> public String getCode() {<br /> return code;<br /> }<br /> public void setCode(String code) {<br /> this.code = code;<br /> }<br /> public String getName() {<br /> return name;<br /> }<br /> public void setName(String name) {<br /> this.name = name;<br /> }<br /> public String getContinent() {<br /> return continent;<br /> }<br /> public void setContinent(String continent) {<br /> this.continent = continent;<br /> }<br /> public String getRegion() {<br /> return region;<br /> }<br /> public void setRegion(String region) {<br /> this.region = region;<br /> }<br /> public Double getLifeExpectancy() {<br /> return lifeExpectancy;<br /> }<br /> public void setLifeExpectancy(Double lifeExpectancy) {<br /> this.lifeExpectancy = lifeExpectancy;<br /> }<br /> public Double getGnp() {<br /> return gnp;<br /> }<br /> public void setGnp(Double gnp) {<br /> this.gnp = gnp;<br /> }<br /><br /> <br />} <br /></pre><br /><h4>Layout for the main activity - activity_main.xml</h4><pre class="brush: xml"><?xml version="1.0" encoding="UTF-8"?><br /><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"<br /> xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"<br /> android:layout_height="match_parent" tools:context=".MainActivity"><br /><br /> <ListView android:id="@+id/countrylistView"<br /> android:layout_width="match_parent" android:layout_height="wrap_content"<br /> android:layout_alignParentLeft="true" android:layout_alignParentTop="true" /><br /><br /></RelativeLayout><br /></pre><br /><h4>Custom layout for ListView row - country_row.xml</h4><pre class="brush: xml"><?xml version="1.0" encoding="utf-8"?><br /><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"<br /> android:layout_width="fill_parent"<br /> android:layout_height="wrap_content"<br /> android:orientation="vertical"<br /> android:padding="6dip" ><br /> <br /> <TextView<br /> android:id="@+id/textView1"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:layout_alignParentLeft="true"<br /> android:layout_alignParentTop="true"<br /> android:text="Code: "<br /> android:textAppearance="?android:attr/textAppearanceMedium" /><br /> <br /> <TextView<br /> android:id="@+id/textView2"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:layout_alignLeft="@+id/textView1"<br /> android:layout_below="@+id/textView1"<br /> android:text="Name: "<br /> android:textAppearance="?android:attr/textAppearanceMedium" /><br /> <br /> <TextView<br /> android:id="@+id/textView3"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:layout_alignLeft="@+id/textView2"<br /> android:layout_below="@+id/textView2"<br /> android:text="Continent: "<br /> android:textAppearance="?android:attr/textAppearanceMedium" /><br /> <br /> <TextView<br /> android:id="@+id/continent"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:layout_alignBaseline="@+id/textView3"<br /> android:layout_alignBottom="@+id/textView3"<br /> android:layout_toRightOf="@+id/textView3"<br /> android:text="TextView" /><br /> <br /> <TextView<br /> android:id="@+id/name"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:layout_above="@+id/textView3"<br /> android:layout_toRightOf="@+id/textView3"<br /> android:text="TextView" /><br /> <br /> <TextView<br /> android:id="@+id/code"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:layout_above="@+id/textView2"<br /> android:layout_alignLeft="@+id/name"<br /> android:text="TextView" /><br /> <br /></RelativeLayout><br /></pre><br /><h4>Application mainfest - AndroidManifest.xml</h4><pre class="brush: xml"><?xml version="1.0" encoding="utf-8"?><br /><manifest xmlns:android="http://schemas.android.com/apk/res/android"<br /> package="com.as400samplecode"<br /> android:versionCode="1"<br /> android:versionName="1.0" ><br /><br /> <uses-sdk<br /> android:minSdkVersion="15"<br /> android:targetSdkVersion="16" /><br /><br /> <uses-permission android:name="android.permission.INTERNET" /><br /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><br /> <br /> <application<br /> android:allowBackup="true"<br /> android:icon="@drawable/ic_launcher"<br /> android:label="@string/app_name"<br /> android:theme="@style/AppTheme" ><br /> <activity<br /> android:name="com.as400samplecode.MainActivity"<br /> android:label="@string/app_name" ><br /> <intent-filter><br /> <action android:name="android.intent.action.MAIN" /><br /><br /> <category android:name="android.intent.category.LAUNCHER" /><br /> </intent-filter><br /> </activity><br /> </application><br /><br /></manifest><br /></pre><br /><h4>Source for the main activity using JsonReader class - MainActivity.java</h4><pre class="brush: java">package com.as400samplecode;<br /><br />import java.io.IOException;<br />import java.io.InputStreamReader;<br />import java.util.ArrayList;<br /><br />import org.apache.http.HttpResponse;<br />import org.apache.http.HttpStatus;<br />import org.apache.http.StatusLine;<br />import org.apache.http.client.HttpClient;<br />import org.apache.http.client.methods.HttpPost;<br />import org.apache.http.conn.params.ConnManagerParams;<br />import org.apache.http.impl.client.DefaultHttpClient;<br />import org.apache.http.params.HttpConnectionParams;<br />import org.apache.http.params.HttpParams;<br /><br />import com.google.gson.Gson;<br />import com.google.gson.stream.JsonReader;<br /><br />import android.os.AsyncTask;<br />import android.os.Bundle;<br />import android.app.Activity;<br />import android.content.Context;<br />import android.util.Log;<br />import android.view.LayoutInflater;<br />import android.view.Menu;<br />import android.view.View;<br />import android.view.ViewGroup;<br />import android.widget.ArrayAdapter;<br />import android.widget.ListView;<br />import android.widget.TextView;<br /><br />public class MainActivity extends Activity {<br /><br /> private static final String LOG_TAG = "JSONStreamReader";<br /> private ArrayList<Country> countryList = new ArrayList<Country>();<br /> private boolean success = false;<br /> private MyCustomAdapter dataAdapter;<br /> <br /> @Override<br /> protected void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> setContentView(R.layout.activity_main);<br /><br /> //create an ArrayAdaptar from the String Array<br /> dataAdapter = new MyCustomAdapter(this,<br /> R.layout.country_row, countryList);<br /> ListView listView = (ListView) findViewById(R.id.countrylistView);<br /> // Assign adapter to ListView<br /> listView.setAdapter(dataAdapter);<br /><br /> //URI to get the JSON stream data array of countries<br /> String url = "http://demo.mysamplecode.com/Servlets_JSP/CountryJSONData";<br /> new MyAsyncTask().execute(url);<br /><br /> }<br /><br /> private void displayCountries(){<br /> //if the request was successful then notify the adapter to display the data<br /> if(success){<br /> dataAdapter.notifyDataSetChanged();<br /> }<br /> }<br /><br /> @Override<br /> public boolean onCreateOptionsMenu(Menu menu) {<br /> // Inflate the menu; this adds items to the action bar if it is present.<br /> getMenuInflater().inflate(R.menu.activity_main, menu);<br /> return true;<br /> }<br /><br /> //custom array adapter to display our custom row layout for the listview<br /> private class MyCustomAdapter extends ArrayAdapter<Country> {<br /><br /> public MyCustomAdapter(Context context, int textViewResourceId, <br /> ArrayList<Country> countryList) {<br /> super(context, textViewResourceId, countryList);<br /> }<br /><br /> private class ViewHolder {<br /> TextView code;<br /> TextView name;<br /> TextView continent;<br /> }<br /><br /> @Override<br /> public View getView(int position, View convertView, ViewGroup parent) {<br /><br /> ViewHolder holder = null;<br /> if (convertView == null) {<br /><br /> LayoutInflater vi = (LayoutInflater)getSystemService(<br /> Context.LAYOUT_INFLATER_SERVICE);<br /> convertView = vi.inflate(R.layout.country_row, null);<br /><br /> holder = new ViewHolder();<br /> holder.code = (TextView) convertView.findViewById(R.id.code);<br /> holder.name = (TextView) convertView.findViewById(R.id.name);<br /> holder.continent = (TextView) convertView.findViewById(R.id.continent);<br /> convertView.setTag(holder);<br /><br /> } <br /> else {<br /> holder = (ViewHolder) convertView.getTag();<br /> }<br /><br /> Country country = countryList.get(position);<br /> holder.code.setText(country.getCode());<br /> holder.name.setText(country.getName());<br /> holder.continent.setText(country.getContinent());<br /><br /> return convertView;<br /><br /> }<br /><br /><br /><br /> }<br /><br /> //asynchronous task to get our JSON data with holding up the main thread<br /> private class MyAsyncTask extends AsyncTask<String, Void, Void> {<br /><br /> private static final int REGISTRATION_TIMEOUT = 3 * 1000;<br /> private static final int WAIT_TIMEOUT = 30 * 1000;<br /> private final HttpClient httpclient = new DefaultHttpClient();<br /><br /> final HttpParams params = httpclient.getParams();<br /> private boolean error = false;<br /><br /> protected Void doInBackground(String... urls) {<br /><br /> String URL = null;<br /><br /> try {<br /><br /> //URL passed to the AsyncTask <br /> URL = urls[0];<br /> HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);<br /> HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);<br /> ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);<br /><br /><br /> HttpPost httpPost = new HttpPost(URL);<br /><br /> //Response from the Http Request<br /> HttpResponse response = httpclient.execute(httpPost);<br /><br /> //Check the Http Request for success<br /> StatusLine statusLine = response.getStatusLine();<br /> if(statusLine.getStatusCode() == HttpStatus.SC_OK){<br /> <br /> Gson gson = new Gson();<br /> //create a new JSON reader from the response input stream <br /> JsonReader jsonReader = new JsonReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));<br /> //begin parsing<br /> jsonReader.beginObject();<br /> //stay in loop as long as there are more data elements<br /> while (jsonReader.hasNext()) {<br /> //get the element name<br /> String name = jsonReader.nextName();<br /> <br /> if (name.equals("success")) {<br /> success = jsonReader.nextBoolean();<br /> }<br /> //if the element name is the list of countries then start the array<br /> else if(name.equals("countryList")){<br /> jsonReader.beginArray();<br /> while (jsonReader.hasNext()) {<br /> //parse every element and convert that to a country object<br /> Country country = gson.fromJson(jsonReader, Country.class);<br /> //add the country object to the list<br /> countryList.add(country);<br /> }<br /> jsonReader.endArray();<br /> }<br /> }<br /> //end reader and close the stream<br /> jsonReader.endObject();<br /> jsonReader.close();<br /><br /> }<br /> else{<br /> //Closes the connection.<br /> Log.w(LOG_TAG,statusLine.getReasonPhrase());<br /> response.getEntity().getContent().close();<br /> throw new IOException(statusLine.getReasonPhrase());<br /> }<br /><br /><br /> } catch (Exception e) {<br /> Log.w(LOG_TAG,e );<br /> error = true;<br /> cancel(true);<br /> }<br /><br /> return null;<br /><br /> }<br /><br /> protected void onCancelled() {<br /> Log.e(LOG_TAG,"Error occured during data download");<br /> }<br /><br /> protected void onPostExecute(Void unused) {<br /> if (error) {<br /> Log.e(LOG_TAG,"Data download ended abnormally!");<br /> } else {<br /> displayCountries();<br /> }<br /> }<br /><br /> }<br /><br />}<br /></pre><br /><h4>Reference</h4><ul><li><a href="https://sites.google.com/site/gson/streaming">Streaming access to JSON documents</a></li></ul>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-85542570178954078502013-06-21T20:52:00.000-04:002019-03-06T00:39:44.705-05:00Sencha Touch auto login exampleIf you are creating a native application using Sencha Touch then most likely your users may expect the app to stay logged in unless they manually take an action to logout as mobile devices are considered kind of personal and they have a lock screen of their own. In this example we take advantage of the local storage that is available to us to keep information about the user session as they login for the first time.<br /><br />We have sample Java servlet program that does the authentication and sends the session Id if the login was successful. The mobile application will throw the login screen to user for the first time. As they login an ajax request will be made to the backend server which will respond if the request was successful or not and if successful we store the session Id in the local storage. Now the next time user tries to open this app it will first check the local storage if there is any information about session Id and if available it will then take them directly into the home page otherwise just throw the login page.<br /><br /><br /><table><tbody><tr><td><a href="https://2.bp.blogspot.com/-AAbeMwHJgvY/UcTxFpLeOvI/AAAAAAAADYk/ULHRFE961_I/s1600/Sencha+Touch+auto+login+example.png" imageanchor="1"><img alt="Sencha Touch auto login example" border="0" height="230" src="https://2.bp.blogspot.com/-AAbeMwHJgvY/UcTxFpLeOvI/AAAAAAAADYk/ULHRFE961_I/s320/Sencha+Touch+auto+login+example.png" width="320" /></a></td><td><a href="https://1.bp.blogspot.com/-DxQhHaAsEFw/UcTxJAOrbSI/AAAAAAAADYs/Etv4Y6SoUkw/s1600/Sencha+Touch+auto+login+home+page.png" imageanchor="1"><img alt="" auto="" border="0" height="230" home="" login="" page="" sencha="" src="https://1.bp.blogspot.com/-DxQhHaAsEFw/UcTxJAOrbSI/AAAAAAAADYs/Etv4Y6SoUkw/s320/Sencha+Touch+auto+login+home+page.png" touch="" /></a></td></tr></tbody></table><h4>Application HTML page - autoLogin.jsp</h4><pre class="brush: js"><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><br /><html><br /><br /><head><br /><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><br /><meta name="robots" content="noindex,nofollow"/><br /><title>Programmers sample guide, help is on the way</title><br /><link rel="stylesheet" href="/sencha-touch/resources/css-debug/sencha-touch.css" type="text/css"><br /><script type="text/javascript" src="/sencha-touch/sencha-touch-all-debug.js"></script><br /><script type="text/javascript"><br /><br />Ext.Loader.setConfig({ <br /> enabled: true <br />});<br /><br />Ext.application({<br /> <br /> name: 'MyApp',<br /> appFolder: '/Sencha_Touch/app/autoLogin',<br /> <br /> requires: [<br /> 'MyApp.view.MainNavigation'<br /> ], <br /> <br /> views : ['MainNavigation'], <br /> controllers: ['AutoLoginDemo'],<br /> <br /> launch: function() {<br /> console.log('Application launch');<br /> Ext.create('Ext.Container', {<br /> fullscreen: true,<br /> layout: 'vbox',<br /> items: [{<br /> flex: 1,<br /> xtype: 'mainNavigation'<br /> }]<br /> });<br /> }<br /> <br />});<br /><br /></script><br /></head><br /><br /><body><br /></body><br /></html><br /></pre><br /><h4>Model for the session storage - SessionInfo.js</h4><pre class="brush: js">Ext.define('MyApp.model.SessionInfo', {<br /> extend: 'Ext.data.Model',<br /> config: {<br /> identifier: 'uuid',<br /> fields: [<br /> 'sessionId'<br /> ]<br /> }<br />});<br /></pre><br /><h4>Store for the session storage - SessionInfo.js</h4><pre class="brush: js">Ext.define('MyApp.store.SessionInfo', {<br /> extend: 'Ext.data.Store',<br /> <br /> config: {<br /> model: 'MyApp.model.SessionInfo',<br /> autoLoad: true,<br /> <br /> proxy: {<br /> type: 'localstorage',<br /> id : 'myApplicationKey'<br /> }<br /> }<br />});<br /></pre><br /><h4>Navigation view for our application - MainNavigation.js</h4><pre class="brush: js">Ext.define('MyApp.view.MainNavigation', {<br /> extend: 'Ext.navigation.View',<br /> alias : 'widget.mainNavigation',<br /> id: 'mainNavigation',<br /> <br /> requires: [<br /> 'MyApp.view.Home',<br /> 'MyApp.view.Login'<br /> ], <br /> <br /> config: {<br /> <br /> navigationBar: {<br /> ui: 'dark',<br /> items: [{<br /> xtype: 'button',<br /> id: 'logoutUser',<br /> text: 'Logout',<br /> align: 'right',<br /> hidden: true,<br /> hideAnimation: Ext.os.is.Android ? false : {<br /> type: 'fadeOut',<br /> duration: 200<br /> },<br /> showAnimation: Ext.os.is.Android ? false : {<br /> type: 'fadeIn',<br /> duration: 200<br /> }<br /> }]<br /> },<br /> <br /> items: [{<br /> title: 'Home',<br /> items: [{<br /> xtype: 'login',<br /> flex: 1<br /> },{<br /> xtype: 'homePage',<br /> flex: 1,<br /> hidden: true<br /> }]<br /> }]<br /> }<br /> <br /> <br />});<br /></pre><br /><h4>View for the login page - Login.js</h4><pre class="brush: js">Ext.define('MyApp.view.Login', {<br /> extend: 'Ext.form.Panel',<br /> alias : 'widget.login',<br /> <br /> config: {<br /> <br /> title: 'Home',<br /> height: 300,<br /> layout: {<br /> type: 'vbox',<br /> },<br /> defaults: {<br /> margin: '0 0 5 0'<br /> },<br /> items: [<br /> {<br /> xtype: 'fieldset',<br /> title: 'User Authentication',<br /> items: [<br /> {<br /> xtype: 'textfield',<br /> label: 'User Id',<br /> itemId: 'userId',<br /> name: 'userId',<br /> allowBlank: false,<br /> autoCapitalize: false,<br /> labelWidth: 100<br /> },<br /> {<br /> xtype: 'passwordfield',<br /> label: 'Password',<br /> itemId: 'password',<br /> name: 'password',<br /> allowBlank: false,<br /> labelWidth: 100<br /> }<br /> ]<br /> }, <br /> {<br /> xtype: 'button',<br /> itemId: 'loginButton',<br /> text: 'Login',<br /> ui: 'action'<br /> }<br /> ]<br /> }<br /> <br />});<br /></pre><br /><h4>View for the home page - Home.js</h4><pre class="brush: js">Ext.define('MyApp.view.Home', {<br /> extend: 'Ext.Panel',<br /> alias : 'widget.homePage',<br /> <br /> config: {<br /> <br /> title: 'Home',<br /> layout: {<br /> type: 'vbox',<br /> },<br /> defaults: {<br /> margin: '5 5 5 5'<br /> },<br /> <br /> items: [{<br /> xtype: 'panel',<br /> id: 'welcomePanel',<br /> html: 'Welcome',<br /> margin: '5 5 20 5'<br /> }]<br /> }<br /> <br />});<br /></pre><br /><h4>Finally the application controller - AutoLoginDemo.js</h4><pre class="brush: js">Ext.define('MyApp.controller.AutoLoginDemo', {<br /> extend : 'Ext.app.Controller',<br /><br /> sessionId: null,<br /> <br /> config: {<br /> profile: Ext.os.deviceType.toLowerCase(),<br /> stores : ['SessionInfo'],<br /> models : ['SessionInfo'],<br /> <br /> refs: {<br /> myNavigationView: 'mainNavigation',<br /> myLoginPanel: 'login'<br /> },<br /> <br /> control: {<br /> 'login button[itemId=loginButton]' : {<br /> tap : 'onUserAuthentication' <br /> },<br /> 'mainNavigation button[itemId=logoutUser]' : {<br /> tap : 'onUserLogout' <br /> }<br /> } <br /><br /> },<br /> <br /> launch: function() {<br /> console.log('Launch for controller');<br /> var sessionInfo = Ext.getStore('SessionInfo'); <br /> if(null!=sessionInfo.getAt(0)){<br /> this.successfulLogin(sessionInfo.getAt(0).get('sessionId'));<br /> }<br /> <br /> },<br /> <br /> onUserAuthentication: function(button) {<br /> var fieldset = button.up('panel').down('fieldset');<br /> var userId = fieldset.getComponent('userId');<br /> var password = fieldset.getComponent('password');<br /> if(userId.getValue() && password.getValue()){<br /> <br /> button.setText('Please wait ...');<br /> button.setDisabled(true);<br /> <br /> Ext.Ajax.request({<br /> url : '../Login',<br /> method:'POST', <br /> params : {<br /> userId: userId.getValue(),<br /> password: password.getValue()<br /> },<br /> scope : this,<br /> //method to call when the request is successful<br /> success : this.onLoginSuccess,<br /> //method to call when the request is a failure<br /> failure : this.onLoginFailure<br /> }); <br /> <br /> password.setValue('');<br /> <br /> }<br /> else {<br /> Ext.Msg.alert('', 'Please enter User Id and/or Password', Ext.emptyFn);<br /> }<br /> },<br /> <br /> onUserLogout: function(button) {<br /> <br /> this.sessionId = null;<br /> var sessionInfo = Ext.getStore('SessionInfo');<br /> sessionInfo.removeAll();<br /> sessionInfo.sync();<br /> <br /> var logoutButton = Ext.getCmp('logoutUser');<br /> logoutButton.setHidden(true);<br /> <br /> var navigationView = this.getMyNavigationView();<br /> var loginPanel = navigationView.down('login');<br /> var homePage = navigationView.down('homePage');<br /> loginPanel.show(true);<br /> homePage.hide(true);<br /> },<br /> <br /> onLoginFailure : function(err) {<br /> <br /> var panel = this.getMyLoginPanel();<br /> var button = panel.getComponent('loginButton');<br /> button.setText('Login');<br /> button.setDisabled(false);<br /> <br /> Ext.Msg.alert('', 'Error connecting to server, please try after some time', Ext.emptyFn);<br /> },<br /><br /> onLoginSuccess : function(response, opts) {<br /> <br /> var panel = this.getMyLoginPanel();<br /> var button = panel.getComponent('loginButton');<br /> button.setText('Login');<br /> button.setDisabled(false);<br /> <br /> response = Ext.decode(response.responseText);<br /> if(response.success){<br /> this.successfulLogin(response.sessionId);<br /> }<br /> else {<br /> Ext.Msg.alert('Login failed', response.message);<br /> }<br /> },<br /><br /> successfulLogin: function(sessionId){<br /> <br /> this.sessionId = sessionId;<br /> <br /> var sessionInfo = Ext.getStore('SessionInfo');<br /> sessionInfo.removeAll();<br /> sessionInfo.sync();<br /> var newRecord = new MyApp.model.SessionInfo({<br /> sessionId: this.sessionId <br /> });<br /> sessionInfo.add(newRecord);<br /> sessionInfo.sync();<br /> <br /> var navigationView = this.getMyNavigationView();<br /> var loginPanel = navigationView.down('login');<br /> var homePage = navigationView.down('homePage');<br /> var myHtml = "Welcome, <b>You are now logged in...</b>";<br /> Ext.getCmp('welcomePanel').setHtml(myHtml);<br /> loginPanel.hide(false);<br /> homePage.show(false);<br /> <br /> var logoutButton = Ext.getCmp('logoutUser');<br /> logoutButton.setHidden(false);<br /> <br /> },<br /> <br /> init: function() {<br /> console.log('Controller initialized');<br /> }<br /><br />});<br /></pre><br />BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-52225851985859953882013-06-17T20:56:00.000-04:002019-03-06T00:39:56.299-05:00Java SFTP Apache commons file download, upload and delete exampleSecure File Transfer Protocol or SFTP uses the SSH secure shell protocol to provides file access, file transfer, and file management functionalities over any reliable data stream. Apache Commons VFS provides a single API for accessing various different file systems and one of them is SFTP. Here are the examples for how to use the VFS to achieve file download, upload and delete on a remote system. Before you copy the sources please go ahead and download the following jar files and place them in your classpath. <br /><ul><li><b>commons-logging-api-1.1.3.jar</b></li><ul><li><a href="http://commons.apache.org/proper/commons-logging/download_logging.cgi">http://commons.apache.org/proper/commons-logging/download_logging.cgi</a></li></ul><li><b>commons-vfs2-2.0.jar</b></li><ul><li><a href="http://commons.apache.org/proper/commons-vfs/download_vfs.cgi">http://commons.apache.org/proper/commons-vfs/download_vfs.cgi</a></li></ul><li><b>jsch-0.1.50.jar</b></li><ul><li><a href="http://www.jcraft.com/jsch/">http://www.jcraft.com/jsch/</a></li></ul></ul><h4>Common java properties file for all the examples</h4><pre class="brush: plain">serverAddress=111.222.333.444<br />userId=myUserId<br />password=myPassword<br />remoteDirectory=products/ <br />localDirectory=import/<br /></pre><br /><h4>Upload file to remote server using SFTP</h4><pre class="brush: java">package com.as400samplecode;<br /><br />import java.io.File;<br />import java.io.FileInputStream;<br />import java.util.Properties;<br /><br />import org.apache.commons.vfs2.FileObject;<br />import org.apache.commons.vfs2.FileSystemOptions;<br />import org.apache.commons.vfs2.Selectors;<br />import org.apache.commons.vfs2.impl.StandardFileSystemManager;<br />import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;<br /><br />public class SendMyFiles {<br /><br /> static Properties props;<br /><br /> public static void main(String[] args) {<br /><br /> SendMyFiles sendMyFiles = new SendMyFiles();<br /> if (args.length < 1)<br /> {<br /> System.err.println("Usage: java " + sendMyFiles.getClass().getName()+<br /> " Properties_file File_To_FTP ");<br /> System.exit(1);<br /> }<br /><br /> String propertiesFile = args[0].trim();<br /> String fileToFTP = args[1].trim();<br /> sendMyFiles.startFTP(propertiesFile, fileToFTP);<br /><br /> }<br /><br /> public boolean startFTP(String propertiesFilename, String fileToFTP){<br /><br /> props = new Properties();<br /> StandardFileSystemManager manager = new StandardFileSystemManager();<br /><br /> try {<br /><br /> props.load(new FileInputStream("properties/" + propertiesFilename));<br /> String serverAddress = props.getProperty("serverAddress").trim();<br /> String userId = props.getProperty("userId").trim();<br /> String password = props.getProperty("password").trim();<br /> String remoteDirectory = props.getProperty("remoteDirectory").trim();<br /> String localDirectory = props.getProperty("localDirectory").trim();<br /><br /> //check if the file exists<br /> String filepath = localDirectory + fileToFTP;<br /> File file = new File(filepath);<br /> if (!file.exists())<br /> throw new RuntimeException("Error. Local file not found");<br /><br /> //Initializes the file manager<br /> manager.init();<br /> <br /> //Setup our SFTP configuration<br /> FileSystemOptions opts = new FileSystemOptions();<br /> SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(<br /> opts, "no");<br /> SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);<br /> SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);<br /> <br /> //Create the SFTP URI using the host name, userid, password, remote path and file name<br /> String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + <br /> remoteDirectory + fileToFTP;<br /> <br /> // Create local file object<br /> FileObject localFile = manager.resolveFile(file.getAbsolutePath());<br /><br /> // Create remote file object<br /> FileObject remoteFile = manager.resolveFile(sftpUri, opts);<br /><br /> // Copy local file to sftp server<br /> remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);<br /> System.out.println("File upload successful");<br /><br /> }<br /> catch (Exception ex) {<br /> ex.printStackTrace();<br /> return false;<br /> }<br /> finally {<br /> manager.close();<br /> }<br /><br /> return true;<br /> }<br /><br /> <br />}<br /></pre><br /><h4>Download file from remote server using SFTP</h4><pre class="brush: java">package com.as400samplecode;<br /><br />import java.io.File;<br />import java.io.FileInputStream;<br />import java.util.Properties;<br /><br />import org.apache.commons.vfs2.FileObject;<br />import org.apache.commons.vfs2.FileSystemOptions;<br />import org.apache.commons.vfs2.Selectors;<br />import org.apache.commons.vfs2.impl.StandardFileSystemManager;<br />import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;<br /><br />public class GetMyFiles {<br /><br /> static Properties props;<br /><br /> public static void main(String[] args) {<br /><br /> GetMyFiles getMyFiles = new GetMyFiles();<br /> if (args.length < 1)<br /> {<br /> System.err.println("Usage: java " + getMyFiles.getClass().getName()+<br /> " Properties_filename File_To_Download ");<br /> System.exit(1);<br /> }<br /><br /> String propertiesFilename = args[0].trim();<br /> String fileToDownload = args[1].trim();<br /> getMyFiles.startFTP(propertiesFilename, fileToDownload);<br /> <br /> }<br /><br /> public boolean startFTP(String propertiesFilename, String fileToDownload){<br /><br /> props = new Properties();<br /> StandardFileSystemManager manager = new StandardFileSystemManager();<br /><br /> try {<br /><br /> props.load(new FileInputStream("properties/" + propertiesFilename));<br /> String serverAddress = props.getProperty("serverAddress").trim();<br /> String userId = props.getProperty("userId").trim();<br /> String password = props.getProperty("password").trim();<br /> String remoteDirectory = props.getProperty("remoteDirectory").trim();<br /> String localDirectory = props.getProperty("localDirectory").trim();<br /><br /> <br /> //Initializes the file manager<br /> manager.init();<br /> <br /> //Setup our SFTP configuration<br /> FileSystemOptions opts = new FileSystemOptions();<br /> SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(<br /> opts, "no");<br /> SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);<br /> SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);<br /> <br /> //Create the SFTP URI using the host name, userid, password, remote path and file name<br /> String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + <br /> remoteDirectory + fileToDownload;<br /> <br /> // Create local file object<br /> String filepath = localDirectory + fileToDownload;<br /> File file = new File(filepath);<br /> FileObject localFile = manager.resolveFile(file.getAbsolutePath());<br /><br /> // Create remote file object<br /> FileObject remoteFile = manager.resolveFile(sftpUri, opts);<br /><br /> // Copy local file to sftp server<br /> localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);<br /> System.out.println("File download successful");<br /><br /> }<br /> catch (Exception ex) {<br /> ex.printStackTrace();<br /> return false;<br /> }<br /> finally {<br /> manager.close();<br /> }<br /><br /> return true;<br /> }<br /><br />}<br /></pre><br /><h4>Delete a file on remote server using SFTP</h4><pre class="brush: java">package com.as400samplecode;<br /><br />import java.io.FileInputStream;<br />import java.util.Properties;<br /><br />import org.apache.commons.vfs2.FileObject;<br />import org.apache.commons.vfs2.FileSystemOptions;<br />import org.apache.commons.vfs2.impl.StandardFileSystemManager;<br />import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;<br /><br />public class DeleteRemoteFile {<br /><br /> static Properties props;<br /><br /> public static void main(String[] args) {<br /><br /> DeleteRemoteFile getMyFiles = new DeleteRemoteFile();<br /> if (args.length < 1)<br /> {<br /> System.err.println("Usage: java " + getMyFiles.getClass().getName()+<br /> " Properties_filename File_To_Delete ");<br /> System.exit(1);<br /> }<br /><br /> String propertiesFilename = args[0].trim();<br /> String fileToDownload = args[1].trim();<br /> getMyFiles.startFTP(propertiesFilename, fileToDownload);<br /> <br /> }<br /><br /> public boolean startFTP(String propertiesFilename, String fileToDownload){<br /><br /> props = new Properties();<br /> StandardFileSystemManager manager = new StandardFileSystemManager();<br /><br /> try {<br /><br /> props.load(new FileInputStream("properties/" + propertiesFilename));<br /> String serverAddress = props.getProperty("serverAddress").trim();<br /> String userId = props.getProperty("userId").trim();<br /> String password = props.getProperty("password").trim();<br /> String remoteDirectory = props.getProperty("remoteDirectory").trim();<br /> <br /> <br /> //Initializes the file manager<br /> manager.init();<br /> <br /> //Setup our SFTP configuration<br /> FileSystemOptions opts = new FileSystemOptions();<br /> SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(<br /> opts, "no");<br /> SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);<br /> SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);<br /> <br /> //Create the SFTP URI using the host name, userid, password, remote path and file name<br /> String sftpUri = "sftp://" + userId + ":" + password + "@" + serverAddress + "/" + <br /> remoteDirectory + fileToDownload;<br /> <br /> //Create remote file object<br /> FileObject remoteFile = manager.resolveFile(sftpUri, opts);<br /><br /> //Check if the file exists<br /> if(remoteFile.exists()){<br /> remoteFile.delete();<br /> System.out.println("File delete successful");<br /> }<br /> <br /> }<br /> catch (Exception ex) {<br /> ex.printStackTrace();<br /> return false;<br /> }<br /> finally {<br /> manager.close();<br /> }<br /><br /> return true;<br /> }<br /><br />}<br /></pre>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-14128887037261927132013-06-14T22:26:00.000-04:002019-03-06T00:40:30.930-05:00iOS programmatically create a custom UITableViewCellIn our <a href="http://www.mysamplecode.com/2013/06/ios-custom-uitableviewcell-example.html">previous tutorial</a> we learned how to create a custom UITableViewCell using a xib file. My personal preference is to define it programmatically as it takes me less time to code. In this example we basically recreate the same custom table cell view which displays our country information and a button that can be used to further drill down to say a detail screen about that specific country.<br /><br /><table><tbody><tr><td><a href="https://3.bp.blogspot.com/-3Vdv-3J69ak/UbvMKYeXrzI/AAAAAAAADYM/ZLqX2_U0ZDM/s1600/iOS+programmatically+create+a+custom+UITableViewCell.png" imageanchor="1"><img alt="iOS programmatically create a custom UITableViewCell" border="0" src="https://3.bp.blogspot.com/-3Vdv-3J69ak/UbvMKYeXrzI/AAAAAAAADYM/ZLqX2_U0ZDM/s320/iOS+programmatically+create+a+custom+UITableViewCell.png" /></a></td><td><a href="https://1.bp.blogspot.com/-G96tClzDWl8/UbvMNw7gbAI/AAAAAAAADYU/KhoiaNMKCLQ/s1600/iOS+custom+UITableViewCell+xcode+project.png" imageanchor="1"><img alt="iOS custom UITableViewCell xcode project" border="0" src="https://1.bp.blogspot.com/-G96tClzDWl8/UbvMNw7gbAI/AAAAAAAADYU/KhoiaNMKCLQ/s320/iOS+custom+UITableViewCell+xcode+project.png" /></a></td></tr></tbody></table><br /><h4>Interface file for the country object - Country.h</h4><pre class="brush: oc">#import <Foundation/Foundation.h><br /><br />@interface Country : NSObject<br /><br />@property (nonatomic, strong) NSString *code;<br />@property (nonatomic, strong) NSString *name;<br />@property (nonatomic, strong) NSString *continent;<br />@property (nonatomic, strong) NSNumber *population;<br /><br />-(id)initWithCode:(NSString *)code_<br /> name:(NSString *)name_<br /> continent:(NSString *)continent_<br /> population:(NSNumber *)population_;<br /><br />@end<br /></pre><br /><h4>Implementation file for the country object - Country.m</h4><pre class="brush: oc">#import "Country.h"<br /><br />@implementation Country<br /><br />@synthesize code;<br />@synthesize name;<br />@synthesize continent;<br />@synthesize population;<br /><br /><br />-(id)initWithCode:(NSString *)code_<br /> name:(NSString *)name_<br /> continent:(NSString *)continent_<br /> population:(NSNumber *)population_<br />{<br /> self = [super init];<br /> if (self) {<br /> self.code = code_;<br /> self.name = name_;<br /> self.continent = continent_;<br /> self.population = population_;<br /> }<br /> return self;<br />}<br /><br />@end<br /></pre><br /><h4>Interface file for the app delegate - TableViewCustomCellAppDelegate.h</h4><pre class="brush: oc">#import <UIKit/UIKit.h><br /><br />@class TableViewCustomCellViewController;<br /><br />@interface TableViewCustomCellAppDelegate : UIResponder <UIApplicationDelegate><br /><br />@property (strong, nonatomic) UIWindow *window;<br /><br />@property (strong, nonatomic) TableViewCustomCellViewController *viewController;<br /><br />@end<br /></pre><br /><h4>Implementation file for the app delegate - TableViewCustomCellAppDelegate.m</h4><pre class="brush: oc">#import "TableViewCustomCellAppDelegate.h"<br /><br />#import "TableViewCustomCellViewController.h"<br /><br />@implementation TableViewCustomCellAppDelegate<br /><br />- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions<br />{<br /> //initialize the screen<br /> self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];<br /> <br /> //initialize your view controller<br /> self.viewController = [[TableViewCustomCellViewController alloc] initWithNibName:@"TableViewCustomCellViewController" bundle:nil];<br /> <br /> //make the new view controller as your root view controller<br /> self.window.rootViewController = self.viewController;<br /> //set background color and make your window visible<br /> self.window.backgroundColor = [UIColor whiteColor];<br /> [self.window makeKeyAndVisible];<br /> return YES;<br /><br />}<br /><br />@end</pre><h4>Interface file for the Table view - TableViewCustomCellViewController.h</h4><pre class="brush: oc">#import <UIKit/UIKit.h><br />#import "Country.h"<br /><br />@interface TableViewCustomCellViewController : UIViewController<br /> <UITableViewDelegate,UITableViewDataSource><br /><br />@property (nonatomic, strong) UITableView *myTableView;<br />@property (nonatomic, strong) NSMutableArray *countryList;<br /><br />@end<br /></pre><br /><h4>Implementation file for the Table view - TableViewCustomCellViewController.m</h4><pre class="brush: oc">//<br />// TableViewCustomCellViewController.m<br />// TableViewCustomCell<br />//<br />// Created by Developer on 6/10/13.<br />// Copyright (c) 2013 MySampleCode. All rights reserved.<br />//<br /><br />#import "TableViewCustomCellViewController.h"<br /><br />#define COUNTRY_TAG 1<br />#define CODE_TAG 2<br />#define CONTINENT_TAG 3<br />#define POPULATION_TAG 4<br /><br />@interface TableViewCustomCellViewController ()<br /><br />@end<br /><br />@implementation TableViewCustomCellViewController<br /><br />@synthesize myTableView;<br />@synthesize countryList;<br /><br />- (void)viewDidLoad<br />{<br /> [super viewDidLoad];<br /> self.view.backgroundColor = [UIColor whiteColor];<br /> <br /> //intialize our data to be displayed in the table view<br /> [self loadCountryData];<br /> <br /> //create the table view with a given style<br /> self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds<br /> style:UITableViewStyleGrouped];<br /> <br /> //set the table view delegate to the current so we can listen for events<br /> self.myTableView.delegate = self;<br /> //set the datasource for the table view to the current object<br /> self.myTableView.dataSource = self;<br /> <br /> //make sure our table view resizes correctly<br /> self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth |<br /> UIViewAutoresizingFlexibleHeight;<br /> <br /> //add the table view to the main view<br /> [self.view addSubview:self.myTableView];<br /> <br />}<br /><br />//Asks the delegate for a view object to display in the header of the specified<br />//section of the table view, display the continent name in the header view<br />- (UIView *) tableView:(UITableView *)tableView<br />viewForHeaderInSection:(NSInteger)section{<br /> <br /> UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,<br /> tableView.bounds.size.width, 30)];<br /> headerView.backgroundColor = [UIColor clearColor];<br /> <br /> if ([tableView isEqual:self.myTableView]){<br /> UILabel *result = [[UILabel alloc]<br /> initWithFrame:CGRectMake(12, 0,<br /> tableView.bounds.size.width, 30)];<br /> result.font = [UIFont boldSystemFontOfSize:16.0f];<br /> result.text = [NSString stringWithFormat:@"%@ :", @"List of Countries"];<br /> result.backgroundColor = [UIColor clearColor];<br /> [headerView addSubview:result];<br /> }<br /> return headerView;<br /> <br />}<br /><br />//asks the delegate for the height to use for the header of a particular section<br />- (CGFloat) tableView:(UITableView *)tableView<br />heightForHeaderInSection:(NSInteger)section{<br /> <br /> CGFloat result = 0.0f;<br /> if ([tableView isEqual:self.myTableView]){<br /> result = 35.0f;<br /> }<br /> return result;<br />}<br /><br /><br />//asks the data source to return the number of rows in a given section of a table view<br />//we are returning the number of countries in a given continent<br />- (NSInteger)tableView:(UITableView *)tableView<br /> numberOfRowsInSection:(NSInteger)section{<br /> <br /> NSLog(@"%@",@"Called number of Rows in a Section");<br /> NSInteger numberOfRows = 0;<br /> <br /> if ([tableView isEqual:self.myTableView]){<br /> numberOfRows = self.countryList.count;<br /> }<br /> return numberOfRows;<br />}<br /><br /><br />//asks the data source for a cell to insert in a particular location of the table view<br />- (UITableViewCell *) tableView:(UITableView *)tableView<br /> cellForRowAtIndexPath:(NSIndexPath *)indexPath{<br /> <br /> NSLog(@"%@",@"Render cell at a given Index Path Section and Row");<br /> UITableViewCell *myCellView = nil;<br /> UILabel *countryLabel, *codeLabel, *continentLabel, *populationLabel;<br /> UIButton *detailInfoButton;<br /><br /> if ([tableView isEqual:self.myTableView]){<br /> <br /> static NSString *TableViewCellIdentifier = @"CountryCell";<br /> <br /> //this method dequeues an existing cell if one is available or creates a new one<br /> //if no cell is available for reuse, this method returns nil<br /> myCellView = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier];<br /> if (myCellView == nil){<br /> myCellView = [[UITableViewCell alloc]<br /> initWithStyle:UITableViewCellStyleDefault<br /> reuseIdentifier:TableViewCellIdentifier];<br /> <br /> //create custom labels and button inside the cell view<br /> CGRect myFrame = CGRectMake(10.0, 0.0, 220, 25.0);<br /> countryLabel = [[UILabel alloc] initWithFrame:myFrame];<br /> countryLabel.tag = COUNTRY_TAG;<br /> countryLabel.font = [UIFont boldSystemFontOfSize:17.0];<br /> countryLabel.backgroundColor = [UIColor clearColor];<br /> [myCellView.contentView addSubview:countryLabel];<br /> <br /> detailInfoButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];<br /> detailInfoButton.frame = CGRectMake(200.0, 5.0, 90, 25.0);<br /> [detailInfoButton setTitle:@"Detail Info"<br /> forState:UIControlStateNormal];<br /> [detailInfoButton addTarget:self<br /> action:@selector(detailInfo:)<br /> forControlEvents:UIControlEventTouchUpInside];<br /> [myCellView.contentView addSubview:detailInfoButton];<br /><br /> myFrame.origin.y += 25;<br /> codeLabel = [[UILabel alloc] initWithFrame:myFrame];<br /> codeLabel.tag = CODE_TAG;<br /> codeLabel.font = [UIFont systemFontOfSize:17.0];<br /> codeLabel.backgroundColor = [UIColor clearColor];<br /> [myCellView.contentView addSubview:codeLabel];<br /> <br /> myFrame.origin.y += 25;<br /> continentLabel = [[UILabel alloc] initWithFrame:myFrame];<br /> continentLabel.tag = CONTINENT_TAG;<br /> continentLabel.font = [UIFont systemFontOfSize:17.0];<br /> continentLabel.backgroundColor = [UIColor clearColor];<br /> [myCellView.contentView addSubview:continentLabel];<br /> <br /> myFrame.origin.y += 25;<br /> populationLabel = [[UILabel alloc] initWithFrame:myFrame];<br /> populationLabel.tag = POPULATION_TAG;<br /> populationLabel.font = [UIFont systemFontOfSize:17.0];<br /> populationLabel.backgroundColor = [UIColor clearColor];<br /> [myCellView.contentView addSubview:populationLabel];<br /> <br /> }<br /> else {<br /> countryLabel = (UILabel *)[myCellView.contentView viewWithTag:COUNTRY_TAG];<br /> codeLabel = (UILabel *)[myCellView.contentView viewWithTag:CODE_TAG];<br /> continentLabel = (UILabel *)[myCellView.contentView viewWithTag:CONTINENT_TAG];<br /> populationLabel = (UILabel *)[myCellView.contentView viewWithTag:POPULATION_TAG];<br /> }<br /> <br /> Country *country = [[Country alloc] init];<br /> country = [self.countryList objectAtIndex:indexPath.row];<br /> <br /> //populate data from your country object to table view cell<br /> countryLabel.text = [NSString stringWithFormat:@"Name: %@", country.name];<br /> codeLabel.text = [NSString stringWithFormat:@"Code: %@", country.code];<br /> continentLabel.text = [NSString stringWithFormat:@"Continent: %@", country.continent];<br /> populationLabel.text = [NSString stringWithFormat:@"Population: %@", country.population];<br /> <br /> <br /> }<br /> return myCellView;<br />}<br /><br />- (void) detailInfo:(UIButton *)sender {<br /> <br /> UITableViewCell *ownerCell = (UITableViewCell *)[[sender superview] superview];<br /> NSIndexPath *indexPath = [self.myTableView indexPathForCell:ownerCell];<br /> <br /> Country *country = [[Country alloc] init];<br /> country = [self.countryList objectAtIndex:indexPath.row];<br /> NSLog(@"Country is %i %@", indexPath.row, country.name);<br /> <br />}<br /><br />- (CGFloat) tableView:(UITableView *)tableView<br />heightForRowAtIndexPath:(NSIndexPath *)indexPath{<br /> <br /> CGFloat result = 20.0f;<br /> if ([tableView isEqual:self.myTableView]){<br /> result = 100.0f;<br /> }<br /> return result;<br /> <br />}<br /><br /><br />//create mutable array to hold list of countries that will be displayed<br />- (void) loadCountryData {<br /> <br /> NSMutableArray *array = [[NSMutableArray alloc] init];<br /> self.countryList = array;<br /> <br /> Country *country = [[Country alloc] initWithCode:@"USA"<br /> name:@"United States"<br /> continent:@"North America"<br /> population:[[NSNumber alloc] initWithInt:989898]];<br /> [countryList addObject:country];<br /> country = [[Country alloc] initWithCode:@"CAN"<br /> name:@"Canada"<br /> continent:@"North America"<br /> population:[[NSNumber alloc] initWithInt:979797]];<br /> [countryList addObject:country];<br /> country = [[Country alloc] initWithCode:@"MXN"<br /> name:@"Mexico"<br /> continent:@"North America"<br /> population:[[NSNumber alloc] initWithInt:969696]];<br /> [countryList addObject:country];<br /> <br /> country = [[Country alloc] initWithCode:@"CHN"<br /> name:@"China"<br /> continent:@"Asia"<br /> population:[[NSNumber alloc] initWithInt:959595]];<br /> [countryList addObject:country];<br /> country = [[Country alloc] initWithCode:@"AFG"<br /> name:@"Afghanistan"<br /> continent:@"Asia"<br /> population:[[NSNumber alloc] initWithInt:939393]];<br /> [countryList addObject:country];<br /> <br />}<br /><br /><br />- (void)didReceiveMemoryWarning<br />{<br /> [super didReceiveMemoryWarning];<br /> // Dispose of any resources that can be recreated.<br />}<br /><br />@end<br /></pre>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-58979660654270460042013-06-12T23:50:00.000-04:002019-03-06T00:41:54.718-05:00iOS custom UITableViewCell example using xib file<table><tbody><tr><td><a href="https://2.bp.blogspot.com/-ORtS1xKijoo/Ubk06DlvfzI/AAAAAAAADX4/2N28phDVuEY/s1600/iOS+custom+UITableViewCell+example+using+xib+file.png" imageanchor="1"><img alt="iOS custom UITableViewCell example using xib file" border="0" height="400" src="https://2.bp.blogspot.com/-ORtS1xKijoo/Ubk06DlvfzI/AAAAAAAADX4/2N28phDVuEY/s400/iOS+custom+UITableViewCell+example+using+xib+file.png" width="225" /></a></td><td> </td><td valign="top">The UITableViewCell class defines the attributes and behavior of the cells that appear in UITableView objects. The iOS SDK comes with some predefined cell styles for your most common needs but what if you need a different layout for your table row data. Well you can easily extend the UITableViewCell class to create a new custom class and initialize that with your custom xib file.<br /><br />In this example we are going to display a list of countries from an array. To create our custom UITableViewCell first we need to create an empty xib file and then add Table View Cell from the list of objects. Next you can customize the cell view such as increase the dimensions, add components such as Labels, Buttons, etc. After that create a custom class extending the UITableViewCell class and then connect the labels from the xib file using IBOutlet.<br /><br />If you are interested in programmatically creating a custom cell for the Table view <b><a href="http://www.mysamplecode.com/2013/06/ios-programmatically-create-custom-cell.html">click here</a></b>.</td></tr></tbody></table><h4>Create a new Interface Builder file for the cell view</h4>Create a new File(Cmd+N), then from the category select User Interface and from right section select empty, then click next to continue. Choose iPhone as the device and click next. Give the file a name, for this example we chose CountryCell.xib and then click create. <br /><table><tbody><tr><td><a href="https://2.bp.blogspot.com/-2jufQkZHVQc/UbfukEYx6dI/AAAAAAAADWo/I2z3SdMZZhc/s1600/iOS+custom+UITableViewCell+user+interface+1.png" imageanchor="1"><img alt="iOS custom UITableViewCell user interface 1" border="0" height="212" src="https://2.bp.blogspot.com/-2jufQkZHVQc/UbfukEYx6dI/AAAAAAAADWo/I2z3SdMZZhc/s640/iOS+custom+UITableViewCell+user+interface+1.png" width="640" /></a></td></tr><tr><td><a href="https://2.bp.blogspot.com/-rCP6kaTeDG0/UbfunbUqqWI/AAAAAAAADWw/oHCm7-OpNRc/s1600/iOS+custom+UITableViewCell+user+interface+2.png" imageanchor="1"><img alt="iOS custom UITableViewCell user interface 2" border="0" height="280" src="https://2.bp.blogspot.com/-rCP6kaTeDG0/UbfunbUqqWI/AAAAAAAADWw/oHCm7-OpNRc/s400/iOS+custom+UITableViewCell+user+interface+2.png" width="400" /></a></td></tr></tbody></table><br />Next from the Object Library, select Table View Cell and drag it to the design area. Add a few labels and a button as shown in the picture below. We added four labels to display for country name, code, continent, population and a custom button to interact with the cell view when the user taps on it. Using the Attributes Inspector you can customize your labels such as make the country name as bold. <br /><table><tbody><tr><td><a href="https://4.bp.blogspot.com/-hNW1fpfAo_I/UbfxQ2lOPpI/AAAAAAAADXA/Q6DqruQg-qY/s1600/iOS+custom+UITableViewCell+Labels+and+button.png" imageanchor="1"><img alt="iOS custom UITableViewCell label and button" border="0" height="163" src="https://4.bp.blogspot.com/-hNW1fpfAo_I/UbfxQ2lOPpI/AAAAAAAADXA/Q6DqruQg-qY/s640/iOS+custom+UITableViewCell+Labels+and+button.png" width="640" /></a></td></tr></tbody></table><br />Next we have to create our custom CountryCell object extending the UITableViewCell class. Again create a new file(Cmd+N) and this time choose Cocoa Touch from the category and Objective-C class from the right section, click next to continue. Give the class name as CountryCell and subclass of UITableViewCell, click next choose folder and then create the files. This should now generate two files in your project folder named CountryCell.h and CountryCell.m <br /><table><tbody><tr><td><a href="https://3.bp.blogspot.com/-fYC8JNcoIdU/UbfzW1F_loI/AAAAAAAADXQ/_ub9tzK_4Os/s1600/iOS+custom+cell+using+subclass+as+UITableViewCell.png" imageanchor="1"><img alt="iOS custom cell using subclass as UITableViewCell" border="0" height="284" src="https://3.bp.blogspot.com/-fYC8JNcoIdU/UbfzW1F_loI/AAAAAAAADXQ/_ub9tzK_4Os/s640/iOS+custom+cell+using+subclass+as+UITableViewCell.png" width="640" /></a></td></tr></tbody></table><br />At this point open your xib file and the CountryCell interface file side by side in the editor and make the IBOutlet connections. You can select a label, then press on both Control+mouse and drag the mouse over to the interface file, it will prompt you to create a connection. I am not going to go into the details how to make these connections as they are same as if you were to create any other views while working with xib files. Do this for all your labels and the button. See images below for help <br /><table><tbody><tr><td><a href="https://3.bp.blogspot.com/-68e2PpqS9VE/UbhS4CK5dWI/AAAAAAAADXg/BoTX4VSLv9Q/s1600/iOS+custom+UITableViewCell+IBOutlet+make+connection.png" imageanchor="1"><img border="0" height="220" src="https://3.bp.blogspot.com/-68e2PpqS9VE/UbhS4CK5dWI/AAAAAAAADXg/BoTX4VSLv9Q/s640/iOS+custom+UITableViewCell+IBOutlet+make+connection.png" width="640" /></a></td></tr><tr><td><a href="https://3.bp.blogspot.com/-ei5kDfR6Eo0/UbhS9fLVJhI/AAAAAAAADXo/BkNVfKqK1Z0/s1600/iOS+custom+UITableViewCell+IBOutlet+connections.png" imageanchor="1"><img border="0" height="154" src="https://3.bp.blogspot.com/-ei5kDfR6Eo0/UbhS9fLVJhI/AAAAAAAADXo/BkNVfKqK1Z0/s640/iOS+custom+UITableViewCell+IBOutlet+connections.png" width="640" /></a></td></tr></tbody></table><br />We are almost done with the setup here. <b>Select your view in Objects list and then in the identity inspecter change the custom class to CountryCell. At this point your custom CountryCell class will look like this</b><br /><br /><h4>Interface file for the custom cell - CountryCell.h</h4><pre class="brush: oc">#import <UIKit/UIKit.h><br /><br />@interface CountryCell : UITableViewCell<br /><br />@property (weak, nonatomic) IBOutlet UILabel *countryLabel;<br />@property (weak, nonatomic) IBOutlet UILabel *codeLabel;<br />@property (weak, nonatomic) IBOutlet UILabel *continentLabel;<br />@property (weak, nonatomic) IBOutlet UILabel *populationLabel;<br />@property (weak, nonatomic) IBOutlet UIButton *detailInfoButton;<br /><br />@end<br /></pre><br /><h4>Implementation file for the custom cell - CountryCell.m</h4><pre class="brush: oc">#import "CountryCell.h"<br /><br />@implementation CountryCell<br /><br />- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier<br />{<br /> self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];<br /> if (self) {<br /> // Initialization code<br /> }<br /> return self;<br />}<br /><br />- (void)setSelected:(BOOL)selected animated:(BOOL)animated<br />{<br /> [super setSelected:selected animated:animated];<br /><br /> // Configure the view for the selected state<br />}<br /><br />@end<br /></pre><br /><h4>Interface file for the country object - Country.h</h4><pre class="brush: oc">#import <Foundation/Foundation.h><br /><br />@interface Country : NSObject<br /><br />@property (nonatomic, strong) NSString *code;<br />@property (nonatomic, strong) NSString *name;<br />@property (nonatomic, strong) NSString *continent;<br />@property (nonatomic, strong) NSNumber *population;<br /><br />-(id)initWithCode:(NSString *)code_<br /> name:(NSString *)name_<br /> continent:(NSString *)continent_<br /> population:(NSNumber *)population_;<br /><br />@end<br /></pre><br /><h4>Implementation file for the country object - Country.m</h4><pre class="brush: oc">#import "Country.h"<br /><br />@implementation Country<br /><br />@synthesize code;<br />@synthesize name;<br />@synthesize continent;<br />@synthesize population;<br /><br /><br />-(id)initWithCode:(NSString *)code_<br /> name:(NSString *)name_<br /> continent:(NSString *)continent_<br /> population:(NSNumber *)population_<br />{<br /> self = [super init];<br /> if (self) {<br /> self.code = code_;<br /> self.name = name_;<br /> self.continent = continent_;<br /> self.population = population_;<br /> }<br /> return self;<br />}<br /><br />@end<br /></pre><br /><h4>Interface file for the app delegate - TableViewCustomCellAppDelegate.h</h4><pre class="brush: oc">#import <UIKit/UIKit.h><br /><br />@class TableViewCustomCellViewController;<br /><br />@interface TableViewCustomCellAppDelegate : UIResponder <UIApplicationDelegate><br /><br />@property (strong, nonatomic) UIWindow *window;<br /><br />@property (strong, nonatomic) TableViewCustomCellViewController *viewController;<br /><br />@end<br /></pre><br /><h4>Implementation file for the app delegate - TableViewCustomCellAppDelegate.m</h4><pre class="brush: oc">#import "TableViewCustomCellAppDelegate.h"<br /><br />#import "TableViewCustomCellViewController.h"<br /><br />@implementation TableViewCustomCellAppDelegate<br /><br />- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions<br />{<br /> //initialize the screen<br /> self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];<br /> <br /> //initialize your view controller<br /> self.viewController = [[TableViewCustomCellViewController alloc] initWithNibName:@"TableViewCustomCellViewController" bundle:nil];<br /> <br /> //make the new view controller as your root view controller<br /> self.window.rootViewController = self.viewController;<br /> //set background color and make your window visible<br /> self.window.backgroundColor = [UIColor whiteColor];<br /> [self.window makeKeyAndVisible];<br /> return YES;<br /><br />}<br /><br />@end</pre><h4>Interface file for the Table view - TableViewCustomCellViewController.h</h4><pre class="brush: oc">#import <UIKit/UIKit.h><br />#import "Country.h"<br />#import "CountryCell.h"<br /><br />@interface TableViewCustomCellViewController : UIViewController<br /> <UITableViewDelegate,UITableViewDataSource><br /><br />@property (nonatomic, strong) UITableView *myTableView;<br />@property (nonatomic, strong) NSMutableArray *countryList;<br /><br />@end<br /></pre><br /><h4>Implementation file for the Table view - TableViewCustomCellViewController.m</h4><pre class="brush: oc">#import "TableViewCustomCellViewController.h"<br /><br />@interface TableViewCustomCellViewController ()<br /><br />@end<br /><br />@implementation TableViewCustomCellViewController<br /><br />@synthesize myTableView;<br />@synthesize countryList;<br /><br />- (void)viewDidLoad<br />{<br /> [super viewDidLoad];<br /> self.view.backgroundColor = [UIColor whiteColor];<br /> <br /> //intialize our data to be displayed in the table view<br /> [self loadCountryData];<br /> <br /> //create the table view with a given style<br /> self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds<br /> style:UITableViewStyleGrouped];<br /> <br /> //set the table view delegate to the current so we can listen for events<br /> self.myTableView.delegate = self;<br /> //set the datasource for the table view to the current object<br /> self.myTableView.dataSource = self;<br /> <br /> //make sure our table view resizes correctly<br /> self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth |<br /> UIViewAutoresizingFlexibleHeight;<br /> <br /> //add the table view to the main view<br /> [self.view addSubview:self.myTableView];<br /> <br />}<br /><br />//Asks the delegate for a view object to display in the header of the specified<br />//section of the table view, display the continent name in the header view<br />- (UIView *) tableView:(UITableView *)tableView<br />viewForHeaderInSection:(NSInteger)section{<br /> <br /> UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,<br /> tableView.bounds.size.width, 30)];<br /> headerView.backgroundColor = [UIColor clearColor];<br /> <br /> if ([tableView isEqual:self.myTableView]){<br /> UILabel *result = [[UILabel alloc]<br /> initWithFrame:CGRectMake(12, 0,<br /> tableView.bounds.size.width, 30)];<br /> result.font = [UIFont boldSystemFontOfSize:16.0f];<br /> result.text = [NSString stringWithFormat:@"%@ :", @"List of Countries"];<br /> result.backgroundColor = [UIColor clearColor];<br /> [headerView addSubview:result];<br /> }<br /> return headerView;<br /> <br />}<br /><br />//asks the delegate for the height to use for the header of a particular section<br />- (CGFloat) tableView:(UITableView *)tableView<br />heightForHeaderInSection:(NSInteger)section{<br /> <br /> CGFloat result = 0.0f;<br /> if ([tableView isEqual:self.myTableView]){<br /> result = 35.0f;<br /> }<br /> return result;<br />}<br /><br /><br />//asks the data source to return the number of rows in a given section of a table view<br />//we are returning the number of countries in a given continent<br />- (NSInteger)tableView:(UITableView *)tableView<br /> numberOfRowsInSection:(NSInteger)section{<br /> <br /> NSLog(@"%@",@"Called number of Rows in a Section");<br /> NSInteger numberOfRows = 0;<br /> <br /> if ([tableView isEqual:self.myTableView]){<br /> numberOfRows = self.countryList.count;<br /> }<br /> return numberOfRows;<br />}<br /><br /><br />//asks the data source for a cell to insert in a particular location of the table view<br />- (UITableViewCell *) tableView:(UITableView *)tableView<br /> cellForRowAtIndexPath:(NSIndexPath *)indexPath{<br /> <br /> NSLog(@"%@",@"Render cell at a given Index Path Section and Row");<br /> CountryCell *myCellView = nil;<br /> <br /> if ([tableView isEqual:self.myTableView]){<br /> <br /> static NSString *TableViewCellIdentifier = @"CountryCell";<br /> <br /> //this method dequeues an existing cell if one is available or creates a new one<br /> //if no cell is available for reuse, this method returns nil<br /> myCellView = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier];<br /> if (myCellView == nil){<br /> //initialize the cell view from the xib file<br /> NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"CountryCell"<br /> owner:self options:nil];<br /> myCellView = (CountryCell *)[nibs objectAtIndex:0];<br /> }<br /> <br /> Country *country = [[Country alloc] init];<br /> country = [self.countryList objectAtIndex:indexPath.row];<br /> <br /> //populate data from your country object to table view cell<br /> myCellView.countryLabel.text = [NSString stringWithFormat:@"Name: %@",<br /> country.name];<br /> myCellView.codeLabel.text = [NSString stringWithFormat:@"Code: %@",<br /> country.code];<br /> myCellView.continentLabel.text = [NSString stringWithFormat:@"Continent: %@",<br /> country.continent];<br /> myCellView.populationLabel.text = [NSString stringWithFormat:@"Population: %@",<br /> country.population];<br /> [myCellView.detailInfoButton addTarget:self action:@selector(detailInfo:)<br /> forControlEvents:UIControlEventTouchUpInside];<br /> <br /> }<br /> return myCellView;<br />}<br /><br />- (void) detailInfo:(UIButton *)sender {<br /> <br /> CountryCell *ownerCell = (CountryCell *)[[sender superview] superview];<br /> NSIndexPath *indexPath = [self.myTableView indexPathForCell:ownerCell];<br /> <br /> Country *country = [[Country alloc] init];<br /> country = [self.countryList objectAtIndex:indexPath.row];<br /> NSLog(@"Country is %i %@", indexPath.row, country.name);<br /> <br />}<br /><br />- (CGFloat) tableView:(UITableView *)tableView<br />heightForRowAtIndexPath:(NSIndexPath *)indexPath{<br /> <br /> CGFloat result = 20.0f;<br /> if ([tableView isEqual:self.myTableView]){<br /> result = 100.0f;<br /> }<br /> return result;<br /> <br />}<br /><br /><br />//create mutable array to hold list of countries that will be displayed<br />- (void) loadCountryData {<br /> <br /> NSMutableArray *array = [[NSMutableArray alloc] init];<br /> self.countryList = array;<br /> <br /> Country *country = [[Country alloc] initWithCode:@"USA"<br /> name:@"United States"<br /> continent:@"North America"<br /> population:[[NSNumber alloc] initWithInt:989898]];<br /> [countryList addObject:country];<br /> country = [[Country alloc] initWithCode:@"CAN"<br /> name:@"Canada"<br /> continent:@"North America"<br /> population:[[NSNumber alloc] initWithInt:979797]];<br /> [countryList addObject:country];<br /> country = [[Country alloc] initWithCode:@"MXN"<br /> name:@"Mexico"<br /> continent:@"North America"<br /> population:[[NSNumber alloc] initWithInt:969696]];<br /> [countryList addObject:country];<br /> <br /> country = [[Country alloc] initWithCode:@"CHN"<br /> name:@"China"<br /> continent:@"Asia"<br /> population:[[NSNumber alloc] initWithInt:959595]];<br /> [countryList addObject:country];<br /> country = [[Country alloc] initWithCode:@"AFG"<br /> name:@"Afghanistan"<br /> continent:@"Asia"<br /> population:[[NSNumber alloc] initWithInt:939393]];<br /> [countryList addObject:country];<br /> <br />}<br /><br /><br />- (void)didReceiveMemoryWarning<br />{<br /> [super didReceiveMemoryWarning];<br /> // Dispose of any resources that can be recreated.<br />}<br /><br />@end<br /></pre><br />BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-38179395423068786302013-06-09T19:11:00.000-04:002019-03-06T00:42:58.030-05:00iOS Core Data example - CRUD operations<b>Core Data</b> is powerful framework, standard within the iOS SDK that simplifies the interaction with the persistent data store in an object-oriented way and the programmer doesn't have to worry about the low level interaction with the underlying database, basically simplifies the crud operations that you generally deal with when using SQL with any relational database. In core data the most important object is the managed object context (MOC). The managed object context is our gateway to the database tables also know as the managed object model thru a persistent store coordinator.<br /><br /><table><tbody><tr><td><a href="https://3.bp.blogspot.com/-jYDPLJiVaqw/UbTBDmpGv3I/AAAAAAAADUw/V_FLaSfNAAc/s1600/iOS+Core+Data+example+-+Table+view.png" imageanchor="1"><img alt="iOS Core Data example - Table view" border="0" src="https://3.bp.blogspot.com/-jYDPLJiVaqw/UbTBDmpGv3I/AAAAAAAADUw/V_FLaSfNAAc/s320/iOS+Core+Data+example+-+Table+view.png" /></a></td><td><a href="https://2.bp.blogspot.com/-GGClfTmTz1Q/UbTBHqA5KJI/AAAAAAAADU4/rrNchc0jbYg/s1600/iOS+Core+Data+example+-+CRUD+operations.png" imageanchor="1"><img alt="iOS Core Data example - CRUD operations" border="0" src="https://2.bp.blogspot.com/-GGClfTmTz1Q/UbTBHqA5KJI/AAAAAAAADU4/rrNchc0jbYg/s320/iOS+Core+Data+example+-+CRUD+operations.png" /></a></td><td><a href="https://2.bp.blogspot.com/-zyDd-XsxgNA/UbTBMoEelDI/AAAAAAAADVA/yZC3c67rMm8/s1600/iOS+Core+Data+example+-+NSFetchedResultsController.png" imageanchor="1"><img alt="iOS Core Data example - NSFetchedResultsController" border="0" src="https://2.bp.blogspot.com/-zyDd-XsxgNA/UbTBMoEelDI/AAAAAAAADVA/yZC3c67rMm8/s320/iOS+Core+Data+example+-+NSFetchedResultsController.png" /></a></td></tr></tbody></table>Here are the most important terminology that one must know for the core data framework<br /><ul><li><b>Managed Object Model</b></li><ul><li>Model Representation of a database table in object-oriented way.</li></ul><li><b>Managed Object</b></li><ul><li>The one specific object inside a model. Kind of a single row in a given database table.</li></ul><li><b>Persistent Store Coordinator</b></li><ul><li>The bridge that is responsible for managing the connection between managed object context and actual data stores.</li></ul><li><b>Managed Object Context</b></li><ul><li>The gateway for your program logic to access the managed object model. This will help you add, delete, update and read records basically the managed objects from the persistant store.</li></ul></ul>In this example we will use core data to create a simple employee maintenance program. It starts of with a table view that will display all current employees using a NSFetchedResultsController which efficiently manages the results returned from a Core Data fetch request to provide data for a UITableView object. From that screen we can add an employee and also edit if we tap on a specific employee record. Please go thru the example and if there is any confusion I would suggest reading the apple documentation about Core Data Basics, <a href="http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/CoreData/Articles/cdBasics.html#//apple_ref/doc/uid/TP40001650-TP1"><b> here is the link</b></a> for that.<br /><br /><h4>Core data project setup</h4>When you create the project make sure that you check the box "Use Core Data" as shown in the picture <br /><table><tbody><tr><td><a href="https://3.bp.blogspot.com/-x4IWDpW3vbQ/UbTDkZOJAQI/AAAAAAAADVQ/G5Dh71PQ4O4/s1600/iOS+core+data+project.png" imageanchor="1"><img alt="iOS core data project" border="0" height="120" src="https://3.bp.blogspot.com/-x4IWDpW3vbQ/UbTDkZOJAQI/AAAAAAAADVQ/G5Dh71PQ4O4/s640/iOS+core+data+project.png" width="640" /></a></td></tr></tbody></table>After the project has been created, look for the file with the extension of xcdatamodeld in your application bundle in Xcode. Click on it to open the editor. Add an entity named Employee and some attributes such as name, age and position to the entity as shown in picture. An entity is same as your database table and attributes are the table columns.<br /><table><tbody><tr><td><a href="https://4.bp.blogspot.com/-wQ_HS7-ha2k/UbUFSyhZG6I/AAAAAAAADVg/0hdcIVqel3c/s1600/iOS+core+data+entity+and+attributes+.png" imageanchor="1"><img alt="iOS core data entity and attributes " border="0" height="116" src="https://4.bp.blogspot.com/-wQ_HS7-ha2k/UbUFSyhZG6I/AAAAAAAADVg/0hdcIVqel3c/s640/iOS+core+data+entity+and+attributes+.png" width="640" /></a></td></tr></tbody></table>You can also choose to click on the data model inspector after you click on a given attribute to changes some properties such as if the attribute is mandatory or optional.<br /><table><tbody><tr><td><a href="https://4.bp.blogspot.com/-oDc08cNOgK8/UbUF9LU9UNI/AAAAAAAADV4/aLQASNAcMF0/s1600/iOS+entity+attribute+data+model+view.png" imageanchor="1"><img alt="iOS entity attribute data model view" border="0" src="https://4.bp.blogspot.com/-oDc08cNOgK8/UbUF9LU9UNI/AAAAAAAADV4/aLQASNAcMF0/s320/iOS+entity+attribute+data+model+view.png" /></a></td></tr></tbody></table>Now its time to create the object representation of the Employee entity. Select the Employee entity and then press Cmd+N (File -> New -> File). Select Core Data in the iOS category and then select NSManagedObject subclass from right section and press Next. Choose where you would like to create the new files in your project and press Create. <br /><table><tbody><tr><td><a href="https://2.bp.blogspot.com/-B2DU-NV9s8g/UbUIOMI-P7I/AAAAAAAADWI/7lUafhtqrr4/s1600/iOS+create+NSManagedObject+subclass+from+entity.png" imageanchor="1"><img alt="iOS create NSManagedObject subclass from entity" border="0" height="196" src="https://2.bp.blogspot.com/-B2DU-NV9s8g/UbUIOMI-P7I/AAAAAAAADWI/7lUafhtqrr4/s640/iOS+create+NSManagedObject+subclass+from+entity.png" width="640" /></a></td></tr></tbody></table>That's all for the core data setup. Now you should have the two files named Employee.h and Employee.m <br /><h4>Interface file for Employee data - Employee.h</h4><pre class="brush: oc">#import <Foundation/Foundation.h><br />#import <CoreData/CoreData.h><br /><br /><br />@interface Employee : NSManagedObject<br /><br />@property (nonatomic, retain) NSString * name;<br />@property (nonatomic, retain) NSString * position;<br />@property (nonatomic, retain) NSNumber * age;<br /><br />@end<br /></pre><br /><h4>Implementation file for the Employee data - Employee.m</h4><pre class="brush: oc">#import "Employee.h"<br /><br />@implementation Employee<br /><br />@dynamic name;<br />@dynamic position;<br />@dynamic age;<br /><br />@end<br /></pre><br /><h4>Interface file for the App Delegate - EmployeeDataAppDelegate.h</h4><pre class="brush: oc">#import <UIKit/UIKit.h><br />#import "DisplayViewController.h"<br /><br />@interface EmployeeDataAppDelegate : UIResponder <UIApplicationDelegate><br /><br />@property (strong, nonatomic) UIWindow *window;<br /><br />@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;<br />@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;<br />@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;<br /><br />@property (strong, nonatomic) UINavigationController *navigationController;<br />@property (strong, nonatomic) DisplayViewController *displayViewController;<br /><br />- (void)saveContext;<br />- (NSURL *)applicationDocumentsDirectory;<br /><br />@end<br /></pre><br /><h4>Implementation file for the App Delegate - EmployeeDataAppDelegate.m</h4><pre class="brush: oc">#import "EmployeeDataAppDelegate.h"<br /><br />@implementation EmployeeDataAppDelegate<br /><br />@synthesize managedObjectContext = _managedObjectContext;<br />@synthesize managedObjectModel = _managedObjectModel;<br />@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;<br /><br />@synthesize navigationController;<br />@synthesize displayViewController;<br /><br />- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions<br />{<br /> self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];<br /> <br /> //create the navigation controller and add the controllers view to the window<br /> navigationController = [[UINavigationController alloc] init];<br /> [self.window addSubview:[self.navigationController view]];<br /> <br /> //check if the display viewcontroller eixsts, otherwise create it<br /> if(self.displayViewController == nil)<br /> {<br /> DisplayViewController *inputView = [[DisplayViewController alloc] init];<br /> self.displayViewController = inputView;<br /> }<br /> <br /> //push the display viewcontroller into the navigation view controller stack<br /> [self.navigationController pushViewController:self.displayViewController animated:YES];<br /> <br /> self.window.backgroundColor = [UIColor whiteColor];<br /> [self.window makeKeyAndVisible];<br /> return YES;<br /><br />}<br /><br /><br />- (void)saveContext<br />{<br /> NSError *error = nil;<br /> NSManagedObjectContext *managedObjectContext = self.managedObjectContext;<br /> if (managedObjectContext != nil) {<br /> if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {<br /> NSLog(@"Unresolved error %@, %@", error, [error userInfo]);<br /> abort();<br /> } <br /> }<br />}<br /><br />#pragma mark - Core Data stack<br /><br />// Returns the managed object context for the application.<br />// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.<br />- (NSManagedObjectContext *)managedObjectContext<br />{<br /> if (_managedObjectContext != nil) {<br /> return _managedObjectContext;<br /> }<br /> <br /> NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];<br /> if (coordinator != nil) {<br /> _managedObjectContext = [[NSManagedObjectContext alloc] init];<br /> [_managedObjectContext setPersistentStoreCoordinator:coordinator];<br /> }<br /> return _managedObjectContext;<br />}<br /><br />// Returns the managed object model for the application.<br />// If the model doesn't already exist, it is created from the application's model.<br />- (NSManagedObjectModel *)managedObjectModel<br />{<br /> if (_managedObjectModel != nil) {<br /> return _managedObjectModel;<br /> }<br /> NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"EmployeeData" withExtension:@"momd"];<br /> _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];<br /> return _managedObjectModel;<br />}<br /><br />// Returns the persistent store coordinator for the application.<br />// If the coordinator doesn't already exist, it is created and the application's store added to it.<br />- (NSPersistentStoreCoordinator *)persistentStoreCoordinator<br />{<br /> if (_persistentStoreCoordinator != nil) {<br /> return _persistentStoreCoordinator;<br /> }<br /> <br /> NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"EmployeeData.sqlite"];<br /> <br /> NSError *error = nil;<br /> _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];<br /> if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {<br /> NSLog(@"Unresolved error %@, %@", error, [error userInfo]);<br /> abort();<br /> } <br /> <br /> return _persistentStoreCoordinator;<br />}<br /><br />#pragma mark - Application's Documents directory<br /><br />// Returns the URL to the application's Documents directory.<br />- (NSURL *)applicationDocumentsDirectory<br />{<br /> return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];<br />}<br /><br />@end<br /></pre><br /><h4>Interface file for the Employee Display - DisplayViewController.h</h4><pre class="brush: oc">#import <UIKit/UIKit.h><br />#import "EditViewController.h"<br /><br />@interface DisplayViewController : UIViewController<br /> <UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate><br /><br />@property (weak, nonatomic) NSManagedObjectContext *managedObjectContext;<br /><br />@property (strong, nonatomic) EditViewController *editViewController;<br />@property (nonatomic, strong) UITableView *myTableView;<br />@property (nonatomic, strong) NSFetchedResultsController *employeeFRC;<br /><br />@end<br /></pre><br /><h4>Implementation file for the Employee Display - DisplayViewController.m</h4><pre class="brush: oc">#import "DisplayViewController.h"<br />#import "EmployeeDataAppDelegate.h"<br /><br />@interface DisplayViewController ()<br /><br />@end<br /><br />@implementation DisplayViewController<br /><br />@synthesize managedObjectContext;<br />@synthesize editViewController;<br />@synthesize myTableView;<br />@synthesize employeeFRC;<br /><br />- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil<br />{<br /> self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];<br /> if (self) {<br /> <br /> ////get the application delegate and its managed object context<br /> if(self.managedObjectContext == nil){<br /> EmployeeDataAppDelegate *myAppDelegate = (EmployeeDataAppDelegate *)<br /> [[UIApplication sharedApplication] delegate];<br /> self.managedObjectContext = myAppDelegate.managedObjectContext;<br /> }<br /> <br /> //Create the fetch request <br /> NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];<br /> <br /> //create reference to the Employee entity<br /> NSEntityDescription *entity = [NSEntityDescription entityForName:@"Employee"<br /> inManagedObjectContext:[self managedObjectContext]];<br /> <br /> //in what order you want your data to be fetched<br /> NSSortDescriptor *nameSort = [[NSSortDescriptor alloc] initWithKey:@"name"<br /> ascending:YES];<br /> NSArray *sortDescriptors = [[NSArray alloc] initWithObjects: nameSort, nil];<br /> fetchRequest.sortDescriptors = sortDescriptors;<br /> <br /> //tell the request that we want to read the contents of the Employee entity<br /> [fetchRequest setEntity:entity];<br /> <br /> //initialize a fetched results controller to efficiently manage the results<br /> //returned from a Core Data fetch request<br /> self.employeeFRC = [[NSFetchedResultsController alloc]<br /> initWithFetchRequest:fetchRequest<br /> managedObjectContext:[self managedObjectContext]<br /> sectionNameKeyPath:nil<br /> cacheName:nil];<br /> //notify the view controller when the fetched results change<br /> self.employeeFRC.delegate = self;<br /> <br /> NSError *fetchingError = nil;<br /> //perform the fetch request<br /> if ([self.employeeFRC performFetch:&fetchingError]){<br /> NSLog(@"Successfully fetched data from Employee entity");<br /> }<br /> else {<br /> NSLog(@"Failed to fetch any data from the Employee entity");<br /> }<br /> <br /> }<br /> return self;<br />}<br /><br />- (void)viewDidLoad<br />{<br /> [super viewDidLoad];<br /> <br /> //set the title of the navigation view<br /> [self.navigationItem setTitle:@"Employee List"];<br /> <br /> //create a submit button in the navigation bar<br /> UIBarButtonItem *myButton = [[UIBarButtonItem alloc]<br /> initWithTitle:@"Add"<br /> style:UIBarButtonItemStylePlain<br /> target:self<br /> action:@selector(addEmployee:)];<br /> [self.navigationItem setRightBarButtonItem:myButton];<br /> <br /> //create the table view, assign the data source and delegate<br /> self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds<br /> style:UITableViewStyleGrouped];<br /> self.myTableView.delegate = self;<br /> self.myTableView.dataSource = self;<br /> [self.view addSubview:self.myTableView];<br /> <br />}<br /><br />//notify the receiver that the fetched results controller has completed processing<br />//of one or more changes due to an add, remove, move, or update<br />- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller{<br /> [self.myTableView reloadData];<br />}<br /><br />//the number of rows in a given section of a table view<br />- (NSInteger)tableView:(UITableView *)tableView<br /> numberOfRowsInSection:(NSInteger)section{<br /> <br /> id <NSFetchedResultsSectionInfo> sectionInfo = [self.employeeFRC.sections objectAtIndex:section];<br /> return [sectionInfo numberOfObjects];<br /> <br />}<br /><br />//insert in a particular location of the table view for a given section/row location<br />- (UITableViewCell *)tableView:(UITableView *)tableView<br /> cellForRowAtIndexPath:(NSIndexPath *)indexPath{<br /> <br /> UITableViewCell *myCell = nil;<br /> static NSString *EmployeeCell = @"EmployeeCell";<br /> <br /> //create a reusable table-view cell object located by its identifier<br /> myCell = [tableView dequeueReusableCellWithIdentifier:EmployeeCell];<br /> if (myCell == nil){<br /> myCell =<br /> [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault<br /> reuseIdentifier:EmployeeCell];<br /> myCell.selectionStyle = UITableViewCellSelectionStyleNone;<br /> }<br /> <br /> //get the employee object at the given index path in the fetch results<br /> Employee *employee = [self.employeeFRC objectAtIndexPath:indexPath];<br /> <br /> //display text for the cell view<br /> myCell.textLabel.text = [NSString stringWithFormat:@"%@", employee.name];<br /> <br /> //set the accessory view to be a clickable button<br /> myCell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;<br /> <br /> return myCell;<br />}<br /><br />//informs the delegate that the user tapped the accessory view associated with a given row<br />- (void) tableView:(UITableView *)tableView<br /> accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{<br /> <br /> if ([tableView isEqual:self.myTableView]){<br /> NSLog(@"%@",<br /> [NSString stringWithFormat:@"Cell %ld accessory button in Section %ld is tapped",<br /> (long)indexPath.row, (long)indexPath.section]);<br /> <br /> //let go ahead and allow edit of the employee information<br /> [self editEmployee:indexPath];<br /> }<br />}<br /><br />- (void) editEmployee:(NSIndexPath *)indexPath {<br /> <br /> //if the edit view controller doesn't exists create it<br /> if(self.editViewController == nil){<br /> EditViewController *editView = [[EditViewController alloc] init];<br /> self.editViewController = editView;<br /> }<br /> <br /> //pass the employee id to the edit view controller<br /> Employee *employee = [self.employeeFRC objectAtIndexPath:indexPath];<br /> NSManagedObjectID *employeeID = [employee objectID];<br /> [self.editViewController setEmployeeID:employeeID];<br /> <br /> //pass the NSManagedObjectContext<br /> self.editViewController.managedObjectContext = self.managedObjectContext;<br /> <br /> //tell the navigation controller to push a new view into the stack<br /> [self.navigationController pushViewController:self.editViewController animated:YES];<br /> <br />}<br /><br /><br />- (void) addEmployee:(id)sender {<br /> <br /> //get reference to the button that requested the action<br /> UIBarButtonItem *myButton = (UIBarButtonItem *)sender;<br /> <br /> //check which button it is, if you have more than one button on the screen<br /> //you must check before taking necessary action<br /> if([myButton.title isEqualToString:@"Add"]){<br /> NSLog(@"Clicked on the bar button");<br /> <br /> //if the edit view controller doesn't exists create it<br /> if(self.editViewController == nil){<br /> EditViewController *editView = [[EditViewController alloc] init];<br /> self.editViewController = editView;<br /> }<br /> <br /> //set the employee id to ZERO when creating a new employee<br /> [self.editViewController setEmployeeID:0];<br /> <br /> //pass the NSManagedObjectContext<br /> self.editViewController.managedObjectContext = self.managedObjectContext;<br /> <br /> //tell the navigation controller to push a new view into the stack<br /> [self.navigationController pushViewController:self.editViewController animated:YES];<br /> <br /> }<br /> <br />}<br /><br /><br />- (void)didReceiveMemoryWarning<br />{<br /> [super didReceiveMemoryWarning];<br /> // Dispose of any resources that can be recreated.<br />}<br /><br />@end<br /></pre><br /><h4>Interface file for the Employee Edit - EditViewController.h</h4><pre class="brush: oc">#import <UIKit/UIKit.h><br />#import "Employee.h"<br /><br />@interface EditViewController : UIViewController<br /><br />@property (weak, nonatomic) NSManagedObjectContext *managedObjectContext;<br /><br />@property (nonatomic, strong) UITextField *name;<br />@property (nonatomic, strong) UITextField *position;<br />@property (nonatomic, strong) UITextField *age;<br /><br />@property (nonatomic) NSManagedObjectID *employeeID;<br /><br />@end<br /></pre><br /><h4>Implementation file for the Employee Edit - EditViewController.m</h4><pre class="brush: oc">#import "EditViewController.h"<br /><br />@interface EditViewController ()<br /><br />@end<br /><br />@implementation EditViewController<br /><br />@synthesize name, position, age;<br />@synthesize managedObjectContext;<br />@synthesize employeeID;<br /><br />- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil<br />{<br /> self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];<br /> if (self) {<br /> // Custom initialization<br /> }<br /> return self;<br />}<br /><br />- (void)viewDidLoad<br />{<br /> [super viewDidLoad];<br /> <br /> //set the title of the navigation view<br /> [self.navigationItem setTitle:@"Employee Info"];<br /> <br /> //create screen layout<br /> [self screenLayout];<br /> <br /> //create a submit button in the navigation bar<br /> UIBarButtonItem *myButton = [[UIBarButtonItem alloc]<br /> initWithTitle:@"Save"<br /> style:UIBarButtonItemStylePlain<br /> target:self<br /> action:@selector(saveEmployee:)];<br /> [self.navigationItem setRightBarButtonItem:myButton];<br /> <br />}<br /><br />- (void)viewWillAppear:(BOOL)animated<br />{<br /> [super viewWillAppear:YES];<br /> <br /> //if we have the employee id then its in an edit mode, load the existing values<br /> if(self.employeeID != nil){<br /> <br /> NSError *error = nil;<br /> //get the employee object based on the id that was passed<br /> Employee *employee = (Employee *)[self.managedObjectContext<br /> existingObjectWithID:self.employeeID<br /> error:&error];<br /> <br /> //set the data from the employee object into the text view<br /> name.text = employee.name;<br /> position.text = employee.position;<br /> age.text = [NSString stringWithFormat:@"%@", employee.age];<br /> <br /> }<br /> //add mode clear our text view fields<br /> else {<br /> name.text = @"";<br /> position.text = @"";<br /> age.text = @"";<br /> }<br /> <br /> <br />}<br /><br />- (void) screenLayout {<br /> <br /> CGRect myFrame = CGRectMake(10.0f, 10.0f, 100.0f, 30.0f);<br /> UILabel *myLabel = [[UILabel alloc] initWithFrame:myFrame];<br /> myLabel.font = [UIFont boldSystemFontOfSize:16.0f];<br /> myLabel.textAlignment = NSTextAlignmentRight;<br /> myLabel.text = @"Name:";<br /> [self.view addSubview:myLabel];<br /> <br /> myFrame.origin.y += 35.0f;<br /> myLabel = [[UILabel alloc] initWithFrame:myFrame];<br /> myLabel.font = [UIFont boldSystemFontOfSize:16.0f];<br /> myLabel.textAlignment = NSTextAlignmentRight;<br /> myLabel.text = @"Position:";<br /> [self.view addSubview:myLabel];<br /> <br /> myFrame.origin.y += 35.0f;<br /> myLabel = [[UILabel alloc] initWithFrame:myFrame];<br /> myLabel.font = [UIFont boldSystemFontOfSize:16.0f];<br /> myLabel.textAlignment = NSTextAlignmentRight;<br /> myLabel.text = @"Age:";<br /> [self.view addSubview:myLabel];<br /> <br /> myFrame = CGRectMake(115.0f, 10.0f, 200.0f, 30.0f);<br /> name = [[UITextField alloc] init];<br /> [name setFrame:myFrame];<br /> [name setBorderStyle: UITextBorderStyleRoundedRect];<br /> [self.view addSubview:name];<br /> <br /> myFrame.origin.y += 35.0f;<br /> position = [[UITextField alloc] init];<br /> [position setFrame:myFrame];<br /> [position setBorderStyle: UITextBorderStyleRoundedRect];<br /> [self.view addSubview:position];<br /> <br /> myFrame.origin.y += 35.0f;<br /> age = [[UITextField alloc] init];<br /> [age setFrame:myFrame];<br /> [age setBorderStyle: UITextBorderStyleRoundedRect];<br /> [self.view addSubview:age];<br /> <br /> UIImage *delete = [UIImage imageNamed:@"delete.png"];<br /> UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];<br /> myButton.frame = CGRectMake(10.0f, 10.0f, 35.0f, 35.0f);<br /> [myButton setImage:delete forState:UIControlStateNormal];<br /> [myButton setTitle:@"Delete" forState:UIControlStateNormal];<br /> myButton.titleLabel.hidden = TRUE;<br /> [myButton addTarget:self<br /> action:@selector(deleteEmployee:)<br /> forControlEvents:UIControlEventTouchUpInside];<br /> [self.view addSubview:myButton];<br /> <br />}<br /><br />- (void) saveEmployee:(id)sender {<br /> <br /> //get reference to the button that requested the action<br /> UIBarButtonItem *myButton = (UIBarButtonItem *)sender;<br /> NSLog(@"Clicked on the %@ button",myButton.title);<br /> <br /> //check which button it is, if you have more than one button on the screen<br /> //you must check before taking necessary action<br /> if([myButton.title isEqualToString:@"Save"]){<br /> <br /> //no object id then we have to create a new employee<br /> if(self.employeeID == nil){<br /> [self createNewEmployeeWithName:self.name.text<br /> position:self.position.text<br /> age:[self.age.text intValue]];<br /> }<br /> //let update the employee as it already exists<br /> else {<br /> [self updateEmployeeWithName:self.name.text<br /> position:self.position.text<br /> age:[self.age.text intValue]];<br /> }<br /> <br /> [self.navigationController popViewControllerAnimated:YES];<br /> <br /> }<br /> <br />}<br /><br />//delete the employee<br />- (void) deleteEmployee:(id)sender {<br /> <br /> //get reference to the button that requested the action<br /> UIButton *myButton = (UIButton *)sender;<br /> NSLog(@"Clicked on the %@ button",myButton.currentTitle);<br /> <br /> if([myButton.currentTitle isEqualToString:@"Delete"]){<br /> <br /> if(self.employeeID != nil){<br /> <br /> NSError *error = nil;<br /> Employee *employee = (Employee *)[self.managedObjectContext<br /> existingObjectWithID:self.employeeID<br /> error:&error];<br /> <br /> if (employee == nil){<br /> NSLog(@"Failed to get the employee object");<br /> return;<br /> }<br /> <br /> <br /> [self.managedObjectContext deleteObject:employee];<br /> <br /> NSError *savingError = nil;<br /> if ([self.managedObjectContext save:&savingError]){<br /> NSLog(@"Employee data was deleted");<br /> }<br /> else {<br /> NSLog(@"Failed to delete the employee, Error = %@", savingError);<br /> }<br /> <br /> }<br /> <br /> [self.navigationController popViewControllerAnimated:YES];<br /> <br /> }<br /> <br />}<br /><br />- (BOOL) updateEmployeeWithName:(NSString *)paramName<br /> position:(NSString *)paramPosition<br /> age:(NSUInteger)paramAge{<br /> <br /> BOOL success = NO;<br /> if ([paramName length] == 0){<br /> NSLog(@"Name is mandatory.");<br /> return NO;<br /> }<br /> <br /> NSError *error = nil;<br /> Employee *employee = (Employee *)[self.managedObjectContext<br /> existingObjectWithID:self.employeeID<br /> error:&error];<br /> <br /> if (employee == nil){<br /> NSLog(@"Failed to get the employee object");<br /> return NO;<br /> }<br /> <br /> employee.name = paramName;<br /> employee.position = paramPosition;<br /> employee.age = [NSNumber numberWithUnsignedInteger:paramAge];<br /> <br /> NSError *savingError = nil;<br /> <br /> if ([self.managedObjectContext save:&savingError]){<br /> NSLog(@"Employee data was updated");<br /> return YES;<br /> }<br /> else {<br /> NSLog(@"Failed to update the employee, Error = %@", savingError);<br /> }<br /> return success;<br />}<br /><br /><br />- (BOOL) createNewEmployeeWithName:(NSString *)paramName<br /> position:(NSString *)paramPosition<br /> age:(NSUInteger)paramAge {<br /> BOOL success = NO;<br /> if ([paramName length] == 0){<br /> NSLog(@"Name is mandatory.");<br /> return NO;<br /> }<br /> <br /> Employee *newEmployee = [NSEntityDescription<br /> insertNewObjectForEntityForName:@"Employee"<br /> inManagedObjectContext:self.managedObjectContext];<br /> <br /> if (newEmployee == nil){<br /> NSLog(@"Failed to create the new employee");<br /> return NO;<br /> }<br /> <br /> newEmployee.name = paramName;<br /> newEmployee.position = paramPosition;<br /> newEmployee.age = [NSNumber numberWithUnsignedInteger:paramAge];<br /> <br /> NSError *savingError = nil;<br /> <br /> if ([self.managedObjectContext save:&savingError]){<br /> NSLog(@"New employee was created");<br /> return YES;<br /> }<br /> else {<br /> NSLog(@"Failed to save the new employee, Error = %@", savingError);<br /> }<br /> return success;<br />}<br /><br /><br /><br />- (void)didReceiveMemoryWarning<br />{<br /> [super didReceiveMemoryWarning];<br /> // Dispose of any resources that can be recreated.<br />}<br /><br />@end<br /></pre><h2>Related Articles</h2><ul><li><a href="/2013/06/ios-sqlite-crud-operations-example.html">iOS SQLite example with Create Insert Select Update and Delete operations</a></li></ul>BetterThanZeronoreply@blogger.comtag:blogger.com,1999:blog-5475461039314973243.post-41987826524691367002013-06-03T23:41:00.000-04:002019-03-06T00:43:41.312-05:00iOS SQLite example with Create Insert Select Update and Delete operationsThe underlying database for iOS applications to store large amounts of data is <b>SQLite</b>. It is considered a de facto industry standard for lightweight embedded SQL database programming. You can use the core data framework provided in the iOS SDK to interact with the database in an abstract manner without actually going into the details how the low-level data management is implemented. The other solution is to interact with the <b>SQLite database directly using SQL CRUD operations</b> most of which programmers are familiar with and queries are almost similar to other databases such as MySQL, DB2, Oracle, etc. In this tutorial we are going to do the later.<br /><br />In this example we are going to create a simple employee maintenance application that let's a user add, edit and delete an employee from the database. We also fetch all existing employees to display them in a UITableView for easy selection. Please note after you create your new project just go into the Build Phases and add libsqlite3.dylib library to the list of libraries and frameworks. For help see the images below …<br /><br /><table><tbody><tr><td colspan="3"><a href="https://4.bp.blogspot.com/-M1N9E_WES2I/Ua1Wu5tf5vI/AAAAAAAADUA/bQgf8gKVK4E/s1600/iOS+project+with+SQLite+library+in+Build+phases.png" imageanchor="1"><img border="0" height="200" src="https://4.bp.blogspot.com/-M1N9E_WES2I/Ua1Wu5tf5vI/AAAAAAAADUA/bQgf8gKVK4E/s640/iOS+project+with+SQLite+library+in+Build+phases.png" width="640" /></a></td></tr><tr><td colspan="3"><a href="https://4.bp.blogspot.com/-rl-N98kjDk0/Ua1W0K2SwQI/AAAAAAAADUI/QSAO-ZHxbaM/s1600/iOS+project+add+SQLite+library.png" imageanchor="1"><img border="0" height="136" src="https://4.bp.blogspot.com/-rl-N98kjDk0/Ua1W0K2SwQI/AAAAAAAADUI/QSAO-ZHxbaM/s640/iOS+project+add+SQLite+library.png" width="640" /></a></td></tr><tr><td><a href="https://1.bp.blogspot.com/-x83oVifggs0/Ua1W-5AGkEI/AAAAAAAADUQ/hSdZ1vccpsQ/s1600/IOS+SQLite+insert+update+delete+data.png" imageanchor="1"><img border="0" src="https://1.bp.blogspot.com/-x83oVifggs0/Ua1W-5AGkEI/AAAAAAAADUQ/hSdZ1vccpsQ/s320/IOS+SQLite+insert+update+delete+data.png" /></a></td><td><a href="https://1.bp.blogspot.com/-oToBpLJ0u7Q/Ua1XCbBOIrI/AAAAAAAADUY/Lk9F2voP9eE/s1600/iOS++SQLite+file+maintenance.png" imageanchor="1"><img border="0" src="https://1.bp.blogspot.com/-oToBpLJ0u7Q/Ua1XCbBOIrI/AAAAAAAADUY/Lk9F2voP9eE/s320/iOS++SQLite+file+maintenance.png" /></a></td><td><a href="https://1.bp.blogspot.com/-QTQHyyTrUWA/Ua1XFtyp6qI/AAAAAAAADUg/dSmiMLUqvJY/s1600/iOS+SQLite+data+display+in+UITableView.png" imageanchor="1"><img border="0" src="https://1.bp.blogspot.com/-QTQHyyTrUWA/Ua1XFtyp6qI/AAAAAAAADUg/dSmiMLUqvJY/s320/iOS+SQLite+data+display+in+UITableView.png" /></a></td></tr></tbody></table><h4>Interface file for the App Delegate - SqliteDataAppDelegate.h</h4><pre class="brush: oc">#import <UIKit/UIKit.h><br />#import "DisplayViewController.h"<br /><br />@interface SqliteDataAppDelegate : UIResponder <UIApplicationDelegate><br /><br />@property (strong, nonatomic) UIWindow *window;<br />@property (strong, nonatomic) UINavigationController *navigationController;<br />@property (strong, nonatomic) DisplayViewController *displayViewController;<br /><br />@end<br /></pre><br /><h4>Implementation file for the App Delegate - SqliteDataAppDelegate.m</h4><pre class="brush: oc">#import "SqliteDataAppDelegate.h"<br /><br />@implementation SqliteDataAppDelegate<br /><br />@synthesize navigationController;<br />@synthesize displayViewController;<br /><br />- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions<br />{<br /> self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];<br /> <br /> //create the navigation controller and add the controllers view to the window<br /> navigationController = [[UINavigationController alloc] init];<br /> [self.window addSubview:[self.navigationController view]];<br /> <br /> //check if the display viewcontroller eixsts, otherwise create it<br /> if(self.displayViewController == nil)<br /> {<br /> DisplayViewController *inputView = [[DisplayViewController alloc] init];<br /> self.displayViewController = inputView;<br /> }<br /> <br /> //push the display viewcontroller into the navigation view controller stack<br /> [self.navigationController pushViewController:self.displayViewController animated:YES];<br /> <br /> self.window.backgroundColor = [UIColor whiteColor];<br /> [self.window makeKeyAndVisible];<br /> return YES;<br /><br />}<br /><br /><br />@end<br /></pre><br /><h4>Interface file for the Employee Object - Employee.h</h4><pre class="brush: oc">#import <Foundation/Foundation.h><br /><br />@interface Employee : NSObject<br /><br />@property (nonatomic) NSInteger employeeID;<br />@property (nonatomic, strong) NSString *name;<br />@property (nonatomic, strong) NSString *department;<br />@property (nonatomic) NSInteger age;<br /><br />@end<br /></pre><br /><h4>Implementation file for the Employee Object - Employee.m</h4><pre class="brush: oc">#import "Employee.h"<br /><br />@implementation Employee<br /><br />@synthesize employeeID, name, department, age;<br /><br />@end<br /></pre><br /><h4>Interface file for the SQLite Database Utility - EmployeeDbUtil.h</h4><pre class="brush: oc">#import <Foundation/Foundation.h><br />#import <sqlite3.h><br />#import "Employee.h"<br /><br />@interface EmployeeDbUtil : NSObject {<br /> sqlite3 *mySqliteDB;<br />}<br /><br />@property (nonatomic, strong) NSString *databasePath;<br /><br />- (void) initDatabase;<br />- (BOOL) saveEmployee:(Employee *)employee;<br />- (BOOL) deleteEmployee:(Employee *)employee;<br />- (NSMutableArray *) getEmployees;<br />- (Employee *) getEmployee:(NSInteger) employeeID;<br /><br />@end<br /></pre><br /><h4>Implementation file for the SQLite Database Utility - EmployeeDbUtil.m</h4><pre class="brush: oc">#import "EmployeeDbUtil.h"<br /><br />@implementation EmployeeDbUtil<br /><br />@synthesize databasePath;<br /><br />- (void) initDatabase {<br /> <br /> NSString *docsDir;<br /> NSArray *dirPaths;<br /> <br /> // Get the documents directory<br /> dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);<br /> docsDir = [dirPaths objectAtIndex:0];<br /> <br /> // Build the path to the database file<br /> databasePath = [[NSString alloc] initWithString:<br /> [docsDir stringByAppendingPathComponent:@"employees.db"]];<br /> <br /> NSFileManager *filemgr = [NSFileManager defaultManager];<br /> <br /> //the file will not be there when we load the application for the first time<br /> //so this will create the database table<br /> if ([filemgr fileExistsAtPath: databasePath ] == NO)<br /> {<br /> const char *dbpath = [databasePath UTF8String];<br /> if (sqlite3_open(dbpath, &mySqliteDB) == SQLITE_OK)<br /> {<br /> char *errMsg;<br /> NSString *sql_stmt = @"CREATE TABLE IF NOT EXISTS EMPLOYEES (";<br /> sql_stmt = [sql_stmt stringByAppendingString:@"id INTEGER PRIMARY KEY AUTOINCREMENT, "];<br /> sql_stmt = [sql_stmt stringByAppendingString:@"name TEXT, "];<br /> sql_stmt = [sql_stmt stringByAppendingString:@"department TEXT, "];<br /> sql_stmt = [sql_stmt stringByAppendingString:@"age TEXT)"];<br /> <br /> if (sqlite3_exec(mySqliteDB, [sql_stmt UTF8String], NULL, NULL, &errMsg) != SQLITE_OK)<br /> {<br /> NSLog(@"Failed to create table");<br /> }<br /> else<br /> {<br /> NSLog(@"Employees table created successfully");<br /> }<br /> <br /> sqlite3_close(mySqliteDB);<br /> <br /> } else {<br /> NSLog(@"Failed to open/create database");<br /> }<br /> }<br /> <br />}<br /><br />//save our data<br />- (BOOL) saveEmployee:(Employee *)employee<br />{<br /> BOOL success = false;<br /> sqlite3_stmt *statement = NULL;<br /> const char *dbpath = [databasePath UTF8String];<br /> <br /> if (sqlite3_open(dbpath, &mySqliteDB) == SQLITE_OK)<br /> {<br /> if (employee.employeeID > 0) {<br /> NSLog(@"Exitsing data, Update Please");<br /> NSString *updateSQL = [NSString stringWithFormat:@"UPDATE EMPLOYEES set name = '%@', department = '%@', age = '%@' WHERE id = ?",<br /> employee.name,<br /> employee.department,<br /> [NSString stringWithFormat:@"%d", employee.age]];<br /> <br /> const char *update_stmt = [updateSQL UTF8String];<br /> sqlite3_prepare_v2(mySqliteDB, update_stmt, -1, &statement, NULL );<br /> sqlite3_bind_int(statement, 1, employee.employeeID);<br /> if (sqlite3_step(statement) == SQLITE_DONE)<br /> {<br /> success = true;<br /> }<br /> <br /> }<br /> else{<br /> NSLog(@"New data, Insert Please");<br /> NSString *insertSQL = [NSString stringWithFormat:<br /> @"INSERT INTO EMPLOYEES (name, department, age) VALUES (\"%@\", \"%@\", \"%@\")",<br /> employee.name,<br /> employee.department,<br /> [NSString stringWithFormat:@"%d", employee.age]];<br /> <br /> const char *insert_stmt = [insertSQL UTF8String];<br /> sqlite3_prepare_v2(mySqliteDB, insert_stmt, -1, &statement, NULL);<br /> if (sqlite3_step(statement) == SQLITE_DONE)<br /> {<br /> success = true;<br /> }<br /> }<br /> <br /> sqlite3_finalize(statement);<br /> sqlite3_close(mySqliteDB);<br /> <br /> }<br /> <br /> return success;<br />}<br /><br /><br />//get a list of all our employees<br />- (NSMutableArray *) getEmployees<br />{<br /> NSMutableArray *employeeList = [[NSMutableArray alloc] init];<br /> const char *dbpath = [databasePath UTF8String];<br /> sqlite3_stmt *statement;<br /> <br /> if (sqlite3_open(dbpath, &mySqliteDB) == SQLITE_OK)<br /> {<br /> NSString *querySQL = @"SELECT id, name, department, age FROM EMPLOYEES";<br /> const char *query_stmt = [querySQL UTF8String];<br /> <br /> if (sqlite3_prepare_v2(mySqliteDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)<br /> {<br /> while (sqlite3_step(statement) == SQLITE_ROW)<br /> {<br /> Employee *employee = [[Employee alloc] init];<br /> employee.employeeID = sqlite3_column_int(statement, 0);<br /> employee.name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];<br /> employee.department = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];<br /> employee.age = sqlite3_column_int(statement, 3);<br /> [employeeList addObject:employee];<br /> }<br /> sqlite3_finalize(statement);<br /> }<br /> sqlite3_close(mySqliteDB);<br /> }<br /> <br /> return employeeList;<br />}<br /><br /><br />//get information about a specfic employee by it's id<br />- (Employee *) getEmployee:(NSInteger) employeeID<br />{<br /> Employee *employee = [[Employee alloc] init];<br /> const char *dbpath = [databasePath UTF8String];<br /> sqlite3_stmt *statement;<br /> <br /> if (sqlite3_open(dbpath, &mySqliteDB) == SQLITE_OK)<br /> {<br /> NSString *querySQL = [NSString stringWithFormat:<br /> @"SELECT id, name, department, age FROM EMPLOYEES WHERE id=%d",<br /> employeeID];<br /> const char *query_stmt = [querySQL UTF8String];<br /> <br /> if (sqlite3_prepare_v2(mySqliteDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)<br /> {<br /> if (sqlite3_step(statement) == SQLITE_ROW)<br /> {<br /> employee.employeeID = sqlite3_column_int(statement, 0);<br /> employee.name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)];<br /> employee.department = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];<br /> employee.age = sqlite3_column_int(statement, 3);<br /> }<br /> sqlite3_finalize(statement);<br /> }<br /> sqlite3_close(mySqliteDB);<br /> }<br /> <br /> return employee;<br />}<br /><br />//delete the employee from the database<br />- (BOOL) deleteEmployee:(Employee *)employee<br />{<br /> BOOL success = false;<br /> sqlite3_stmt *statement = NULL;<br /> const char *dbpath = [databasePath UTF8String];<br /> <br /> if (sqlite3_open(dbpath, &mySqliteDB) == SQLITE_OK)<br /> {<br /> if (employee.employeeID > 0) {<br /> NSLog(@"Exitsing data, Delete Please");<br /> NSString *deleteSQL = [NSString stringWithFormat:@"DELETE from EMPLOYEES WHERE id = ?"];<br /> <br /> const char *delete_stmt = [deleteSQL UTF8String];<br /> sqlite3_prepare_v2(mySqliteDB, delete_stmt, -1, &statement, NULL );<br /> sqlite3_bind_int(statement, 1, employee.employeeID);<br /> if (sqlite3_step(statement) == SQLITE_DONE)<br /> {<br /> success = true;<br /> }<br /> <br /> }<br /> else{<br /> NSLog(@"New data, Nothing to delete");<br /> success = true;<br /> }<br /> <br /> sqlite3_finalize(statement);<br /> sqlite3_close(mySqliteDB);<br /> <br /> }<br /> <br /> return success;<br />}<br /><br /><br />@end<br /></pre><br /><h4>Interface file for the Employee Table view - DisplayViewController.h</h4><pre class="brush: oc">#import <UIKit/UIKit.h><br />#import "EditViewController.h"<br />#import "Employee.h"<br />#import "EmployeeDbUtil.h"<br /><br />@interface DisplayViewController : UIViewController <UITableViewDelegate,UITableViewDataSource><br /><br />@property (strong, nonatomic) EditViewController *editViewController;<br />@property (nonatomic, strong) UITableView *myTableView;<br />@property (strong, nonatomic) EmployeeDbUtil *employeeDbUtil;<br /><br />@property (strong, nonatomic) NSMutableArray *employeeList;<br /><br />@end<br /></pre><br /><h4>Implementation file for the Employee Table view - DisplayViewController.m</h4><pre class="brush: oc">#import "DisplayViewController.h"<br /><br />@interface DisplayViewController ()<br /><br />@end<br /><br />@implementation DisplayViewController<br /><br />@synthesize editViewController;<br />@synthesize employeeDbUtil;<br />@synthesize myTableView;<br />@synthesize employeeList;<br /><br />- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil<br />{<br /> self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];<br /> if (self) {<br /> // Custom initialization<br /> self.employeeDbUtil = [[EmployeeDbUtil alloc] init];<br /> [employeeDbUtil initDatabase];<br /> }<br /> return self;<br />}<br /><br />- (void)viewDidLoad<br />{<br /> [super viewDidLoad];<br /> <br /> //set the title of the navigation view<br /> [self.navigationItem setTitle:@"Employee List"];<br /> <br /> //create the table view with a given style<br /> self.myTableView = [[UITableView alloc] initWithFrame:self.view.bounds<br /> style:UITableViewStyleGrouped];<br /> <br /> //set the table view delegate to the current so we can listen for events<br /> self.myTableView.delegate = self;<br /> //set the datasource for the table view to the current object<br /> self.myTableView.dataSource = self;<br /> <br /> //make sure our table view resizes correctly<br /> self.myTableView.autoresizingMask = UIViewAutoresizingFlexibleWidth |<br /> UIViewAutoresizingFlexibleHeight;<br /> <br /> //add the table view to the main view<br /> [self.view addSubview:self.myTableView];<br /><br /> <br /> //create a submit button in the navigation bar<br /> UIBarButtonItem *myButton = [[UIBarButtonItem alloc]<br /> initWithTitle:@"Add"<br /> style:UIBarButtonItemStylePlain<br /> target:self<br /> action:@selector(addEmployee:)];<br /> [self.navigationItem setRightBarButtonItem:myButton];<br />}<br /><br />- (void)viewWillAppear:(BOOL)animated<br />{<br /> [super viewWillAppear:YES];<br /> <br /> //get Employee List<br /> self.employeeList = [employeeDbUtil getEmployees];<br /> <br /> //reload the data in the table view<br /> [self.myTableView reloadData];<br /> <br />}<br /><br /><br />//asks the data source to return the number of sections in the table view<br />//we are retuneing the number of continents<br />- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{<br /> <br /> NSLog(@"%@",@"Called number of Sections in Table View");<br /> NSInteger numberOfSections = 1;<br /> return numberOfSections;<br />}<br /><br />//asks the data source to return the number of rows in a given section of a table view<br />//we are returning the number of countries in a given continent<br />- (NSInteger)tableView:(UITableView *)tableView<br /> numberOfRowsInSection:(NSInteger)section{<br /> <br /> NSLog(@"%@",@"Called number of Rows in a Section");<br /> NSInteger numberOfRows = self.employeeList.count;<br /> return numberOfRows;<br />}<br /><br /><br />//asks the data source for a cell to insert in a particular location of the table view<br />- (UITableViewCell *) tableView:(UITableView *)tableView<br /> cellForRowAtIndexPath:(NSIndexPath *)indexPath{<br /> <br /> NSLog(@"%@",@"Render cell at a given Index Path Section and Row");<br /> UITableViewCell *myCellView = nil;<br /> <br /> if ([tableView isEqual:self.myTableView]){<br /> <br /> static NSString *TableViewCellIdentifier = @"MyCells";<br /> <br /> //this method dequeues an existing cell if one is available or creates a new one<br /> //if no cell is available for reuse, this method returns nil<br /> myCellView = [tableView dequeueReusableCellWithIdentifier:TableViewCellIdentifier];<br /> if (myCellView == nil){<br /> //create a new cell<br /> myCellView = [[UITableViewCell alloc]<br /> initWithStyle:UITableViewCellStyleDefault<br /> reuseIdentifier:TableViewCellIdentifier];<br /> }<br /> <br /> //get the employee based on the index path section<br /> Employee *employee = [[Employee alloc] init];<br /> employee = [self.employeeList objectAtIndex:indexPath.row];<br /> <br /> //display the employee name in main label of the cell<br /> myCellView.textLabel.text = [NSString stringWithFormat:@"%@",<br /> employee.name];<br /> <br /> //set the accessory view to be a clickable button<br /> myCellView.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;<br /> <br /> }<br /> return myCellView;<br />}<br /><br /><br />//informs the delegate that the specified row is now selected<br />- (void) tableView:(UITableView *)tableView<br />didSelectRowAtIndexPath:(NSIndexPath *)indexPath{<br /> <br /> if ([tableView isEqual:self.myTableView]){<br /> NSLog(@"%@",<br /> [NSString stringWithFormat:@"Cell %ld in Section %ld is selected",<br /> (long)indexPath.row, (long)indexPath.section]);<br /> [self editEmployee:indexPath];<br /> }<br />}<br /><br />//informs the delegate that the user tapped the accessory view associated with a given row<br />- (void) tableView:(UITableView *)tableView<br />accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{<br /> <br /> if ([tableView isEqual:self.myTableView]){<br /> NSLog(@"%@",<br /> [NSString stringWithFormat:@"Cell %ld accessory button in Section %ld is tapped",<br /> (long)indexPath.row, (long)indexPath.section]);<br /> <br /> //let go ahead and allow edit of the employee information<br /> [self editEmployee:indexPath];<br /> }<br />}<br /><br />- (void) editEmployee:(NSIndexPath *)indexPath {<br /> <br /> //if the edit view controller doesn't exists create it<br /> if(self.editViewController == nil){<br /> EditViewController *editView = [[EditViewController alloc] init];<br /> self.editViewController = editView;<br /> }<br /> <br /> //pass the employee id to the edit view controller<br /> Employee *employee = [[Employee alloc] init];<br /> employee = [employeeList objectAtIndex:indexPath.row];<br /> [self.editViewController setEmployeeID:employee.employeeID];<br /> <br /> //tell the navigation controller to push a new view into the stack<br /> [self.navigationController pushViewController:self.editViewController animated:YES];<br /> <br />}<br /><br />- (void) addEmployee:(id)sender {<br /> <br /> //get reference to the button that requested the action<br /> UIBarButtonItem *myButton = (UIBarButtonItem *)sender;<br /> <br /> //check which button it is, if you have more than one button on the screen<br /> //you must check before taking necessary action<br /> if([myButton.title isEqualToString:@"Add"]){<br /> NSLog(@"Clicked on the bar button");<br /> <br /> //if the edit view controller doesn't exists create it<br /> if(self.editViewController == nil){<br /> EditViewController *editView = [[EditViewController alloc] init];<br /> self.editViewController = editView;<br /> }<br /> <br /> //since we are in edit mode we don't have an employee id<br /> [self.editViewController setEmployeeID:0];<br /> <br /> //tell the navigation controller to push a new view into the stack<br /> [self.navigationController pushViewController:self.editViewController animated:YES];<br /> <br /> }<br /> <br />}<br /><br />- (void)didReceiveMemoryWarning<br />{<br /> [super didReceiveMemoryWarning];<br /> // Dispose of any resources that can be recreated.<br />}<br /><br />@end<br /></pre><br /><h4>Interface file for the Employee Maintenance - EditViewController.h</h4><pre class="brush: oc">#import <UIKit/UIKit.h><br />#import "Employee.h"<br />#import "EmployeeDbUtil.h"<br /><br />@interface EditViewController : UIViewController<br /><br />@property (nonatomic, strong) UITextField *name;<br />@property (nonatomic, strong) UITextField *department;<br />@property (nonatomic, strong) UITextField *age;<br /><br />@property (nonatomic) NSInteger employeeID;<br />@property (strong, nonatomic) EmployeeDbUtil *employeeDbUtil;<br /><br />@end<br /></pre><br /><h4>Implementation file for the Employee Maintenance - EditViewController.m</h4><pre class="brush: oc">#import "EditViewController.h"<br /><br />@interface EditViewController ()<br /><br />@end<br /><br />@implementation EditViewController<br /><br />@synthesize name, department, age;<br />@synthesize employeeDbUtil;<br />@synthesize employeeID;<br /><br />- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil<br />{<br /> self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];<br /> if (self) {<br /> // Custom initialization<br /> self.employeeDbUtil = [[EmployeeDbUtil alloc] init];<br /> [employeeDbUtil initDatabase];<br /> }<br /> return self;<br />}<br /><br />- (void)viewDidLoad<br />{<br /> [super viewDidLoad];<br /> NSLog(@"View Loading...");<br /> <br /> //set the title of the navigation view<br /> [self.navigationItem setTitle:@"Employee Info"];<br /> <br /> //create screen layout<br /> [self screenLayout];<br /> <br /> //create a submit button in the navigation bar<br /> UIBarButtonItem *myButton = [[UIBarButtonItem alloc]<br /> initWithTitle:@"Save"<br /> style:UIBarButtonItemStylePlain<br /> target:self<br /> action:@selector(saveEmployee:)];<br /> [self.navigationItem setRightBarButtonItem:myButton];<br />}<br /><br />- (void)viewWillAppear:(BOOL)animated<br />{<br /> [super viewWillAppear:YES];<br /> <br /> //well if we have the employee if then its an edit mode<br /> //load the existing values<br /> if(self.employeeID > 0){<br /> Employee *employee = [[Employee alloc] init];<br /> employee = [employeeDbUtil getEmployee:self.employeeID];<br /> name.text = employee.name;<br /> department.text = employee.department;<br /> age.text = [NSString stringWithFormat:@"%d", employee.age];<br /> }<br /> //add mode clear our fields<br /> else {<br /> name.text = @"";<br /> department.text = @"";<br /> age.text = @"";<br /> }<br /> <br /> <br />}<br /><br />//save the employee information<br />- (void) saveEmployee:(id)sender {<br /> <br /> //get reference to the button that requested the action<br /> UIBarButtonItem *myButton = (UIBarButtonItem *)sender;<br /> NSLog(@"Clicked on the %@ button",myButton.title);<br /> <br /> //check which button it is, if you have more than one button on the screen<br /> //you must check before taking necessary action<br /> if([myButton.title isEqualToString:@"Save"]){<br /> <br /> Employee *employee = [[Employee alloc] init];<br /> employee.employeeID = self.employeeID;<br /> employee.name = self.name.text;<br /> employee.department = self.department.text;<br /> employee.age = [self.age.text intValue];<br /> [employeeDbUtil saveEmployee:employee];<br /> <br /> [self.navigationController popViewControllerAnimated:YES];<br /> <br /> }<br /> <br />}<br /><br />//delete the employee<br />- (void) deleteEmployee:(id)sender {<br /> <br /> //get reference to the button that requested the action<br /> UIButton *myButton = (UIButton *)sender;<br /> NSLog(@"Clicked on the %@ button",myButton.currentTitle);<br /> <br /> if([myButton.currentTitle isEqualToString:@"Delete"]){<br /> <br /> Employee *employee = [[Employee alloc] init];<br /> employee.employeeID = self.employeeID;<br /> [employeeDbUtil deleteEmployee:employee];<br /> <br /> [self.navigationController popViewControllerAnimated:YES];<br /> <br /> }<br /> <br />}<br /><br /><br />- (void) screenLayout {<br /> <br /> CGRect myFrame = CGRectMake(10.0f, 10.0f, 100.0f, 30.0f);<br /> UILabel *myLabel = [[UILabel alloc] initWithFrame:myFrame];<br /> myLabel.font = [UIFont boldSystemFontOfSize:16.0f];<br /> myLabel.textAlignment = NSTextAlignmentRight;<br /> myLabel.text = @"Name:";<br /> [self.view addSubview:myLabel];<br /> <br /> myFrame.origin.y += 35.0f;<br /> myLabel = [[UILabel alloc] initWithFrame:myFrame];<br /> myLabel.font = [UIFont boldSystemFontOfSize:16.0f];<br /> myLabel.textAlignment = NSTextAlignmentRight;<br /> myLabel.text = @"Department:";<br /> [self.view addSubview:myLabel];<br /> <br /> myFrame.origin.y += 35.0f;<br /> myLabel = [[UILabel alloc] initWithFrame:myFrame];<br /> myLabel.font = [UIFont boldSystemFontOfSize:16.0f];<br /> myLabel.textAlignment = NSTextAlignmentRight;<br /> myLabel.text = @"Age:";<br /> [self.view addSubview:myLabel];<br /> <br /> myFrame = CGRectMake(115.0f, 10.0f, 200.0f, 30.0f);<br /> name = [[UITextField alloc] init];<br /> [name setFrame:myFrame];<br /> [name setBorderStyle: UITextBorderStyleRoundedRect];<br /> [self.view addSubview:name];<br /> <br /> myFrame.origin.y += 35.0f;<br /> department = [[UITextField alloc] init];<br /> [department setFrame:myFrame];<br /> [department setBorderStyle: UITextBorderStyleRoundedRect];<br /> [self.view addSubview:department];<br /> <br /> myFrame.origin.y += 35.0f;<br /> age = [[UITextField alloc] init];<br /> [age setFrame:myFrame];<br /> [age setBorderStyle: UITextBorderStyleRoundedRect];<br /> [self.view addSubview:age];<br /> <br /> UIImage *delete = [UIImage imageNamed:@"delete.png"];<br /> UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];<br /> myButton.frame = CGRectMake(10.0f, 10.0f, 35.0f, 35.0f);<br /> [myButton setImage:delete forState:UIControlStateNormal];<br /> [myButton setTitle:@"Delete" forState:UIControlStateNormal];<br /> myButton.titleLabel.hidden = TRUE;<br /> [myButton addTarget:self<br /> action:@selector(deleteEmployee:)<br /> forControlEvents:UIControlEventTouchUpInside];<br /> [self.view addSubview:myButton];<br /> <br />}<br /><br />- (void)didReceiveMemoryWarning<br />{<br /> [super didReceiveMemoryWarning];<br /> // Dispose of any resources that can be recreated.<br />}<br /><br />@end<br /></pre><h2>Related Articles</h2><ul><li><a href="/2013/06/ios-core-data-example-crud-operations.html">iOS Core Data example - CRUD operations</a></li></ul>BetterThanZeronoreply@blogger.com