Facebook login and retrieve profile data in Android

Add Facebook dependency in your app level gradle file.

compile 'com.facebook.android:facebook-android-sdk:[4,5)'

Always check https://developers.facebook.com/ for the latest version of their Android SDK.

Now add following things in your manifest file.

Add this meta-data and activity declaration inside your application tag.

<meta-data
  android:name="com.facebook.sdk.ApplicationId"
  android:value="@string/facebook_app_id" />
<activity
  android:name="com.facebook.FacebookActivity"
  android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
  android:label="@string/app_name" />
<activity
  android:name="com.facebook.CustomTabActivity"
  android:exported="true">
    <intent-filter>
      <action android:name="android.intent.action.VIEW" />
      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="android.intent.category.BROWSABLE" />
      <data android:scheme="@string/fb_login_protocol_scheme" />
    </intent-filter>
</activity>

Please add 2 strings ‘facebook_app_id’ and ‘fb_login_protocol_scheme’ from your Facebook app. You will already have ‘app_name’ string created in your project by Android Studio.

Now add this 2 line in your Application class(the class extending Application).

FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);

Now we add one button in our layout which will do login/logout functionality.

<Button
  android:id="@+id/btn"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Login" />

Here is the coding for the java file, i.e. MainActivity.java

public class MainActivity extends AppCompatActivity {
  private Button btn;
  private CallbackManager callbackManager;
  private AccessTokenTracker accessTokenTracker;
  private AccessToken accessToken;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FacebookSdk.sdkInitialize(this.getApplicationContext());

    btn = (Button) findViewById(R.id.btn);

    callbackManager = CallbackManager.Factory.create();

    accessTokenTracker = new AccessTokenTracker() {
      @Override
      protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
        accessToken = currentAccessToken;
        if (accessToken == null) {
          btn.setText("LOGIN");
        }
        else {
          btn.setText("LOGOUT");
          GraphRequest request = GraphRequest.newMeRequest(accessToken,
            new GraphRequest.GraphJSONObjectCallback() {
              @Override
              public void onCompleted(JSONObject object, GraphResponse response  {
                if (null != object) {
                  //your json object here, access user data here
                  Log.e("test", "json: " + object.toString());
                }
                else {
                  Log.e("test", "json: null");
                }
              }
            });
            Bundle parameters = new Bundle();
            parameters.putString("fields",  "id,birthday,first_name,gender,last_name,location,name,locale,timezone,updated_time,verified,email,hometown");
            request.setParameters(parameters);
            request.setAccessToken(accessToken);
            request.executeAsync();
          }
        }
      };

      accessToken = AccessToken.getCurrentAccessToken();
      if (null != accessToken) {
        btn.setText("LOGOUT");
      } else {
        btn.setText("LOGIN");
      }

      btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          if ("LOGOUT".equals(btn.getText().toString())) {
            LoginManager.getInstance().logOut();
          } else {
          LoginManager.getInstance().logInWithReadPermissions(MainActivity1.this, Arrays.asList("public_profile", "email", "user_birthday", "user_hometown", "user_location"));
          }
        }
      });
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    accessTokenTracker.stopTracking();
  }
}

Various material designs for Button in Android

It is very important to update/create your app with material design. It will boost up your app downloads compare to older design.

Using AppCompat library you can design Button in your app in many ways. Here is demonstrate you 6 different kind of buttons with example code so you can directly integrate them in your code.

Screenshot_2016-04-28-23-52-27

1. Simple Button

<Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="Simple Button" />

2. Coloured Button

<Button
  style="@style/Widget.AppCompat.Button.Colored"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="10dp"
  android:text="Colored Button" />

3. Borderless Button

<Button
  style="@style/Widget.AppCompat.Button.Borderless"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="10dp"
  android:text="Borderless Button" />

4. Borderless Coloured Button

<Button
  style="@style/Widget.AppCompat.Button.Borderless.Colored"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="10dp"
  android:text="Borderless Colored Button" />

5. Simple Button Without Shadow

<Button
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:stateListAnimator="@null"
  android:layout_marginTop="10dp"
  android:text="Simple Button Without Shadow" />

6. Coloured Button Without Shadow

<Button
  style="@style/Widget.AppCompat.Button.Colored"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:stateListAnimator="@null"
  android:layout_marginTop="10dp"
  android:text="Colored Button Without Shadow" />

Download Source Code: https://github.com/dakshbhatt21/a-computer-engineer

Add border at bottom of TextField in iOS

If you want to make your TextField simple like in Android Lollipop. In this code, your TextField will be clean with a single border at bottom and your placeholder/text. Checkout the below image for that.

Screen Shot 2015-12-31 at 7.35.57 PM

Just add this code in your app and you are ready to go.

textField.layer.masksToBounds=YES;
textField.backgroundColor=[UIColor clearColor];
textField.borderStyle = UITextBorderStyleNone;
[textField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    
CALayer *bottomBorder = [CALayer layer];
bottomBorder.frame = CGRectMake(0, textField.frame.size.height - 2, textField.frame.size.width, 2.0f);
bottomBorder.backgroundColor = [[UIColor whiteColor]CGColor];

[textField.layer addSublayer:bottomBorder];

Add “more apps from this developer” button to your Android app

It’s a good practice to add a button called “more apps” or “more apps from this developer” in your Android app. It will increase downloads of your other apps to as well as the user can checkout your other apps if interested.

So now here is the code that you should paste in the button click event or any other place you want.

try {
  //replace &quot;Unified+Apps&quot; with your developer name
  startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(&quot;market://search?q=pub:Unified+Apps&quot;)));
}
catch (android.content.ActivityNotFoundException anfe) {
  //replace &quot;Unified+Apps&quot; with your developer name
  startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(&quot;http://play.google.com/store/search?q=pub:Unified+Apps&quot;)));
}

Here we use try and catch because very few Android device do not have Play Store app in their device. In that case, it will open your developer page as a website in the browser.

Try it now!

Admob banner ad integration in Andriod Studio

Admob integration becomes very easy with the Android Studio. No need to include .jar file or google play service lib like in Eclipse. Follow the steps to include admob banner to your app.

 

  1. Make sure you’ve updated the “Extra” part of your android sdk. Because we need here Google Repository. Now add the following line to dependencies area of your app’s gradle file.
    compile 'com.google.android.gms:play-services-ads:7.8.0'
    

    After pasting this line, check the bottom part of the android studio where it will suggest you to change the version of google play service ads. Because it might be possible that there will be new version of google play service ads. Now click on “sync now” at the top of android studio and you are ready to go.

  2. Now open the AndroidManifest.xml file and include following in different part of the file. First add two permission in the <manifest> tag and out side of <application> tag.
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    Now add meta data in your <application> tag.

    <meta-data 
    android:name="com.google.android.gms.version" 
    android:value="@integer/google_play_services_version" />

    Now add admob activity in application tag same as meta data.

    <activity 
    android:name="com.google.android.gms.ads.AdActivity" 
    android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" 
    android:theme="@android:style/Theme.Translucent" />
  3. Then add the below xml code in your xml layout file where you want to display ad. It’s a good practice to surround your ad with relative layout. So that you can easily hide the ad until it’s load without affecting the rest of your layout.
    <RelativeLayout 
      xmlns:ads="http://schemas.android.com/apk/res-auto"
      android:id="@+id/rl_ad" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_alignParentBottom="true">
        <com.google.android.gms.ads.AdView 
          android:id="@+id/adView" 
          android:layout_width="wrap_content" 
          android:layout_height="wrap_content" 
          android:layout_centerHorizontal="true" 
          android:layout_alignParentBottom="true" 
          android:visibility="gone" 
          ads:adSize="BANNER" 
          ads:adUnitId="YOUR_AD_UNIT_ID">
        </com.google.android.gms.ads.AdView>
    </RelativeLayout>

    Make sure that you set the visibility of the ad to “gone” in xml file. Because we will hide the ad until it loads completely or there will be blank white space until the ad loads from server and it looks bad. Do not forget to replace YOUR_AD_UNIT_ID with your actual Ad unit id created from admob dashboard.

  4. And finally add the following code in your respective Activity file and that’s it! The ad should be loaded.
    final AdView mAdView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().build();
    mAdView.loadAd(adRequest);
    mAdView.setAdListener(new AdListener() {
      @Override
      public void onAdLoaded() {
        super.onAdLoaded();
        mAdView.setVisibility(View.VISIBLE);
      }
    });

    It will display the ad once it loaded completely.

 
You can check the detailed explanation of everything in this tutorial as well as other information about integration here on Google Developers site and download sample app from there.

If you have any issues in the above code, please write them below in comment section. Thank you.
 

Validation in Java/Android

Many time during my Android development, I need to verify email address, username, password or any specific requirements. Most of times it needs when I am building registration form or login form. So I made the function that takes first argument as string on which validation is needed and pattern [Regular Expression] that decides first argument is valid or invalid.

Here I use two main java class

Here Pattern class compile the regular expression and then Matcher class perform match operation against given String using compiled pattern. Here is the function for that.

	public Boolean validate(String text, String regex)	{
		Pattern pattern;	
		Matcher matcher;
		pattern = Pattern.compile(regex);
    	matcher = pattern.matcher(text);
    	if(matcher.matches())	{
    		return true;
    	}
    	else	{
    		return false;
    	}
	}

Here you can see that the function validate validates the String text against the regex using Pattern and Matcher class. I attached the example of email validation below, but you can use any validation by just providing their regular expression.

Download example of email validation with comments here : https://www.mediafire.com/view/vgw8pdf5db9ygzu/Validation.java

References :