Now you can Subscribe using RSS

Submit your Email

Sunday

How to use Crashlytics with Android Studio | Error Reporting Example

Vishal Shrestha

In any Android or iOS applications, it is highly likely that these will be a use case where your app will crash even if after the rigorous tests you've put your app through. Be it because of different API levels, memory issues, hardware incompability or any other problem, its of utmost importance that you recognize these factor and diagnose them. This is where Crashlytics comes in, it helps you track crashes very precisely find out the issue and diagnose them. Crashlytics can also provide you insights and possible solutions for common errors.

Paying attention to these crashes and fixing them as soon as possible avoids frustation among more users and possibly you can impress your users with quick bug fixes. If you don't use tools like Crashlytics, it's very difficult track the crashes, more of your users might get unhappy and give your app bad ratings and reviews, uninstall your app and go with your competitier's app instead. The app market is already very crowded, keeping your users happy and providing them a bug free and crash free experience is vital in any app's success.

Crashlytics is my favorite tool for crash analytics, it is quick, provides nice summary and has almost everything I need to know about the crash. Some of the key features I like about crashlytics are:
1. Real time error reports: You can opt to receive email about the errors in real time so you know exactly when the app has crashed.
2. Possible solutions and insights for major/common issues: Crashlytics also provides possible solutions to some commont problems so you can understand more about the crash in your apps.
3. Stability Digest: Crashlytics also provides a stability digesting informing you how stable your app is. It provide key features of your apps performance.
4. Helpful Organization of errors into categories: The errors are well organized and categorized into different groups making it very easy for you to navigate through and focus on the important ones.
5. Free! Yes, Crashlytics is free :D

Use Crashlytics and you'll come to know the importance of it and know how good your app is ;). In this tutorial we will go over account creation with Crashlytics, its integration in Android, getting crash reports and custom messages. So lets start integration of Crashlytics in your Android app, you can also check our tutorial video:


1. Create a Fabric account
  • Go to Fabric's site and sign up: Fabric Sign Up
  • You'll see a page similar to this:


    Enter your details, use an Email address to which you have access as you'll receive the confirmation email later on. Once you have confirmed your account, you'll have the options to select from: iOS, Android and Unity.


    Select Android as we will be integrating Crashlytics to our Android App.
2. Installing Fabric Plugin to Android Studio.

  • Now it's time to install Fabric plugin to Android Studio so we can use Crashlytics. You will be able to see what you need to do once you select Android. However, at the moment of writing this, the instruction were not upto date due to updates in Android Studio, so here are the generic steps: Go to file->settings->plugins then search for Fabric and click install.


  • After you've installed Fabric, you might need to restart Android Studio to see the the changes. Once Fabric is successfully installed, you'll see Fabric logo along with other options in the toolbar as shown in image below:


3. Add Crashlytics to your Android Project.
  • Now click on the Fabric icon and you'll see login option. Login in using your details that you had used in step 1.


  • Once you've successfully logged in, you'll see a bunch of options that you can use in your project. We will select Crashlytics as we are only interested in crash reporting for now.


  • After selecting Crashlytics, you'll find options to do the necessary changes automatically, code to generate a crash to test and user information. Just click on install and your Gradle file will be modified automatically to include Crashlytics.


4. Build and Run your project
  • After you've run the project, you see your project in Crashlytics dashboard.
5. Mock a crash and see Error Reporting in Crashlytics
  • You can check the crash code from Crashlytics, but I am too lazy to check it, and the least we as programmers can do is generate a crash :P, so here's how I did it:
    I just added a button variable and set a OnClickListner to it without referencing the variable to any real button. It will generate a null pointer exception and we will be able to see crash report in Crashlytics. Here the code:
     Button aButton;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Fabric.with(this, new Crashlytics());
            setContentView(R.layout.activity_main);
            aButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                }
            });
        }
This is it! We have integrated Fabric Plugin in Android Studio and Crashlytics to Android App. If you have any issues feel free to comment below, I'll be happy to help. :) Happy Coding!

Monday

Show GUI components in OnGUI method and change Font, Size and Color | Unity Tutorial

Vishal Shrestha
Unity provides a very helpful method, OnGui that can be used to create UI components easily and you can easily remove them my just a simple condition checking, you have probably done that and just want want the title describes but I can't resist from showing how simple it is to just show/hide window components and register button click. You just create components like this in the onGUI method:

void onGUI(){
if (GUI.Button (Rect (20,20,250,200), "I am that Button"))
    print("And I just got pressed!");
}

And now, let's say you want to hide the button when your player is dead or any other event, you just do this:

void onGUI(){
if(!isUserDeadOrAnyOtherEvent) 

  if (GUI.Button (Rect (20,20,250,200), "I am that Button"))
    print("And I just got pressed!");
}

Now, the button will simply be shown only when the condition above is met, that is only when user is not dead or any other condition that needs to be satisfied.

Alright, that was a brief intro to how you can create GUI components, now we will see how we can change their look via their properties:
gui-properties-unity
GUI Components properties Unity
1. Changing Text color of Labels in OnGUI in Unity.

GUIStyle guiStyle = new GUIStyle(GUI.skin.label);
guiStyle.normal.textColor = Color.white;
GUI.Label(new Rect(0, 0, 800, 300), "I am the White Label", guiStyle);

2. Changing Font Size in OnGUI in Unity

GUIStyle guiStyle = new GUIStyle(GUI.skin.label);
guiStyle.fontSize = 36;
GUI.Label(new Rect(0, 0, 800, 300), "I am the White Label", guiStyle);

3. Changing Font in OnGUI in Unity

// You may put a label to show a message to the player
GUIStyle guiStyle = new GUIStyle(GUI.skin.label);
// Load and set Font
Font myFont = (Font)Resources.Load("Fonts/AMERICANCAPTAINWEBFONT", typeof(Font));
guiStyle.font = myFont;
GUI.Label(new Rect(0, 0, 800, 300), "I am the White Label", guiStyle);

Note that you need to put you fonts in a Fonts folder inside Assets folder in order for this to work.
4. Changing Text Alignment in OnGUI in Unity

GUIStyle guiStyle = new GUIStyle(GUI.skin.label);
guiStyle.alignment = TextAnchor.MiddleCenter;
GUI.Label(new Rect(0, 0, 800, 300), "I am the White Label", guiStyle); 

Now, you know how you can change Text color, size, font and Alignment in Unity. You can include all these properties like this:
GUIStyle guiStyle = new GUIStyle(GUI.skin.label);
guiStyle.fontSize = 36;
guiStyle.normal.textColor = Color.white;
//Load and set Font
Font myFont = (Font)Resources.Load("Fonts/AMERICANCAPTAINWEBFONT", typeof(Font));
guiStyle.font = myFont;
guiStyle.alignment = TextAnchor.MiddleCenter; 

This it it, it's all pretty simple. Feel free to drop any comments or queries you have below. Happy Coding!

Friday

Twilio PHP API for sending SMS-OTP Tutorial & Example.

Vishal Shrestha
Twilio provides a set of web APIs that enabled users to use standard web languages to build VoIP, voice and SMS apps via a web APIs.
Twilio has grown a lot and has a lot of APIs that can be used by customers to enhance the service that they are providing. Some of those APIs are Programmable SMS, Chat, Verification Services, Authentication, Elastic SIP Trunking and a lot more. Today we will be looking at Twilio's SMS API. We will send verification SMS to any required device using Twilio's SMS API. We will be using Twilio's PHP SDK . We can easily install it using Composer. It can easily be used without composer but composer pulls all the required libraries, dependencies and manage them all in one place. It's very useful and easy to learn. Learning it will help you manage a lot of dependencies. Now a good time to start learning it. Here's more details if you want to learn more about it, however for this project the details provided in this article will be enough. So lets begin. The steps involved in integrating Twilio SMS for our app are:
  1. Create a Twilio Account.
  2. Get SID and Token from Twilio.
  3. Set up Twilio PHP SDK using composer.
  4. Create a Twilio Client using PHP to send SMS.
You can check out the full tutorial video too :

Now lets go over the steps in detail:

1. Creating a Twilio Account
 If you don't already have an account, you need to sign up for using Twilio APIs. The Login screen looks like this:

Twilio-login-page
Twilio Login

Enter you name, password and select I'm just exploring in the question where you need to select which product do you plan to use. Select phone verification for the question "What are you building", select PHP as the language and finally select not a production app for the "Potential Monthly Interaction" question. After that you need to enter your phone number so that they can verify you. Enter you real phone number as a code will be sent to you for verification. Enter the code that you receive, you are now required to create a project name. Name the project SmsVerification, and click done. The account creation is now complete, you should be able to see your project console.

2. Get SID and Token from Twilio
You can see you Account SID and Auth Token on the first visible page in the console. The console looks like the image below, you can see the SID and Auth token blurred.

Twilio-console
Twilio Account Dashboard

 Once you have your Account SID and Auth token, next we will set up the Twilio PHP SDK.

3. Setting up Twilio PHP SDK
Now we will use composer to set up Twilio's PHP SDK. First of all download and install COMPOSER. After the composer has been successfully installed, create a project directory/folder if you haven't already. Open terminal and go to the root directory of you project and enter the following commands in the terminal:

composer init --require=twilio/sdk

After you hit enter, you'll be asked several things like author, minimum stability and some other project information. You can leave it as it is and just press enter through the options until it asks do you want to resolve dependencies interactively? You need to type n meaning no for that option.
This will create a composer.json file with the required details for installing Twilio's PHP SDK. Now run the following command:

composer install

You'll be able to see Twilio SDK being downloaded and set up. After the process has been successfully installed, there will be a vendor directory created with a twilio directory with several other files and directories inside it. Now we are ready to code.

4. Creating a Twilio Client using PHP to send SMS
 In your PHP file put the following statements in the beginning of the code:

require __DIR__ . '\vendor\twilio\sdk\Twilio\autoload.php';
use Twilio\Rest\Client;

For sending the message, we need to create a client object defined in the Twilio SDK, here the required code:

    $sid = 'YOUR ACCOUNT SID';
    $token = 'YOUR AUTH TOKEN';
    $client = new Client($sid, $token);

    //Use the client to do fun stuff like send text messages!
    $client->messages->create(
    //the number you'd like to send the message to
        'TO PHONE NUMBER',
        array(
        //A Twilio phone number you purchased at twilio.com/console
            'from' => 'FROM PHONE NUMBER',
            'body' => 'TEST MESSAGE'
        )
    );
 

NOTE: The from is a phone number that you will need to purchase in your twilio.com/console. Remember that you cannot send SMS with test SID and AUTH token even if you have purchased a phone number. You need actual production sid and token with the number that you bought for the SMS to be sent to an actual number.
That's it, this is all that is required for using the Twilio API for message sending, you can use this for OTP verification, SMS notifications and much more. It's pretty straight forward, if you have any problems feel free to put them in the comment section below. Happy Coding!

Sunday

StaggeredGridLayoutManager with RecyclerView in Android - Tutorial | Pinterest like UI

Vishal Shrestha
We have previously seen how we can create Grids in RecyclerView using GridLayoutManager. You can check out that tutorial/example here: GridLayoutManager with RecyclerView.
In this tutorial we will learn how we can use the StaggeredGridLayoutManager with RecyclerView in Android to create Grids of unequal size.

Staggered-Grid-Layout-in-RecyclerView
Staggered Grid Layout in Pinterest


We are trying to achieve a layout design like Pinterest which you might be familiar with. By using the StaggeredGridLayoutManager with RecyclerView in Android, we can easily achieve the desired layout. Our RecyclerView will look like this at the end:


Here are the prerequisites for successfully creating the app described in this tutorial:
0. An internet connection. Duh! :D
1. Android Studio, get it here:
Android Developer website.


We will go over the following things in this tutorial:

1. Set up Gradle Dependencies for using RecyclerView and CardView.
2. Create an Activity Layout with RecyclerView as a ChildView.
3. Create a Layout that will be used as a Grid in the RecyclerView.
4. Create an Activity class where we will have majority of our code.
5. Create and Adapter and ViewHolder for our RecyclerView.
6. Select the Images to show in the Grids of RecyclerView.
7. Set up the RecyclerView.

Okay, so lets begin with creating the Staggered Grids in RecyclerView. You can also check out the video tutorial:

1. Set Up Gradle Dependencies

First thing that we need to do is to set up dependencies. This allows us to use RecylerView. If we don't use this dependency then we won't be able to use RecyclerView. Open your App level Gradle file(build.gradle(Module: app)), it is inside the App folder in Project view of Android Studio and listed inside Gradle Scripts in Android View. Include the dependencies to use CardView and RecyclerView, copy the following lines inside the dependencies section:

compile 'com.android.support:recyclerview-v7:26.+'
compile 'com.android.support:cardview-v7:26+'

You can check out the latest versions of support library packages here: Support Library Packages


2. Create a Layout with RecyclerView

For this tutorial, we will name this file: activity_staggered_view.xml. The layout is very simple, we will create a LinearLayout as Root layout and then have a RecyclerView inside it. Here's the code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvMain"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

3. Create a Layout to be used as a Grid

Now that we have created our layout, we well create the layout out of a single grid. The Grids in out RecyclerView will look like how we define it now. For this project, we will create a simple layout with an ImageView at the top and textView below it. We will just show pictures with captions below them as the grids in our layout. The layout is very simple and self explanatory, here's the code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="4dp"
    app:cardUseCompatPadding="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/ivImage"
            android:scaleType="fitXY"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/tvCaption"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

</android.support.v7.widget.CardView>


We've used cardView as the root because we want our images and text inside curved cards similar to that of Pinterest layout. The parameters cardCornerRadius is used to define how much we want our cards to be rounded at the corners. CardUseCompatPadding defines is for the backward compatibility for deviecs lower than Lollipop.
In the LinearLayout we have defined orientation to be vertical. In the ImageView, we have ScaleType set to FitXY in the ImageView as it allows the image stretch and occupy all the available space. Finally, we have a TextView below the ImageView. We will display the caption in this TextView.

4. Create a Java Class to handle RecyclerView.

This is the class where we make it all work. Lets name the java class ActivityStaggered and in the onCreate set the content view to our activity_staggered_view.xml and create reference to the RecyclerView. Here what the code in ActivityStaggered method upto now:

RecyclerView recyclerView;

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

        recyclerView = (RecyclerView) findViewById(R.id.rvMain);
    }


In the next steps we will an Adapter and ViewHolder for the RecyclerView that defines what to display in the RecyclerView.

5. Create a RecyclerView Adapter and ViewHolder.

Create a nested class called GridHolder. It should extend RecyclerView.ViewHolder. Create a default constructor and create references to ImageView and Text that will be populated as the Grid or our RecyclerView. Here's the code for GridHolder Class:

private class GridHolder extends RecyclerView.ViewHolder {

        ImageView imageView;
        TextView textView;

        public GridHolder(View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.ivImage);
            textView = itemView.findViewById(R.id.tvCaption);
        }
    }


Now, let us create the Adapter for our RecyclerView. The Job of adapter is to create and bind data to view that correspond to each item in our Data-set.
Create a nested class again. I've called it GridLayoutAdapter. It should extend RecycerView.Adapter.
Here's what the Adapter Class look like at the moment:

private class GridLayoutAdapter extends RecyclerView.Adapter<GridHolder> {

        @Override
        public GridHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return null;
        }

        @Override
        public void onBindViewHolder(GridHolder holder, int position) {
        }

        @Override
        public int getItemCount() {
            return 0;
        }
    }
    }

This is not doing anything at the moment, to this adapter we need to pass the data that we will be displaying in the Grids of our RecyclerView. We will just show Images and then display the item count as the caption. So create a bitmap array and a constructor. We will populate the Bitmap array in the constructor. Include the following inside the GridLayoutAdapter:

  Bitmap[] bitmaps;

        public GridLayoutAdapter(Bitmap[] bitmaps) {
            this.bitmaps = bitmaps;
        } 


Now, we need to display the layout that we had created with CardView and TextView in Step 3 as the Grid of the recyclerView. We do it inside the onCreateViewHolder method of the Adatper. Here's the updated onCreateViewHolder method.

@Override
        public GridHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(ActivityStaggered.this).inflate(R.layout.staggered_row, parent, false);
            return new GridHolder(view);
        }

Finally, we will need to figure out what data to display in which Grid. This is the Data Binding part. It is done inside the onBindView Holder method. The GirdHolder and current position is passed as the parameter to this method. We will set the ImageView and TextView of the holder in this method. Here's the updated Code:

 @Override
        public void onBindViewHolder(GridHolder holder, int position) {
            holder.imageView.requestLayout();
            holder.imageView.setImageBitmap(bitmaps[position]);
            holder.textView.setText("Caption: " + position);
        }
Finally, we have the getItemCount method, it return the number of items to be displayed in the RecyclerView. In our case it's bitmaps.length. Here's the updated of getItemCount:

@Override
        public int getItemCount() {
            return bitmaps.length;
        }

6. Setting up the Images we need to display.

We are almost done now! we just need the images we need to display and set the adapter to recyclerView. In the drawable folders inside res folder, I have added some images that will be displayed in the Grids of RecyclerView. Let's create a method called setUpBitmaps() that return an array of Bitmaps.

private Bitmap[] setUpBitmaps() {
        Bitmap[] bitmaps = new Bitmap[10];
        bitmaps[0] = BitmapFactory.decodeResource(getResources(), R.drawable.icon_1);
        bitmaps[1] = BitmapFactory.decodeResource(getResources(), R.drawable.icon_2);
        bitmaps[2] = BitmapFactory.decodeResource(getResources(), R.drawable.icon_3);
        bitmaps[3] = BitmapFactory.decodeResource(getResources(), R.drawable.icon_4);
        bitmaps[4] = BitmapFactory.decodeResource(getResources(), R.drawable.icon_5);
        bitmaps[5] = BitmapFactory.decodeResource(getResources(), R.drawable.icon_6);
        bitmaps[6] = BitmapFactory.decodeResource(getResources(), R.drawable.icon_7);
        bitmaps[7] = BitmapFactory.decodeResource(getResources(), R.drawable.icon_8);
        bitmaps[8] = BitmapFactory.decodeResource(getResources(), R.drawable.icon_9);
        bitmaps[9] = BitmapFactory.decodeResource(getResources(), R.drawable.icon_10);
        return bitmaps;
    }

Now we have everything we need, The RecyclerView, The ViewHolder, The Adapter and The Data that needs to be display. On to the next step!

7. Setting Adapter to RecyclerView.

We are one step from our StaggeredView in RecyclerView. We just need to put everything that we have coded together. First or all, In our onCreate we will call the setUpBitmaps method that we had just created in the previous step. Then we need to set the StaggeredLayoutManager to RecyclerView. Then finally create the Instance of our GridLayoutAdapter and the bitmaps to Adapter and Set the adapter to our RecyclerView. Here's the updated onCreate method:

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

        recyclerView = (RecyclerView) findViewById(R.id.rvMain);

        Bitmap[] bitmaps = setUpBitmaps();
        recyclerView.setAdapter(new GridLayoutAdapter(bitmaps));
        StaggeredGridLayoutManager mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(mLayoutManager);
    }


We are now done, just add the Activity to Manager and set it's category as launcher. Include the following code inside the application tags:
 <activity android:name=".ActivityStaggered">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

We are now done. You can build and run the project and you will see a Staggered Grid Layout, just like pinterest. Enjoy! Drop any question you have in the comment section below. Happy Coding.

Wednesday

Login with Facebook in Android App - Tutorial & Source Code

Vishal Shrestha
integrating-facebook-login-with-android-app

If you have an app that required user login, providing Facebook login in your Android App can be an easy and convenient way for both your user and you to implement login. Now a days we can see lot of web and mobile apps provide an option to Login with Facebook along with the general email and password login. Most people already have a Facebook account and it's easy to just login using Facebook rather than to first register using email and password. This has become more of a common trend because of how easy Facebook has made integrating Facebook Login in your Android App or any app for that matter. So integrating Facebook Login in you App is a win-win situation for both you and your users.
Let's begin with latest Facebook's SDK for Android, it should take only a few minutes to add this feature to your app. After the basic login, we will also see how we can get the Facebook Profile Picture in our Android app and other profile details like email, date of birth, name and more.

This we will cover in this tutorial:
  1. Creating a new project and registering it in Facebook Developers for Facebook Login.
  2. Integrate Facebook Login in our Android App.
  3. Get User profile detail like User ID, Profile Picture, Email, First Name, Last Name and more.
Note: By Default, when you perform Facebook Login in you Android App, the you can access some details like :  id, cover, name, gender, profile picture and few more. You don't to do any more requests to get the mentioned details, however if you need to access other details like Email you need to define those properties while you login, so that Facebook can ask if you want to allow an app to access those properties. You'll notice in our app that we explicitly define we need Email, so that Facebook can let you know the app will access your Email. You can check out more details in Facebook's official Page: Facebook Login Permissions

Pre-requisites:
  1. A Facebook Account to test login.
  2. Installed Android Studio on your laptop or PC.
  3. An Android Device.

So let's begin!

Adding Facebook Login to our Android App:

1. Create a new Android App.

First of all, let's open up Android Studio and create a new App. Let's call the app myloginapp. After the app is created we don't need to write any code at the moment. Just keep in mind or copy the package name from Manifest file or App level Gradle file. We will need the package name of the name when we are registering the App for Facebook Login.

2. Add the App in Facebook developer page.

Now that we have our Android App's package Name, we can go to Facebook Developers Page and Register our app and integrate Facebook Login. Go to: Facebook for Developers You'll see a page similar to this:
Facebook-for-developers-page
Register Android App for Facebook Login

Now click on the create new app button and enter the package name of your Android App. It will show a warning that the App cannot be found on the Play Store, click on add the app anyway as we are just building our Android app. Now we have successfully added our Android App for Facebook Login, we just need to add hash, we'll do that is the following sections.

3. Add necessary Dependencies.

Now if you scroll down you'll find adding dependencies section like this:
Required-Dependencies-for-Facebook-Login-in-Android
Facebook Dependencies for Android App
We need to include these dependencies to use the Facebook SDK for Android. The Facebook SDK contains methods and callback that makes Facebook login integration very easy in an Android App. Add mavenCentral() in project level repositories section and and the dependency "compile 'com.facebook.android:facebook-android-sdk:[4,5)'" in App Level Gradle File. You Project level Gradle file should look like this: And App level Gradle file should look like this.

4. Add App ID to strings.xml and edit Manifest file.

Now you'll need to add your Facebook App Id and protocol scheme in strings.xml, inside values folder. If you scroll down on the developer's page you can find you APP ID and Protocol Scheme. After adding the dependencies, you will need to add you APP ID in strings.xml inside values folder. App ID is unique for each app and it will identify your Android App uniquely.
Facebook-App-id-in-Manifest-file
Facebook App ID
Copy them and paste it in your strings.xml. If you have strings.xml corresponding to multiple languages, paste it in all the strings.xml. Now open you manifest.xml file. We need to add the internet permissions for obvious reasons and also meta-data required for Facebook Login, do not forget this as the Login won't work without this. So add internet permission: "<uses-permission android:name="android.permission.INTERNET" />" As you're app will need Internet connection for Login. Finally you'll need to add a meta-data and the default FacebookActivity. You can copy the meta data from the code below or Facebook Developers page. The Final manifest.xml should look like this:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.thecodecity.myloginapp">

    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <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" />
    </application>

</manifest>

5. Generate and add Key Hash.

Now scroll down on the Facebook Developers page and you'll see a section that looks like this:
Associating-Android-App-Package-Name-with-Facebook
Associating Package Name
This is the Final Part of App registration. We can start coding after this. Enter your package name that you had entered earlier in step 2. In the default Activity class name, enter your package name followed by .MainActivity
We don' have an activity created yet so now we'll have to name our launcher Activity MainActivity. Finally, if you scroll down a bit more you'll see a section that requires Key Hash, for development you'll need to get your debug key hashes. Use the following commands to get key hashes.
On Windows: keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64
On Mac: keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64
In windows the HOMEPATH is usually C:/Users/Username.
If you are having problems like Command keytool not recognized, you'll need to go to your Java installation directory and run the command from inside the bin folder. If you are having problems with the ssl command, you'll probably need to install SSL, refer here if you have problem with SSL command: OpenSSL Issues.

6. Create Facebook Login Activity Layout.

Now finally we can do some code. We have successfully registered our Android App to Facebook, added the required dependencies and modified the Manifest file appropriately. Now let's write some code. Switch to Android Studio and create a new layout file. Name it activity_main.xml. We will add the default Facebook Login button provided by Facebook Android SDK. The Default Facebook Button looks like this:
Facebook-Login-Button-For-Android-App
Default Facebook Login Button for Android app
The Layout is pretty simple and should look like this: main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Connect with FB"
        android:layout_marginBottom="30dp"
        android:layout_marginTop="30dp" />

</LinearLayout>


The default text on the button is Connect with Facebook. To change the text on the Button we need to add this in LoginButton:
facebook:com_facebook_login_text="Your Login Text"
To change the Text for logout add the following code to the button facebook:com_facebook_logout_text="You Logout Text"

7. Create Facebook Login Activity Java File.

Now Create a new java file and name it MainActivity.java. We will do following things in this class:
  • Add Reference to the Facebook Login button.
  • Initialize a callback Manager to get Login Request Result.
  • Register the callback Manger with Facebook Login button.
  • Call the Callback Manager in onActivityResult.
    Here's what you MainActivity.java should look like:

public class MainActivity extends AppCompatActivity {

    LoginButton loginButton;
    CallbackManager callbackManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setReadPermissions("email");
        callbackManager = CallbackManager.Factory.create();
        // Callback registration
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                // App code
                Log.d("mylog", "Successful: " + loginResult.getAccessToken());
                Log.d("mylog", "User ID: " + Profile.getCurrentProfile().getId());
                Log.d("mylog", "User Profile Pic Link: " + Profile.getCurrentProfile().getProfilePictureUri(500, 500));
            }

            @Override
            public void onCancel() {
                // App code
            }

            @Override
            public void onError(FacebookException exception) {
                // App code
                Log.d("mylog", "Successful: " + exception.toString());
            }
        });
    }

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

Now if the Facebook Login is successfully added, you should be able to see Access token, User ID and Link to Facebook's Profile Picture in the log.The code is pretty simple, we are just getting reference to Facebook login button then setting email read permission and the registering the callback manager. Don't forget to include the onActivityResult, as that part triggers the callback manager. If you just want a secure login, then we are done, we've successfully integrated Facebook Login to our Android App.

8. Perform Graph Request to get User Details like Email and Birthday.

We now have successfully logged in, but what if we need more user details. It's always good to greet the user with a Happy Birthday message in your app. So in order to get more details, we utilize the graph request feature of the Facebook SDK. It's pretty simple you just define what you need to read from the Facebook Profile of the User and execute the request. Add this performGraphRequest method to you MainActivity.java and call it from the onSuccess method of the FacebookCallback that you had registered with Facebook Button in the previous step: Here's the performGraphRequestMethod:

private void performGraphRequest(LoginResult loginResult) {
        GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject json, GraphResponse response) {
                // Application code
                if (response.getError() != null) {
                    System.out.println("ERROR");
                } else {
                    System.out.println("Success");
                    String jsonresult = String.valueOf(json);
                    Log.d("mylog", "JSON Result" + jsonresult);

                    String fbUserFirstName = json.optString("name");
                    String fbUserEmail = json.optString("email");
                    String fbBirthday = json.optString("birthday");
                }
                Log.v("FaceBook Response :", response.toString());
            }
        });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,email,gender, birthday");
        request.setParameters(parameters);
        request.executeAsync();
    }

So we are requesting more of the user details when the user is successfully logged in to your app using Facebook. Here's the performGraphRequest method: We are done, now just run the App in your Android Phone and test it. You should be able to see the user details in the Logs. Use it creatively. This marks the end of this tutorial, if you have any problems just let me know in the comments below, excited to see what you build! Happy Coding.
Download the full source code: Facebook Login Integration in Android App.

Saturday

Firebase Cloud Messaging (Notifications) in Android App full tutorial

Vishal Shrestha
Firebase is a valuable tool for developers that helps you to integrate many services like cloud messaging, authentication, realtime database, storage, crash reporting and much more . You might have already used some services from the vast pool of services that Firebase provides, and in this post we will discuss how we can add our project to Firebase and Integrate it's cloud messaging service in our Android App. Topics discussed in this tutorial are:
  1. How to add an Android Project to Firebase Console.
  2. How to Integrate Firebase Services(Cloud Messaging)in our Android app.
  3. How to Send Notification to the app from Firebase console.
  4. How to handle Received notification and Notification data in our app.
The first step is to create a project in Android Studio and add it to Firebase Console. So let's get started:
If you already have an Android Project in which you want to add Firebase, you can skip the section below that shows creating a new project in Android Studio. For beginners, here's how you create a project:


You can also check out the our YouTube tutorial here: Integrating Push Notifications in Android using Firebase Cloud Messaging.
Creating a new project in Android Studio:
  1. Open Android Studio then from the Navigation Menu select File->New->New Project. 
  2. Name the new project named FirebaseRealtime and click next. 
  3. Now select a minimum SDK version of your choice, I've selected 5.1. 
  4. After a minimum SDK selection click on next and select Add no Activity and click finish. You've successfully created an Android Project.


Adding the project to Firebase

Once you have your project ready, It's time to add the project to firebase. Open the app-level gradle file of your project and copy the application package name. We will use it to add our project in Firebase. Check the highlighted section in the Image below for reference:


In the image above, the application package name is is com.thecodecity.firebaserealtime. Copy the package name and go to Firebase Console. You can login with your Gmail account.
Once you are logged in you should see a screen like this:

Adding-new-project-to-firebase


Now click on add project and enter any name and click next. You have your project ready. Now you should be in your project console and it will look similar to this:

firebase-console-for-new-projects

Notice the scroll bar at the left side, it contains many options and once you scroll down you'll see a notifications option. Click on it, a dialog box will pop up asking for package name, app nickname and SHA1. It should look similar to this:

Adding-package-name-for-firebase-cloud-messaging

Everything except the package name is optional. Now paste your package name that you had copied earlier and click on register app. Now you should see another dialog with option to download json. Download the json file and copy it in the app directory of your project.

Integrating Firebase in Android App

Now that we have added the Json file in our project and added our app in Firebase console, It's time to integrate Firebase in our Android app. First of all we need to add dependencies so that we can use classes and Methods provided by Firebase. In your project level Gradle file add the following dependency as highlighted in the figure below.
classpath 'com.google.gms:google-services:3.1.0'

Firebase-project-level-dependency

Now in your app level Gradle file, add the following dependency as shown in the figure below:
compile 'com.google.firebase:firebase-messaging:11.0.2'
Firebase-app-level-dependency

Now add this: apply plugin: 'com.google.gms.google-services' to the bottom of the file as shown in the image above.
Voila, finally we are now ready to write some code!
We need to create two services, one to get the refreshed token and other to handle notification that the app will receive. The refreshedToken is actually a device registration ID that Firebase generates that uniquely identifies a device. It can be used to send notification to a particular device from the vast pool of devices in which your app is installed.
Let's get started and create the first service. Name it MyFirebaseInstanceIDService.java. Here's the code:

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    String refreshedToken;

    @Override
    public void onTokenRefresh() {
        Log.d("mylog", "Inside on token refresh");
        //Getting registration token
        refreshedToken = FirebaseInstanceId.getInstance().getToken();
        //Displaying token on logcat
        Log.d("mylog", "Refreshed token: " + refreshedToken);
    }


In the code above we are not doing anything important, just displaying the token in the log. In real world applications it can be stored in a database in a server and later it may be used to send individual personalized notification to the device. The Token is refreshed only once when the app is installed in the device. So you will not be able to see this log more than one unless you uninstall and reinstall your app or clear the data of your app from settings. You can later access this token using: FirebaseInstanceId.getInstance().getToken();

Now let's create our second service, name it MyFirebaseMessagingService.java. Here's the code for the class:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
        Log.d("mylog", "From: " + remoteMessage.getFrom());

}


In the onMessageReceived method, we get a remoteMessage object that contains notification details like title, body and data payload. We will discuss it in detail in the next section. However our app is ready to receive notifications.

Receiving Notification and Data Payload in App

Till now, our app can just receive notifications without any other data. Now let's do a little more and handle data other than just title and body as well. Keep in mind you can access this data only when you receive a notification when you app is in the foreground. We already have our MyFirebaseMessagingService class, just add the following lines of code in the onMessageReceivedMethod:

// Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d("mylog", "Message data payload: " + remoteMessage.getData());
        }
        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d("mylog", "Body: " + remoteMessage.getNotification().getBody());
            Log.d("mylog", "Title: " + remoteMessage.getNotification().getTitle());
        }

        String message = remoteMessage.getData().get("message");
        Log.d("mylog", "Message Payload: " + message);

        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.putExtra("message", message);
        getApplicationContext().startActivity(intent);



Here, remoteMessage.getNotification().getBody() gets the body of the notification and remoteMessage.getNotification().getBody() gets the title of the notification. Other then that if there is more data, known as data payload we can access it using remoteMessage.getData().get("key"). Data payload is sent in key-value pair and values can be accessed using their key. In the code above, after the value of the key "message" is fetched, we start a new Activity with the message as extra. We don't have that Activity yet, so let's create a new Activity. First let us create a simple XML layout for the Activity. Name the layout activity_main.xml. Here's the layout code:

<?xml version="1.0" encoding="utf-8"?>
<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:gravity="center"
    android:orientation="vertical"
    tools:context="com.thecodecity.firebaserealtime.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Message from Firebase Notification:"/>

    <TextView
        android:id="@+id/tvMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="No Message"
        android:layout_margin="16dp" />

</LinearLayout>


It's a simple layout that contains two TextViews. We will use one of the TextView to display the message sent in the Notification. Now let's create the Activity. Name it MainActivity.java

public class MainActivity extends AppCompatActivity {

    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView)findViewById(R.id.tvMessage);
        String id = FirebaseInstanceId.getInstance().getToken();
        Log.d("mylog", "Token: " + id);
        Intent intent = getIntent();
        if(intent.hasExtra("message")){
            textView.setText(intent.getStringExtra("message"));
        }
    }
}


In this Activity we check the token for the device using FirebaseInstanceId.getInstance().getToken(); and display in in log. Then we check if the intent has an extra called "message". If yes, then we change the content of the textView to that message. When we first open the App, there will be default text shown in the textView but if we send a notification with data that contains the key "message". The message will be shown in the textView. Now we are all done. We just need to add the Activity and the Services that we created in the Manifest file and we are good to go. Put the following lines inside <application> tag:

   <service android:name=".MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>

        <service android:name=".MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


Also add the following permission outside of the <application> tag: <uses-permission android:name="android.permission.INTERNET"/>

We are now done! we can now run our app and test notifications by sending notification from the Firebase notification console. Go to Firebase Console, select your project and scroll the left side bar to the bottom and click on notification. You'll should now see a page similar to this:

Sending-notification-from-firebase-console


The options are self explanatory, the message text is the description part of the notification that is displayed below the notification title, Message label is for you so that you can later find this notification using this label. In the delivery date you can choose to send now or send later on a specified date or time and finally you can choose a package name to which you need to send notification. Now you can scroll down and click send notification and you'll receive notification if your app is in the background. If you were attentive enough to see the advanced options button while scrolling down, clicking on that button will reveal some options looking like this:

Sending-notification-from-firebase-console-advanced-options

The title option is self explanatory, it's the title of the notification that the users will see, Notification channel is a new feature since Marshmallow that allows sending notifications to certain channel within app like sports, news etc. Custom data allows to send extra data that can be retrieved using key value pairs. Try it out, minimize our app and send notifications. Open the app and send notification with key value pairs and you should see the contents of the TextView change. That's it, we have a fully functional app with cloud notification working. We will cover some more advanced stuff with Firebase Cloud Messaging in the next tutorial. If you have any issues, feel free to comment them below. I'll try to solve it to the best of my abilities. Cheers! happy coding.

SOURCE CODE: Firebase Cloud Messaging Android App

Thursday

Send Email from Android App directly without Intent

Vishal Shrestha
Sending Email from an Android app is not difficult if you want to open up another Email App that handles sending the Email. We can just achieve that by adding an ACTION_SEND intent and we can also set content type and use extras such as EXTRA_EMAIL, EXTRA_CC and more. If we start this intent, all the apps that can handle emails such as Gmail app, default Email app will be shown in a chooser dialog if you haven't chosen a default already. Then your user can easily manage the creation and sending of the email from the third party app. But that's not always the case, some times we are required to send an Email from our own App with a fixed Email address to a specific Email address, for example if we need to send a password recovery link on the click of Forgot Password, recovery link to the user should be sent by email from within our app with our own Email Address. In this post we will learn how we can send Email directly from an Android App without and Intent. So let us begin.

sending-emails-directly-from-app
Screenshot of final App of this tutorial

Steps in sending Email from Android App directly without Intent: 

 

  • We require 3 jar libraries for allowing us to send Emails, download the three libraries (LINK BELOW)
  • We create a JSSEProvider class.
  • We create a MailSender class that handles Authentication for our Email and sends Email directly without intent.
So now that we have the steps laid out, let's dig deeper on how to send Email Directly form our App, here's a sample video of the Email app that we will create:


Step 1
First of all download the 3 files- Activation.jar, Additional.jar, Mail.jar.
These are libraries that allow us to send Email in Java.
Once you've downloaded theses files, put it in the libs folder inside your app directory. If you don't have a libs folder inside your app folder, create one and place these files inside the folder.

Step 2
Now that you've copied the files in libs directory, it's time to include those libraries as dependencies. You'll need to do some changes in the app level Gradle file.  Add the following lines in you dependencies section:

compile files('libs/activation.jar')
compile files('libs/additional.jar')
compile files('libs/mail.jar')

Now you are done with libraries part and are ready to code the Email Sender App.

Step 3
Create a new class called JSSEProvider it should extend Provider class. JSSE provides a framework and an implementation for the SSL and TLS security and also provides some other functionalities like encryption and more. You can learn more about it here. Now add the following code in the class. Import all the required classes:


public JSSEProvider() {
        super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
        AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
            public Void run() {
                put("SSLContext.TLS",
                        "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
                put("Alg.Alias.SSLContext.TLSv1", "TLS");
                put("KeyManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
                put("TrustManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
                return null;
            }
        });
}
 


Step 4
Create a class that extends javax.mail.Authentication. I've called it Gmail Sender because I'll be sending Email from one of my Gmail account. Now add the following code in the class:

 private String mailhost = "smtp.gmail.com";
    private String user;
    private String password;
    private Session session;

    static {
        Security.addProvider(new JSSEProvider());
    }

    public GMailSender(String user, String password) {
        this.user = user;
        this.password = password;

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", mailhost);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");

        session = Session.getDefaultInstance(props, this);
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }

    public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
        try{
            MimeMessage message = new MimeMessage(session);
            DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
            message.setSender(new InternetAddress(sender));
            message.setSubject(subject);
            message.setDataHandler(handler);
            if (recipients.indexOf(',') > 0)
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
            else
                message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
            Transport.send(message);
        }catch(Exception e){
            Log.d("mylog", "Error in sending: " + e.toString());
        }
    }

    public class ByteArrayDataSource implements DataSource {
        private byte[] data;
        private String type;

        public ByteArrayDataSource(byte[] data, String type) {
            super();
            this.data = data;
            this.type = type;
        }

        public ByteArrayDataSource(byte[] data) {
            super();
            this.data = data;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getContentType() {
            if (type == null)
                return "application/octet-stream";
            else
                return type;
        }

        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(data);
        }

        public String getName() {
            return "ByteArrayDataSource";
        }

        public OutputStream getOutputStream() throws IOException {
            throw new IOException("Not Supported");
        }
    }


Now we have all the required this are we are ready to send Email from our app. We will just create one method in our Activity and call it whenever we need to send the Email to the User. This method will contain your Email Address, your password so you can be authenticated and the email address of your recipient. Let's call this methods sendMessage():

private void sendMessage() {
        final ProgressDialog dialog = new ProgressDialog(ActivityMain.this);
        dialog.setTitle("Sending Email");
        dialog.setMessage("Please wait");
        dialog.show();
        Thread sender = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    GMailSender sender = new GMailSender("youremail", "yourpassword");
                    sender.sendMail("EmailSender App",
                            "This is the message body",
                            "youremail",
                            "your recipient's email");
                    dialog.dismiss();
                } catch (Exception e) {
                    Log.e("mylog", "Error: " + e.getMessage());
                }
            }
        });
        sender.start();
    }


Finally we have our app ready and we can call this method whenever we need to send the Email directly from the app without any intents. You can find the full source code below, Cheers!

NOTE: Gmail has disabled logging in to accounts by third party apps. You need to disable this feature of Gmail and allow logging in from any app otherwise you won't be able to login and Emails won't be sent from your account.

Full source code for Email Sender App:Download Email Sender


Coprights @ 2017 | The Code City by Vishal Shrestha Vishal Shrestha