Wednesday, December 25, 2013

Singleton Pattern in Volley library

Singleton Pattern in Volley library

Google recommends that you use a common RequestQueue object for your app in the form of a Singleton. 


import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class VolleySingleton {
private static VolleySingleton mInstance = null;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;

private VolleySingleton(Context context){
mRequestQueue = Volley.newRequestQueue(context);
mImageLoader = new ImageLoader(this.mRequestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> mCache = new LruCache<String, Bitmap>(10);
public void putBitmap(String url, Bitmap bitmap) {
mCache.put(url, bitmap);
}
public Bitmap getBitmap(String url) {
return mCache.get(url);
}
});
}

public static VolleySingleton getInstance(Context context){
if(mInstance == null){
mInstance = new VolleySingleton(context);
}
return mInstance;
}

public RequestQueue getRequestQueue(){
return this.mRequestQueue;
}

public ImageLoader getImageLoader(){
return this.mImageLoader;
}

}

use this
RequestQueue queue = VolleySingleton.getInstance(context).getRequestQueue();

//or


mImageLoader = VolleySingleton.getInstance(context).getImageLoader();

Handle image in Android from Url

Setting up the Android Google Volley ImageLoader for NetworkImageView
-----------------------------------------------------------

<com.android.volley.toolbox.NetworkImageView
android:id="@+id/twitter_avatar"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
/>

NetworkImageView avatar = (NetworkImageView)view.findViewById(R.id.twitter_avatar);
avatar.setImageUrl("http://someurl.com/image.png",mImageLoader);

Or

mRequestQueue = Volley.newRequestQueue(context);
mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> mCache = new LruCache<String, Bitmap>(10);
public void putBitmap(String url, Bitmap bitmap) {
mCache.put(url, bitmap);
}
public Bitmap getBitmap(String url) {
return mCache.get(url);
}
});
NetworkImageView avatar = (NetworkImageView)view.findViewById(R.id.twitter_avatar);

avatar.setImageUrl("http://someurl.com/image.png",mImageLoader);

Spring for Android

                       Spring for Android




add the below code in you gradle file in android studio 
-----
dependencies {
compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'
compile 'org.springframework.android:spring-android-auth:1.0.1.RELEASE'
compile 'org.springframework.android:spring-android-core:1.0.1.RELEASE'
}
add this in your activity
The following example illustrates how to search Google:

"services/search/web?v=1.0&q={query}";

// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate();

// Add the String message converter
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

// Make the HTTP GET request, marshaling the response to a String

String result = restTemplate.getForObject(url, String.class, "Android");

Android – Volley Library

                           Android – Volley Library


Volley is a library that makes networking for Android apps easier and most importantly, faster.

Advantages of using Volley:
                         Volley automatically schedule all network requests. It means that Volley will be taking                                  care of all the network requests your app executes for fetching response or image                                     from web.
                        Volley provides transparent disk and memory caching.
                      Volley provides powerful cancellation request API. It means that you can cancel a single                             request or you can set blocks or scopes of requests to cancel.
                     Volley provides powerful customization abilities.
                    Volley provides Debugging and tracing tools

How to get started?
    Clone the Volley project
       Import the code into your project
       Clone the Volley project:

Wednesday, November 27, 2013

Regx Validation in IOS

Email validation using Regx in iOS


+(BOOL) isValidEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}
Phone number validation using Regx in iOS

+(BOOL) isValidPhone:(NSString *)phone
{
    NSString *phoneRegex = @"[235689][0-9]{6}([0-9]{3})?";
    NSPredicate *test = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [test evaluateWithObject:phone];
}
Password validation using Regx in iOS
+(BOOL) isPasswordValid:(NSString *)pwd
{
    if ( [pwd length]<6 || [pwd length]>32 ) return NO// too long or too short
    NSRange rang;
    rang = [pwd rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
    if ( !rang.length ) return NO// no letter
    rang = [pwd rangeOfCharacterFromSet:[NSCharacterSet decimalDigitCharacterSet]];
    if ( !rang.lengthreturn NO// no number;
    return YES;

}

get device Name and device id in iOS 5 and IOS6 and iOS 7

#pragma mark - get unique id
 + (NSString *)getUUID
{
    return [[[UIDevice currentDevice] identifierForVendor] UUIDString];
}

#pragma  mark - get device name
 + (NSString *)getDeviceName
{
    return [[UIDevice currentDevice] name];

}

Different Label for Navigationbar title and back button

self.navigationItem.title=@"Recent Books";
UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@"Back"
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
self.navigationItem.backBarButtonItem=backButton;

How to create back button in navigation bar

Add the following in viewWillappear
     UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style: UIBarButtonItemStyleBordered target:self action:@selector(Back)];
     self.navigationItem.leftBarButtonItem = backButton;
And in
- (IBAction)Back
  {
    [self dismissViewControllerAnimated:YES completion:nil]; // ios 6
  }

IOS gradient Button

// Add Border to button
        CALayer *layer = btnCalender.layer;
        layer.cornerRadius = 5.0f;
        layer.masksToBounds = YES;
        layer.borderWidth = 1.0f;
        layer.borderColor = [UIColor colorWithWhite:0.3f alpha:0.2f].CGColor;
        
        // Add Shine to button
        CAGradientLayer *Layer = [CAGradientLayer layer];
        Layer = layer.bounds;
        Layer.colors = [NSArray arrayWithObjects:
                             (id)[UIColor colorWithWhite:1.0f alpha:0.4f].CGColor,
                             (id)[UIColor colorWithWhite:1.0f alpha:0.2f].CGColor,
                             (id)[UIColor colorWithWhite:0.75f alpha:0.2f].CGColor,
                             (id)[UIColor colorWithWhite:0.4f alpha:0.2f].CGColor,
                             (id)[UIColor colorWithWhite:1.0f alpha:0.4f].CGColor,
                             nil];
        Layer.locations = [NSArray arrayWithObjects:
                                [NSNumber numberWithFloat:0.0f],
                                [NSNumber numberWithFloat:0.2f],
                                [NSNumber numberWithFloat:0.3f],
                                [NSNumber numberWithFloat:0.0f],
                                [NSNumber numberWithFloat:1.0f],
                                nil];
        [layer addSublayer: Layer];

using a unique identifier of iPhone or iOS device

Create a UUID: A string containing a UUID. The standard format for UUIDs represented in ASCII is a string punctuated by hyphens, for example 68753A44-4D6F-1226-9C60-0050E4C00067.
+ (NSString *)newUUID
{
    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return (NSString *)string;
}

Check for internet connection

Please Use Any Of the below Code


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkChanged:) name:kReachabilityChangedNotification object:nil];

reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];

- (void)networkChanged:(NSNotification *)notification
{

  NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];

  if(remoteHostStatus == NotReachable) { NSLog(@"not reachable");}
  else if (remoteHostStatus == ReachableViaWiFiNetwork) { NSLog(@"wifi"); }
  else if (remoteHostStatus == ReachableViaCarrierDataNetwork) { NSLog(@"carrier"); }
}

Or

#import <CoreFoundation/CoreFoundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <netdb.h>

BOOL networkReachable()
{
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    SCNetworkReachabilityRef reachabilityRef = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *) &zeroAddress);

    SCNetworkReachabilityFlags flags;
    if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) {
        if ((flags & kSCNetworkReachabilityFlagsReachable) == 0) {
            // if target host is not reachable
            return NO;
        }

        if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0) {
            // if target host is reachable and no connection is required
            //  then we'll assume (for now) that your on Wi-Fi
            return YES; // This is a wifi connection.
        }


        if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0)
            ||(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)) {
            // ... and the connection is on-demand (or on-traffic) if the
            //     calling application is using the CFSocketStream or higher APIs

            if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0) {
                // ... and no [user] intervention is needed
                return YES; // This is a wifi connection.
            }
        }

        if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) {
            // ... but WWAN connections are OK if the calling application
            //     is using the CFNetwork (CFSocketStream?) APIs.
            return YES; // This is a cellular connection.
        }
    }

    return NO;
}
or
- (BOOL)connectedToInternet
{
   NSURL *url=[NSURL URLWithString:@"http://www.google.com"];
   NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
   [request setHTTPMethod:@"HEAD"];
   NSHTTPURLResponse *response;
   [NSURLConnection sendSynchronousRequest:request returningResponse:&response error: NULL];

   return ([response statusCode]==200)?YES:NO;
}

Virtual Function in C++ Programming

                             If there are member function with same name in derived classes, virtual functions gives programmer capability to call member function of different class by a same function call depending upon different context. This feature in C++ programming is known as polymorphism which is one of the important feature of OOP.

Example
#include <stdio.h>
  using namespace std; 
   class B { 
       public: 
           void display() {
                  cout<<"Content of base class.\n"; 
               }
 }; 
class D : public B {

 public:   
 void display() {
      cout<<"Content of derived class.\n"; 
      }
 };
 int main() { 

B *b; 
D d;
 b->display(); 
b = &d; /* Address of object d in pointer variable */ 
b->display(); 
return 0; 
}

Output 
Content of base class. 
Content of base class. 



If you want to execute the member function of derived class then, you can declare display( ) in the base class virtual which makes that function existing in appearance only but, you can't call that function. In order to make a function virtual, you have to add keyword virtual in front of a function. 



* Example to demonstrate the working of virtual function in C++ programming. */

#include <iostream>
using namespace std;
class B
{
    public:
     virtual void display()      /* Virtual function */
         { cout<<"Content of base class.\n"; }
};

class D1 : public B
{
    public:
       void display()
         { cout<<"Content of first derived class.\n"; }
};

class D2 : public B
{
    public:
       void display()
         { cout<<"Content of second derived class.\n"; }
};

int main()
{
    B *b;
    D1 d1;
    D2 d2;

/* b->display();  // You cannot use this code here because the function of base class is virtual. */

    b = &d1;
    b->display();   /* calls display() of class derived D1 */
    b = &d2;           
    b->display();   /* calls display() of class derived D2 */
    return 0;
}
Output
-------------


Content of first derived class.
Content of second derived class.

Inheritance in C++


What to inherit?
In principle, every member of a base class is inherited by a derived class 
– just with different access permission
A class can be derived from more than one classes, which means it can inherit data and functions from multiple base classes. To define a derived class, we use a class derivation list to specify the base class(es). A class derivation list names one or more base classes and has the form:
class derived-class: access-specifier base-class
Access Control Over the Members
• Two levels of access control over class members
class definition inheritance type
base class/ superclass/ parent class

class Point{
protected: int x, y;
public: void set(int a, int b);
};
derived class/ subclass/ child class
class Circle : public Point{ ......
};
0 

Example 
// derived classes
#include <iostream>
using namespace std;

class CPolygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b;}
  };

class CRectangle: public CPolygon {
  public:
    int area ()
      { return (width * height); }
  };

class CTriangle: public CPolygon {
  public:
    int area ()
      { return (width * height / 2); }
  };
  
int main () {
  CRectangle rect;
  CTriangle trgl;
  rect.set_values (4,5);
  trgl.set_values (4,5);
  cout << rect.area() << endl;
  cout << trgl.area() << endl;
  return 0;
}