Thursday, December 11, 2014

Android XMPP delete user

To register in XMPP server first of all you need to CREATE XMPP CONNECTION

After connection to XMPP server. If you don't have registration in XMPP server, for Registration click here

For delete user from XMPP server you need to use AccountManager  class for get account and than deleteAccount() method is used for delete the account.

For delete account from XMPP server user must login to XMPP server. For login to XMPP server 

Below is example code for delete user from XMPP server.

XML file layout is below.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/btn_Delete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_centerInParent="true"
        android:layout_marginTop="38dp"
        android:text="Delete User" />

</RelativeLayout>

Use below activity for the login to XMPP server.

import org.jivesoftware.smack.AccountManager;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
 
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
 
public class TestActivity extends Activity{
 
 private Button btn_Delete;
 
 XMPPConnection connection ;
 ConnectionConfiguration config;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.demo_activity);
  
  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
      .detectAll()
      .penaltyLog()
      .build();
  StrictMode.setThreadPolicy(policy);
 
  btn_Delete = (Button) findViewById(R.id.btn_Delete);
  
  btn_Delete.setOnClickListener(new OnClickListener() {
 
   @Override
   public void onClick(View v) {
    try {
     if (connection.isConnected()) {
      connection.disconnect();
      connection.connect();
      connection.login("USERNAME", "PASSWORD");
        AccountManager accountManager = connection.getAccountManager();
        accountManager.deleteAccount();
        connection.disconnect();
//        System.exit(0);
     }else {
      connection.connect();
       AccountManager accountManager = connection.getAccountManager();
        accountManager.deleteAccount();
        connection.disconnect();
//        System.exit(0);
     }
     
    } catch (XMPPException e) {
     e.printStackTrace();
    }
   }
  });
 }
}

Hope this post is helpful for you...

Android XMPP login

To register in XMPP server first of all you need to CREATE XMPP CONNECTION

After connection to XMPP server. If you don't have registration in XMPP server, for Registration click here

For login  login("USERNAME", "PASSWORD") method is used.  In this method you need to pass username and password as parameter.

For this example below is the code for xml file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/btn_Login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_centerInParent="true"
        android:layout_marginTop="38dp"
        android:text="Login" />

</RelativeLayout>


Use below activity for the login to XMPP server.

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
 
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
 
public class TestActivity extends Activity{
 
 private Button btn_Login;
 
 XMPPConnection connection ;
 ConnectionConfiguration config;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.demo_activity);
  
  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
      .detectAll()
      .penaltyLog()
      .build();
  StrictMode.setThreadPolicy(policy);
 
  
  btn_Login = (Button) findViewById(R.id.btn_Login);
  
  btn_Login.setOnClickListener(new OnClickListener() {
 
   @Override
   public void onClick(View v) {
    try {
     try {
      if (connection.isConnected()) {
       connection.disconnect();
       connection.connect();
       connection.login("USERNAME", "PASSWORD");
       
      }else {
       connection.connect();
       connection.login("USERNAME", "PASSWORD");
       
      }
      
     } catch (XMPPException e) {
      e.printStackTrace();
     }
     
    } catch (Exception e) {
     e.printStackTrace();
    }
   }
  });
 }
}

Hope this post may helpful for you...

Friday, December 5, 2014

Android XMPP registration

To register in XMPP server first of all you need to connect with XMPP server.

For register new user in XMPP server AccountManager class is used

To get account manager below code snippet is used
 
AccountManager accountManager = connection.getAccountManager();

For register new user in XMPP server below method is used.

createAccount("USERNAME", "PASSWORD")

For this example below is the code for xml file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/btn_Register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_centerInParent="true"
        android:layout_marginTop="38dp"
        android:text="Register" />

</RelativeLayout>

Use below activity for the register new user to XMPP server.

public class DemoActivity extends Activity{
 
 private Button btn_Register;
 XMPPConnection connection ;
 ConnectionConfiguration config;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.demo_activity);
 
  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
       .detectAll()
       .penaltyLog()
       .build();
   StrictMode.setThreadPolicy(policy);

  new ConnectToXmpp().execute();
  
  btn_Register = (Button) findViewById(R.id.btn_Register);
  btn_Register.setOnClickListener(new OnClickListener() {
 
   @Override
   public void onClick(View v) {
     try {
       AccountManager accountManager = connection.getAccountManager();
               accountManager.createAccount("USERNAME", "PASSWORD");
    } catch (XMPPException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
            
   }
  });
 }
 private class ConnectToXmpp extends AsyncTask<Void, Void, Void> {
 
     @Override
     protected Void doInBackground(Void... params) {
           config = new ConnectionConfiguration("YOUR SERVER IP", PORT);
           connection = new XMPPConnection(config);
     try {
          connection.connect();
          connection.login("ADMIN LOGIN", "ADMIN PASSWORD");
     } catch (XMPPException e) {
         e.printStackTrace();
     } 
 
         return null;
     }
 
     @Override
     protected void onPostExecute(Void result) {
 
     }
 
 }
}


Hope this post may helpful for you....

Android create XMPPConnection

To create XMPP connection in android you required smack.jar file in your project.

Download smack.jar file from Here

Add jar file in lib folder of your project and than add to build path.

To create connection with XMPP server first of all create XMPPConnection.
Use below code snippet for connection with server.

 
ConnectionConfiguration  config = new ConnectionConfiguration(“YOUR SERVER IP, PORT);
XMPPConnection  connection = new XMPPConnection(config);


To create XMPP connection in your android put this below code in your  activity for XMPP connection


 
public class MainActivity extends Activity {
 
 XMPPConnection connection ;
 ConnectionConfiguration config;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
 
  new ConnectToXmpp().execute();
  
 }
 private class ConnectToXmpp extends AsyncTask {
 
     @Override
     protected Void doInBackground(Void... params) {
           config = new ConnectionConfiguration(“YOUR SERVER IP”, PORT);
           connection = new XMPPConnection(config);
     try {
          connection.connect();
          connection.login("ADMIN USERNAME”, “ADMIN PASSWORD”);
     } catch (XMPPException e) {
         e.printStackTrace();
     } 
 
         return null;
     }
 
     @Override
     protected void onPostExecute(Void result) {
 
     }
 
 }
}

That's it...

Hope this post may helpful for you...

Saturday, November 8, 2014

Android change orientation of layout dynamically

In this post create demo for change orientation of layout programmatically on radio button click.

See more update about android

See below is the output of the example.


First create xml layout file for radio button.
Below is the code for main.xml file

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/lin_btn"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="vertical" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Horizontal" />
</RadioGroup>
</LinearLayout>
</LinearLayout>

Now, For change orientation programtically from Java put below java activity in your project.

public class MainActivity extends ActionBarActivity {
public LinearLayout lin_btn;
RadioGroup group;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
group = (RadioGroup) findViewById(R.id.radioGroup1);
lin_btn = (LinearLayout) findViewById(R.id.lin_btn);
group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final RadioGroup group, int checkedId) {
if (checkedId == R.id.radio0) {
group.setOrientation(RadioGroup.VERTICAL);
} else if (checkedId == R.id.radio1) {
group.setOrientation(RadioGroup.HORIZONTAL);
}
}
});
}
}

Hope this post may helpful for you.

Saturday, October 4, 2014

StringBuilder example in java

The Java StringBuilder class represents string objects that can be changed. It contains methods such as append and insert that modify the string object. For example, the append method adds a string to the end of the StringBuilder object. The object is changed; no new object is created or returned. Generally use the StringBuilder class for string objects that will change.

There is mainly two way to append string.

Way – 1:

    String s = “Example”;
    s = s + ”  varemads”;
    system.out.println(s);

Output give you “Hello World”, let’s be different from the rest and think about making the code more efficient.

Way - 2:



    StringBuilder sb = new StringBuilder(“Example”);
    sb.append(” varemads”);
    system.out.println(sb);

well… thats it!! You’ll get your “Hello World” but in a more efficient way.

It is recommended to use StringBuilder whenever possible because
it is faster than StringBuffer. However if thread safety is

necessary the best option is StringBuffer objects.


http://www.varemads.com/java-2/java-use-stringbuilder/

Difference between Stringbuffer and Stringbuilder

Hope this post is helpful for you...



Stringbuffer and StringBuilder in java

The most important difference between String and StringBuffer/StringBuilder in java is that String object is immutable whereas StringBuffer/StringBuilder objects are mutable.

String

One important characteristic of the Java String class is that the string object cannot be changed. Even though the String class contains methods such as replace andtoUpperCase, the object remains unchanged. Instead, these methods return a new String object. For example, the toLowerCase method returns a new String object with all of the characters in lower case. As a guideline, use Java String for string objects that will not change.

StringBuilder

The Java StringBuilder class represents string objects that can be changed. It contains methods such as append and insert that modify the string object. For example, the append method adds a string to the end of the StringBuilder object. The object is changed; no new object is created or returned. Generally use the StringBuilder class for string objects that will change.

StringBuffer

The Java StringBuffer class is just like StringBuilder. The primary difference is that StringBuffer issynchronized. In other words, multiple threads can safely process StringBuffer objects. However, additional overhead is required to make StringBuffer synchronized. So StringBuffer is slower than StringBuilder. You should use the StringBuffer class for string objects that will be changed by multiple threads of execution.

The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer and StringBuilder is that StringBuilders methods are not thread safe(not Synchronised).

StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isn’t thread safe).


So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.

It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However if thread safety is necessary the best option is StringBuffer objects.

http://www.varemads.com/java-2/java-difference-stringbuffer-stringbuilder/

Here is Example of StringBuilder in JAVA

Hope this post is helpful for you...


Wednesday, October 1, 2014

Circular Imageview in android

In this post create circular ImageView in android. For create circular imageview here we use custom class named as CircularImageView.

Create CircularImageView.java in your project package.

public class CircularImageView extends ImageView {
 private int borderWidth;
 private int canvasSize;
 private Bitmap image;
 private Paint paint;
 private Paint paintBorder;

 public CircularImageView(final Context context) {
  this(context, null);
 }

 public CircularImageView(Context context, AttributeSet attrs) {
  this(context, attrs, R.attr.circularImageViewStyle);
 }

 public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);

  paint = new Paint();
  paint.setAntiAlias(true);

  paintBorder = new Paint();
  paintBorder.setAntiAlias(true);

  TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CircularImageView, defStyle, 0);

  if(attributes.getBoolean(R.styleable.CircularImageView_border, true)) {
   int defaultBorderSize = (int) (4 * getContext().getResources().getDisplayMetrics().density + 0.5f);
   setBorderWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_border_width, defaultBorderSize));
   setBorderColor(attributes.getColor(R.styleable.CircularImageView_border_color, Color.WHITE));
  }

  if(attributes.getBoolean(R.styleable.CircularImageView_shadow, false))
   addShadow();
 }

 public void setBorderWidth(int borderWidth) {
  this.borderWidth = borderWidth;
  this.requestLayout();
  this.invalidate();
 }

 public void setBorderColor(int borderColor) {
  if (paintBorder != null)
   paintBorder.setColor(borderColor);
  this.invalidate();
 }

 public void addShadow() {
  setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
  paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
 }

 @Override
 public void onDraw(Canvas canvas) {
  image = drawableToBitmap(getDrawable());

  if (image != null) {

   canvasSize = canvas.getWidth();
   if(canvas.getHeight() < canvasSize)
    canvasSize = canvas.getHeight();

   BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
   paint.setShader(shader);

   int circleCenter = (canvasSize - (borderWidth * 2)) / 2;
   canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) + borderWidth - 4.0f, paintBorder);
   canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) - 4.0f, paint);
  }
 }

 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  int width = measureWidth(widthMeasureSpec);
  int height = measureHeight(heightMeasureSpec);
  setMeasuredDimension(width, height);
 }

 private int measureWidth(int measureSpec) {
  int result = 0;
  int specMode = MeasureSpec.getMode(measureSpec);
  int specSize = MeasureSpec.getSize(measureSpec);

  if (specMode == MeasureSpec.EXACTLY) {
   result = specSize;
  } else if (specMode == MeasureSpec.AT_MOST) {
   result = specSize;
  } else {
   result = canvasSize;
  }

  return result;
 }

 private int measureHeight(int measureSpecHeight) {
  int result = 0;
  int specMode = MeasureSpec.getMode(measureSpecHeight);
  int specSize = MeasureSpec.getSize(measureSpecHeight);

  if (specMode == MeasureSpec.EXACTLY) {
   result = specSize;
  } else if (specMode == MeasureSpec.AT_MOST) {
   result = specSize;
  } else {
   result = canvasSize;
  }

  return (result + 2);
 }

 public Bitmap drawableToBitmap(Drawable drawable) {
  if (drawable == null) {
   return null;
  } else if (drawable instanceof BitmapDrawable) {
   return ((BitmapDrawable) drawable).getBitmap();
  }

  Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
    drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(bitmap);
  drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
  drawable.draw(canvas);

  return bitmap;
 }
}

Now create attr.xml under res/values/ folder in your project.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="CircularImageView">
        <attr name="border" format="boolean"></attr>
        <attr name="border_width" format="dimension"></attr>
        <attr name="border_color" format="color"></attr>
        <attr name="shadow" format="boolean"></attr>
    </declare-styleable>
   
    <declare-styleable name="Theme">
        <attr name="circularImageViewStyle" format="reference"></attr>
    </declare-styleable>

</resources>

In your layout file add imageview like below code

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:gravity="center">

    <**YOUR PACKAGE NAME**.CircularImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:src="@drawable/ic_launcher"/>
 
</LinearLayout>

Output for above code is like below


Hope this post is helpful for you...

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.