Monday, September 29, 2014

UITableView using swift iPhone example

In this article we create UITableView using swift programming language. For create UITableView in iPhone main class is UITableViewControllerUITableViewDelegateUITableViewDataSource.


To create UITableView below two overrided method is used in ViewController

 override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    }
The above method is used for the number of cells in UITableView.

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    }

This method is used for the create cell at particular row and data to be display in cell.

Below is the full TableViewController class

import Foundation
import UIKit

class tableViewContoller: UITableViewController, UITableViewDelegate, UITableViewDataSource {
    let kCellIdentifier: String = "Cell"
IBOutlet var appsTableView : UITableView!
    let array:NSArray = ["Item 1","Item 2", "Item 3","Item 4"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: kCellIdentifier)
        cell.textLabel?.text = "\(array[indexPath.row])"
        cell.textLabel?.textColor = UIColor.blueColor();
        return cell
    }
}
 Output of the above UITableView Controller.

Hope this is post is helpful for you...

Monday, September 22, 2014

Google Play soon list in-app purchase price ranges on Sept. 30 2014

Google today dropped word on the developer dashboard that the price-range for in-app purchases on a given app soon will be listed in the app description. The change takes effect Sept. 30.



Basically if an app has in-app purchases or subscription rates, you'll be able to see the ballpark cost first thing and not get blindsided later by, for (extreme) example, a free app that for some reason charges $20 later to do something. (And for parents, this definitely is a good thing.)

Here's the announcement from Google:

Price ranges for in-app purchases Beginning September 30, 2014, all apps offering in-app purchases to users will have an "In-app purchases" price range displayed on their detail page on Google Play. Price ranges will include in-app products and subscriptions.

If any of your apps offer paid in-app features or subscriptions, go to your app's In-app Products page to review the prices and publishing status of your in-app items.

Refrence :

Webservice call in swift iOS

In this article we call webservice using the swift programming language in iPhone.

To make webservice call using swift language first of create NSURL with your webservice url and create NSURLRequest using NSURL.

        let nsurl:NSURL = NSURL(string:"PUT YOUR WEB_SERVICE URL HERE")
        let request:NSURLRequest = NSURLRequest(URL: nsurl)
Now create connection with server using NSURLConnection using Asynchronous.
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) in
            println(NSString(data: data, encoding: NSUTF8StringEncoding))
          
            var nsdata:NSData = NSData(data: data)
            var response:NSString = NSString(data: data, encoding:                                                       NSUTF8StringEncoding)
            println("This is the final response \(response)")
In this article I parse the JSON response. To parse the json response create below method for parse the JSON response.

    func parseJSON(inputData: NSData){
        var error: NSError?
        var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary

For get any string from the JSON response use below line of code.
      var status:NSString = boardsDictionary["YOUR KEY OF JSONOBJECT"] as NSString

For get JSON array from JSON response use below code 
        var tableList:NSArray = boardsDictionary["YOUR KEY FOR JSONARRAY"] as NSArray
       } 

That's it...

Full code for your UIViewController.

import UIKit

class getWebserviceCall: UIViewController {
  
    override func viewDidLoad() {
        super.viewDidLoad()
       
        let nsurl:NSURL = NSURL(string:"YOUR WEBSERVICE URL")
        let request:NSURLRequest = NSURLRequest(URL: nsurl)
       
      
        let indicator:UIActivityIndicatorView = UIActivityIndicatorView (activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        indicator.color = UIColor .magentaColor()
        indicator.frame = CGRectMake(0.0, 0.0, 10.0, 10.0)
        indicator.center = self.view.center
        self.view.addSubview(indicator)
        indicator.bringSubviewToFront(self.view)
       
        indicator.startAnimating()
       
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) in
            println(NSString(data: data, encoding: NSUTF8StringEncoding))
          
            var nsdata:NSData = NSData(data: data)
            var response:NSString = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("This is the final response \(response)")
            indicator.stopAnimating()
           
                self.parseJSON(nsdata)
            })
       
    }
   
    func parseJSON(inputData: NSData){
        var error: NSError?
        var boardsDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
       
        var status:NSString = boardsDictionary["YOUR JSONOBJECT KEY"] as NSString
        var tableList:NSArray = boardsDictionary["YOUR JSONARRAY KEY"] as NSArray
        
      
    }
}

Hope this post is helpful for you..






Sunday, September 21, 2014

Add Log file in SDCard android

Now a days some developer want to add error crash report to sdcard.

For those this is the best example for append crash log file to SD Card.

To add crash log file to the SD Card use below code snippet.

To add heap memory information to log file use this.

ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);

To get device information use this

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);

Using above two class We can get all the information and print that all in the log file.
To create and write the log file use below piece of code.

File logFile = new File("sdcard/" + getResources().getString(R.string.app_name) + ".sys"));
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}

Use below two methods for write the log file on your device SD Card.

This method is for device configuration and exceptions.
public void printDeviceConfig(Context context) {
StringBuilder stringBuilder = new StringBuilder();
try {
System.err.println("=============== HEAP INFO ===============================");
stringBuilder.append("=============== HEAP INFO(S) ===============================");
stringBuilder.append("\n");

ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);

System.err.println("Over All Memory: " + (memoryInfo.availMem / 1024) + " KB");
stringBuilder.append("Over All Memory: " + (memoryInfo.availMem / 1024) + " KB");
stringBuilder.append("\n");
System.err.println("low Memory: " + memoryInfo.lowMemory);
stringBuilder.append("low Memory: " + memoryInfo.lowMemory);
stringBuilder.append("\n");
System.err.println("Threshold Memory: " + (memoryInfo.threshold / 1024) + " KB");
stringBuilder.append("Threshold Memory: " + (memoryInfo.threshold / 1024) + " KB");
stringBuilder.append("\n");

System.err.println("=============== OS INFO ===============================");
stringBuilder.append("=============== OS INFO ===============================");
stringBuilder.append("\n");
System.err.println("Device MODEL: " + android.os.Build.MODEL);
stringBuilder.append("Device MODEL: " + android.os.Build.MODEL);
stringBuilder.append("\n");
System.err.println("VERSION RELEASE: " + android.os.Build.VERSION.RELEASE);
stringBuilder.append("VERSION RELEASE: " + android.os.Build.VERSION.RELEASE);
stringBuilder.append("\n");
System.err.println("VERSION SDK: " + android.os.Build.VERSION.SDK);
stringBuilder.append("VERSION SDK: " + android.os.Build.VERSION.SDK);
stringBuilder.append("\n");

System.err.println("=============== Device Information ===============================");
stringBuilder.append("=============== Device Information ===============================");
stringBuilder.append("\n");
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
System.err.println("Device Resolution (WxH)= " + dm.widthPixels + " x " + dm.heightPixels);
stringBuilder.append("Device Resolution (WxH)= " + dm.widthPixels + " x " + dm.heightPixels);
stringBuilder.append("\n");
System.err.println("Density DPI= " + dm.densityDpi);
stringBuilder.append("Density DPI= " + dm.densityDpi);
stringBuilder.append("\n");

} catch (Exception e) {
e.printStackTrace();
StringWriter stackTrace = new StringWriter();
e.printStackTrace(new PrintWriter(stackTrace));
stringBuilder.append("\n");
stringBuilder.append("=============== Exception while Fetching Information ===============================");
stringBuilder.append("\n");
stringBuilder.append(stackTrace);
stringBuilder.append("\n");
}
appendLog(stringBuilder.toString());
}
Now the below method appendLog() is for the write all the above data in the file which stored in your device SD card.

public void appendLog(String text) {
File logFile = new File("sdcard/" + getResources().getString(R.string.app_name) + ".sys"));
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
Calendar calendar = Calendar.getInstance();
try {
System.err.println("Logged Date-Time : " + calendar.getTime().toLocaleString());
} catch (Exception e) {
}
buf.append("Logged Date-Time : " + calendar.getTime().toLocaleString());
buf.append("\n\n");
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}

That's it....
Now every when application run all information write in the log file in your SD Card.

NOTE:

Also when your app is crashed or any exception is occurred in your activity that also write in your log file.

Put this method in all the activity in which you want the exception.
That all exception wrote on log file.

And file name is same as your application name.

Hope this post is help full for you...

The biggest iOS release ever

iOS 8 comes with big updates to apps you use every day, like Messages and Photos. A whole new way to share content with your family. And exciting new connections between apps and between devices. All that and more make iOS 8 the biggest iOS release ever.




Quickly find and edit the photos you take. Add your voice right in a text message. Let your health and fitness apps communicate with each other, with your trainer, and even with your doctor. We’ve also provided developers with deeper access and more tools. You’ll have new keyboard options and even more ways to share your content. And you’ll be able to use iCloud and Touch ID in ways you never have before. Here are some of the things iOS 8 can do for you so you can do more than ever.

Family Sharing.
Sharing with your family comes naturally. Now it comes to all your content.


Family Sharing is a new way to bring harmony to your family’s digital life. Up to six people in your family can share purchases from iTunes, iBooks, and the App Store without sharing accounts. Pay for family purchases with the same credit card and approve kids’ spending right from a parent’s device. Easily share photos, a family calendar, and more to help keep everyone connected.
Now you have the freedom to work with the document of your choice on the device of your choice. Because with iCloud Drive, you can safely store all your presentations, spreadsheets, PDFs, images, and any other kind of document in iCloud and access them from your iPhone, iPad, iPod touch, Mac, or PC.

Storing files in iCloud is simple. Just as it should be.

To upload your files to iCloud, simply drag them into the iCloud Drive folder on your Mac running OS X Yosemite or PC running Windows 7 or later. Or start a new document using an iCloud-enabled app on your iOS device. Then you’ll be able to access those documents from all your devices.



UIActivity IndicatorView using swift iPhone

In this article create UIActivity IndicatorView in iPhone using swift programming langauge.


To create UIActivity indicator in iPhone using swift.
Create object of UIActivityIndicator

 let indicator:UIActivityIndicatorView = UIActivityIndicatorView (activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)

Set property to activity indicator like


Color
        indicator.color = UIColor .magentaColor() 
Frame :
indicator.frame = CGRectMake(0.0, 0.0, 10.0, 10.0) 
Position
indicator.center = self.view.center

After this add this subview to main  view

self.view.addSubview(indicator)

Now to display this indicator on the view 

indicator.bringSubviewToFront(self.view)

There are methods for show and hide this view is

  1. startAnimating()
  2. stopAnimating()
To use this methods when you want to show the indicator call this indicator.startAnimating()

and when you want to hide this indicator call this indicator.stopAnimating()

The full code for UIActivity IndicatorView 

let indicator:UIActivityIndicatorView = UIActivityIndicatorView (activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        indicator.color = UIColor .magentaColor()
        indicator.frame = CGRectMake(0.0, 0.0, 10.0, 10.0)
        indicator.center = self.view.center
        self.view.addSubview(indicator)
        indicator.bringSubviewToFront(self.view)
        indicator.startAnimating()

Output :



Hope this article is helpful for you...





 

Saturday, September 20, 2014

Encryption and decryption in android using AESHelper

In this article we will learn how make a program which to helps you learn how you can perform encryption/decryption with java.

In this post I explain the encryption and decryption of string using Cipher class.

Below is the class in which method for encryption and decryption.

Add this class in your android project package.

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import android.util.Base64;
public class AESHelper{
        public static String encrypt(String seed, String cleartext) throws Exception {
                byte[] rawKey = seed.getBytes();
                byte[] result = encrypt(rawKey, cleartext.getBytes());
                return Base64.encodeToString(result, Base64.DEFAULT);
        }
        public static String decrypt(String seed, String encrypted) throws Exception {
                byte[] rawKey = seed.getBytes();
                byte[] enc = Base64.decode(encrypted, Base64.DEFAULT);
                byte[] result = decrypt(rawKey, enc);
                return new String(result);
        }
      
        private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(clear);
                return encrypted;
        }
        private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
                Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] decrypted = cipher.doFinal(encrypted);
                return decrypted;
        }
}

For encryption of the string using this class
AESHelper.encrypt(HERE IS YOUR ENCRYPTION KEY, HERE PASS YOUR STRING TO BE ENCRYPT);
For decryption of the string using above class
AESHelper.decrypt(HERE IS YOUR ENCRYPTION KEY, HERE PASS YOUR STRING TO BE DECRYPT);
NOTE : Make sure that your key is of 128 bit or higher.

Hope this post is helpful for you...

Timeago class in android

In this article we create Timeago function for change time.

For example AWeek ago, A Day ago, A Minute ago etc.

For Change your time in above format use below class for change your time to Timeago format.

Create object of TimeAgo class.
TimeAgo timeAgo = new TimeAgo(YOUR CLASS NAME HERE.this);
timeAgo.timeAgo(PASS YOUR STRING DATE HERE, PASS DATE FORMATTER HERE) ;
Below I describe the example with use of TimeAgo class.
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TimeAgo timeago = new TimeAgo(MainActivity.this);
        String time1 = timeago.timeAgo("2014-09-20 00:10", "yyyy-MM-dd HH:mm");
        String time2 = timeago.timeAgo("2014-09-20 11:59", "yyyy-MM-dd HH:mm");
        String time3= timeago.timeAgo("2014-09-28 11:59", "yyyy-MM-dd HH:mm");
        TextView textView1 = (TextView) findViewById(R.id.textView1);
        TextView textView2 = (TextView) findViewById(R.id.textView2);
        TextView textView3 = (TextView) findViewById(R.id.textView3);
        textView1.setText(time1);
        textView2.setText(time2);
        textView3.setText(time3);
    }
}

Output of above example is like below.

First of add below this string to your string.xml file in your android project.

    <string name="time_ago_prefix"></string>

    <string name="time_ago_suffix">ago</string>

    <string name="time_ago_seconds">less than a minute</string>

    <string name="time_ago_minute">about a minute</string>

    <string name="time_ago_minutes">%d minutes</string>

    <string name="time_ago_hour">about an hour</string>

    <string name="time_ago_hours">about %d hours</string>

    <string name="time_ago_day">a day</string>

    <string name="time_ago_days">%d days</string>

    <string name="time_ago_month">about a month</string>

    <string name="time_ago_months">%d months</string>

    <string name="time_ago_year">about a year</string>

    <string name="time_ago_years">%d years</string>

Add this below TimeAgo.java  class in your package of android Project.
public class TimeAgo {
protected Context context;
public TimeAgo(Context context) {
this.context = context;
}

public String timeAgo(String strDate,String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format);
try {
return timeAgo(formatter.parse(strDate));
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}
public String timeAgo(Date date) {
return timeAgo(date.getTime());
}
public String timeAgo(long millis) {
long diff = new Date().getTime() - millis;
Resources r = context.getResources();
String prefix = r.getString(R.string.time_ago_prefix);
String suffix = r.getString(R.string.time_ago_suffix);
double seconds = Math.abs(diff) / 1000;
double minutes = seconds / 60;
double hours = minutes / 60;
double days = hours / 24;
double years = days / 365;
String words;
if (seconds < 45) {
words = r.getString(R.string.time_ago_seconds, Math.round(seconds));
} else if (seconds < 90) {
words = r.getString(R.string.time_ago_minute, 1);
} else if (minutes < 45) {
words = r.getString(R.string.time_ago_minutes, Math.round(minutes));
} else if (minutes < 90) {
words = r.getString(R.string.time_ago_hour, 1);
} else if (hours < 24) {
words = r.getString(R.string.time_ago_hours, Math.round(hours));
} else if (hours < 42) {
words = r.getString(R.string.time_ago_day, 1);
} else if (days < 30) {
words = r.getString(R.string.time_ago_days, Math.round(days));
} else if (days < 45) {
words = r.getString(R.string.time_ago_month, 1);
} else if (days < 365) {
words = r.getString(R.string.time_ago_months, Math.round(days / 30));
} else if (years < 1.5) {
words = r.getString(R.string.time_ago_year, 1);
} else {
words = r.getString(R.string.time_ago_years, Math.round(years));
}
StringBuilder sb = new StringBuilder();
if (prefix != null && prefix.length() > 0) {
sb.append(prefix).append(" ");
}
sb.append(words);
if (suffix != null && suffix.length() > 0) {
sb.append(" ").append(suffix);
}
return sb.toString().trim();
}
}
Hope this post is helpful for you.





Thursday, September 18, 2014

UIAlertView using Swift in iOS

In this post we create simple UIAlertView using swift programming language in iOS with example.

For create UIAlertView using Swift programming language.
First of all create object of UIAlertView class

var alert: UIAlertView = UIAlertView()
After  that  add title and message to  UIAlertView object.

alert.title =  "Test Alert"
 alert.message = "This is test alert message"
Now add button to alert message like below
alert.addButtonWithTitle("Ok")
Now yout alert dialog is ready. It's time to show your alert dialog.
Show your Alert dialog using show() method.
alert.show()


 
 This is the output of our Alert dialog.
Put below code in method  where you want to show UIAlertView.

            var alert: UIAlertView = UIAlertView()
            alert.title"Test Alert"
            alert.message = "This is test alert message"
            alert.addButtonWithTitle("Ok")
            alert.show() 

That's it...
I hope this post may  helpful to you...

Java serialization de-serialization

In previous post we seen the example of interface in Java. In this Java serialization de-serialization with example.
Primary purpose of java serialization is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again. When there are two different parties involved, you need a protocol to rebuild the exact same object again. Java serialization API just provides you that. Other ways you can leverage the feature of serialization is, you can use it to perform a deep copy.
Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.
Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.
Create a Java project called “varemads.java.serilization”. Create the following Java object called Employee
import java.io.Serializable;
public class Employee implements Serializable {
private String firstName;
private String lastName;
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return “Employee [firstName=" + firstName + ", lastName=" + lastName+ "]“;
}
}
The following code example show you how you can serializable and de-serializable this object.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Main {
public static void main(String[] args) {
String filename = “varemads.ser”;
Employee employee = new Employee(“Arvind”, “Kanjariya”);

// save the object to file
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
out.writeObject(employee);

out.close();
} catch (Exception ex) {
ex.printStackTrace();
}
// read the object from file
// save the object to file
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(filename);
in = new ObjectInputStream(fis);
p = (Person) in.readObject();
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(employee);
}
}
Note:The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject()method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can’t find a class during the deserialization of an object, it throws a ClassNotFoundException.