Now you can Subscribe using RSS

Submit your Email

Saturday

Android RecyclerView Row Slide in Animation on Scroll

Vishal Shrestha
Animations in your Android App have a huge impact on how the user perceive your app. Creating Animations have been constantly simplified with newer APIs that Google provides. Feel free to check out our tutorial on enabling default Animation of visibility changes. Now, on to the matter at hand: Animating the rows of RecyclerView when Scrolled.
You might have seen the slide in from right animation in the Official Android Apps from Google like Google Plus or Google News stand, it looks very intuitive and pleasing. Be joyful because implementing that slide in animation in your own Apps' RecyclerView is very easy and can be done in just around 10 lines of code(5 Lines of Java, 5 Lines of XML)! So lets get started:



Slide in Animation on Scroll in RecyclerView
  1. First of all we will create a slide in Animation in XML that we will use.
  2. In RecyclerViews' bindViewHolder we will set this as the Animation for each view.

1. Creating the Slide in Animation in XML:
Right click on your resources folder and create a new XML resource, select the resource type as Animation and name the file slide_in_right. Then just add the following code in the file:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="100%p"
        android:toXDelta="0" />
</set>


We are just defining the animation that will slide our row view from right to left. 100%p means the row will slide in from where the parent ends. 0 mean its ending x position will the 0.

2. Using the slide in animation in onBindViewHolder
Now that we have already defined our animation, we just need to apply in to our rows of the recyclerView. We can easily do that whenever we need to bind new rows to the RecyclerView. Add the following code in onBindViewHolder.
if (position > lastPosition) {
            Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.slide_in_right);
            viewToAnimate.startAnimation(animation);
            lastPosition = position;
}

This code just checks if the position of the row to be displayed is greater that the last row that has been already displayed, if so we just apply our animation to the view. Here lastPosition is a global variable that is initially set to -1 and we can also set the animation variable as global variable depending on your requirements.

We are done! now just add the changes mentioned above to your code, run you app and see beautiful slide in animations in the rows of your RecyclerView whenever you scroll the recyclerView. Feel free to let me know if you have any issues.

Thursday

Animate View on Visibility (Visible - Gone) Changes Android Example

Vishal Shrestha
Animations can separate your app from normal "Just Functional" app and give you app a more polished feel. There are a lot of options how you can show animations on Android, however there is a very easy way to animate layout changes that will make your app look and feel better and more natural. 
Android has some predefined animations that your app can use whenever you have to make change to your app's layout. The layout changes can be setting the visibility of a view to hidden or visible, or when you add a new view. You just need to define an Attribute in the layout that tell the Android system to show animations for these layout changes, and your app will show system-default animations whenever there are layout changes. Check the Gif below for example:

visibility-gone-visible-default-animation
Default Animations in Android


Okay, no more talking, you just need to add the following tag in your root layout:
android:animateLayoutChanges="true" 

Note: You can also do it completely programmatically with the XML, that discussed at the end.
Now don't go running to build your app and see those fluid animations, unless you want to be disappointed and come back to this tutorial and continue it. Setting the animateLayoutChanges property is important, but you also need the following code to make it all work,

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
  ((ViewGroup) findViewById(R.id.llRoot)).getLayoutTransition()
          .enableTransitionType(LayoutTransition.CHANGING);
}
 
We are now done, findViewById refrences the root layout inside which you want to show animations. Now is the time you can build and show or hide some views and test if this works or not! It will work. So wasn't that easy? Of course you can have you custom animation and not the default changeBounds and Fade animations, but for simple Visibility the default ones are the best in my opinion.
In case you want to show your custom animations, you need to create a LayoutTransition object and supply it to the layout using the setLayoutTransition() method but that the code for some other day!

Also, if you are not interested in XML, you can also apply the same animations when there are layout changes using the beginDelayedTransition method. This method was added in API level 19 so make sure the device satisfies the API level before you use this code:

if (Build.VERSION.SDK_INT >= 19) {
                TransitionManager.beginDelayedTransition((ViewGroup) yourViewOnWhichAnimationNeedsToBeShown.getParent());
            }

This is it! Now your app will show animations on layout changes, show whenever the visibility of your views is set to Hidden or Visible, they are handled gracefully, 2 minutes of your time for better UI and UX. Let me what you think below. Cheers!
Also don't forget to check out the RecyclerView Slide in Row Animation Tutorial. Have animations in your RecyclerViews in just 2 Minutes!

Sunday

Fonts in XML | Custom Fonts in Android Support Library

Vishal Shrestha
Finally, after years of dreaming and praying external fonts are fully supported in Android. By fully I mean you can use it directly in XML, add them to styles, create your own font family. Have same fonts through out the app. It is great! Yes, I am enjoying every bit of this easy font styling instead of having to write a custom class extending required view just to have the font you like, oh what a pain it was! I am happy and this post will make you happy, so lets dive right into code. Yeaaahhhh! The scream of joy!
No more of this stupid method: Custom Fonts In Android Using Custom Class.

different-fonts-letters
Just Some Random Fonts


Custom Fonts in Android
Since Android 8.0, fonts in XML has been introduced. It means fonts can be used as resources. Just add the font file in font folder in your resources directory. Alright people, let's get going. Open your resources folder, create a new folder font in it. Inside it just copy all the fonts you want. For this project I've added montserrat fonts. I like them they are sexy just like myself. HaHa. And now you can just create Styles for your Android App and use the style where you want. For example, create a style like this:

<style name="AccentTitleTextStyle" parent="AppTheme">
        <item name="android:textSize">@dimen/title_text_size</item>
        <item name="android:fontFamily">@font/montserrat_bold</item>
        <item name="android:textColor">@color/colorAccent</item>
</style> 


Now all you need to do is just use this style whereever you want through-out your Android app provided you have added montserrat_bold font in your font folder inside resources.
If you want a default font through out an Android App without applying to every single view, then you can just add the font in your default App Theme like this:

<!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:fontFamily">@font/montserrat_bold</item>
    </style>


Now you'll have the font mentioned in fontFamily property. But this allow only one font, wouldn't it be nice if we could create a Font family and change it just by setting fontStyle property just as we do now with the default Roboto Font? Yes, it would be. And yes we can! Yaaahhhh. Okay come back to earth and create a new XML file in font folder. I'll just call it montserrat as all the fonts I have belong to Montserrat Family. Okay let's go insiiddee the montserrat.xml file:

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <font
        android:font="@font/montserrat_regular"
        android:fontStyle="normal"
        android:fontWeight="400"

        app:font="@font/montserrat_regular"
        app:fontStyle="normal"
        app:fontWeight="400" />

    <font
        android:font="@font/montserrat_light_italic"
        android:fontStyle="italic"
        android:fontWeight="400"

        app:font="@font/montserrat_light_italic"
        app:fontStyle="italic"
        app:fontWeight="400" />

</font-family>


So Simple, now if you use this file as the fontFamily in a style and use that style in views then you can just type fontStyle as italic and your view will use montserrat_light_italic as the style. To use this in Android version as low as 4.1 (API level 16), you need to use a support library >= 26. The app:font lines are so than your fonts can be used in versions lower than API level 26.
This is it. Go, cry tears of joy and use your favorite font in you app!
If you have any issues, feel free to comment below. I'll help, I am happy. :D

Thursday

Android Retrofit JSON API with POST-GET Params Tutorial | Example App

Vishal Shrestha

Welcome fellow Android Developer, in the Retrofit tutorial I will give you an Android example of how you can integrate Retrofit to handle JSON response from a REST API in your Android app.
We will go over the following things in this Retrofit tutorial:
Retrofit
1. Retrofit and Gson Dependencies for Android
2. Setting us Retrofit Client and Interface
3. Create model class for Gson Parsing
4. Creating XML Layout
5. Creating RecyclerView Adapter
6. Creating MainActivity to make Retrofit JSON API calls.
 
Retrofit Android Example
Retrofit is a library for Android developed by Square to perform and handle REST API call in our Android application. Retrofit make it very easy to handle JSON response (or any other structured response) from REST API calls. In this tutorial, our example app will use Gson as converter to directly convert JSON response from our POST/GET calls to model objects. If required, we can add custom converters to Retrofit.
In this Example, we will use jservice API as you don't need any key for that, and it returns JSON response. You can check it out here: JService.
Here's the JSON response that is returned.
Jservice-JSON-Response
Json Response from Jservice API


Using Retrofit in Android App
To use Retrofit, first of all you need to add some dependencies to you app level Gradle file. Add the following dependencies to your Android app:

    //Retrofit, gson
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'

    compile 'com.squareup.retrofit2:retrofit:2.0.2'

    // recycler view
    compile 'com.android.support:recyclerview-v7:26.1.0'


The first two dependency are for Gson converter, we will use Gson as the converter for the response to our Retrofit API calls. The third dependency is for the Retrofit Library itself. The fourth dependency is for RecyclerView as we will display the result from API calls in a RecyclerView. Now we have the necessary APIs for our example app. Let's move to the next section of Retrofit integration in Android app.

Retrofit ApiClient and Retrofit Interface setup
It is recommended that we use a single instance of Retrofit throughout our whole application. So we need a static Retrofit variable. So create a new package, name it network and create a new Java Class inside it. Name the class ApiClient. Here's the code inside ApiClient class:

public class ApiClient {
    public static final String BASE_URL = "http://jservice.io/api/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit == null)
            retrofit = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create()).build();

        return retrofit;
    }
}


Now we need to create an Interface consisting of methods that will have methods for our required API calls. Create a new class inside network package. Name it ApiInterface. Here's the code in ApiInterface:

public interface ApiInterface {
    @GET("random")
    Call<List<QuestionModel>> getRandomQuestions(@Query("count") int count);

    /*
    @FormUrlEncoded
    @POST("login")
    Call<UserInfo> doLogin(@Field("username") String uname, @Field("pwd") String pwd);
    */
}

The @GET annotation is used for get methods,the @Query is used as the parameter name, and then we pass the parameter value after that, i.e int count in the example above. If we call the getRandomQuestions above, it will call an API like: http://jservice.io/api/random/?count=(AnyValueWePassWhileCallingTheAPI). It will return a list of QuestionModel, but now we don't have a question model, so it will be showing error. We will create the models in the next step.
For POST API calls, we can send parameter using the @Field annotation as shown in the code above, the value in @Field annotation is the parameter name and the value is passed after that.
Retrofit provides a number of other options of parameters that we can pass to a method, they are:
    @Body – Sends Java objects as request body.
    @Url – uses dynamic URLs.
    @Header - Sends header values.
      
 Our Retrofit Network classes are done, now let's create the question models.

Create Model Classes for JSON Parsing
Create a new package, name it models. Inside models create a new Java class called CategoryModel, here's the code:

class CategoryModel {
    @SerializedName("id")
    int id;
    @SerializedName("title")
    String title;
    @SerializedName("created_at")
    String created_at;
    @SerializedName("updated_at")
    String updated_at;
    @SerializedName("clues_count")
    int clues_count;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getCreated_at() {
        return created_at;
    }

    public void setCreated_at(String created_at) {
        this.created_at = created_at;
    }

    public String getUpdated_at() {
        return updated_at;
    }

    public void setUpdated_at(String updated_at) {
        this.updated_at = updated_at;
    }

    public int getClues_count() {
        return clues_count;
    }

    public void setClues_count(int clues_count) {
        this.clues_count = clues_count;
    }
} 

Now lets create a class for the actual Question that we will get, create a new class inside models folder, name it QuestionModel. Here the code:
public class QuestionModel {
    @SerializedName("id")
    int id;
    @SerializedName("answer")
    String answer;
    @SerializedName("question")
    String question;
    @SerializedName("value")
    int value;
    @SerializedName("airdate")
    String airdate;
    @SerializedName("created_at")
    String created_at;
    @SerializedName("updated_at")
    String updated_at;
    @SerializedName("category")
    CategoryModel category;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getAnswer() {
        return answer;
    }

    public void setAnswer(String answer) {
        this.answer = answer;
    }

    public String getQuestion() {
        return question;
    }

    public void setQuestion(String question) {
        this.question = question;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public String getAirdate() {
        return airdate;
    }

    public void setAirdate(String airdate) {
        this.airdate = airdate;
    }

    public String getCreated_at() {
        return created_at;
    }

    public void setCreated_at(String created_at) {
        this.created_at = created_at;
    }

    public String getUpdated_at() {
        return updated_at;
    }

    public void setUpdated_at(String updated_at) {
        this.updated_at = updated_at;
    }

    public CategoryModel getCategory() {
        return category;
    }

    public void setCategory(CategoryModel category) {
        this.category = category;
    }
}

Notice that I have not create variables for all the returned data, as I will not be using most of that. You can just create variables for parameters that you are interested from the JSON Response. Also, it's very important to add the @SerializedName annotation as that's used for automatic parsing.

Now since we have everything ready, we just need to call the getQuestions Method and display the data.

Creating the Layout for Retrofit App
Create a new layout resource for the  android app, call in activity_main.xml. 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:padding="16dp">

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

This is pretty simple layout, it just has a RecyclerView that will be used to Display the data that we will get from the API.
Now we will create a layout for individual row of the RecyclerView. Create a layout, name it question_row. 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="wrap_content"
    android:orientation="vertical"
    android:padding="8dp">

    <TextView
        android:id="@+id/tvQuestion"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Question"
        android:textSize="22sp" />

    <TextView
        android:id="@+id/tvPoints"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:text="200" />
</LinearLayout>


Now let's create an adapter for the RecyclerView to display the data.

Creating RecyclerView Adapter and ViewHolder
Create a new class called QuestionsAdapter, this will be the adapter for our RecyclerView. If you want to know more about RecyclerView, check out this tutorial: RecyclerView.
Here's the code inside QuestionsAdapter:

public class QuestionsAdapter extends RecyclerView.Adapter<QuestionsAdapter.QuestionsHolder> {
    ArrayList<QuestionModel> questionModels;

    public QuestionsAdapter(ArrayList<QuestionModel> questionModels) {
        this.questionModels = questionModels;
    }

    @Override
    public QuestionsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.question_row, parent, false);
        return new QuestionsHolder(view);
    }

    @Override
    public void onBindViewHolder(QuestionsHolder holder, int position) {
        holder.question.setText(questionModels.get(position).getQuestion());
        holder.points.setText(questionModels.get(position).getValue() + "");
    }

    @Override
    public int getItemCount() {
        return questionModels.size();
    }

    public class QuestionsHolder extends RecyclerView.ViewHolder {
        TextView question, points;

        public QuestionsHolder(View itemView) {
            super(itemView);
            question = itemView.findViewById(R.id.tvQuestion);
            points = itemView.findViewById(R.id.tvPoints);
        }
    }
}
 

Now everything is ready, we just need a main activity to call the Retrofit GET method and  display the data in RecyclerView.

Creating MainActivity and Calling Retrofit GET method.
Create a new activity, call it MainActivity. We will call the user the ApiClient that we had created earlier to get a Retrofit instance and then call the GET method to get the details and set the adapter to our RecyclerView and we our done with our Android app with Retrofit API Calls. Here's the code in MainActivity.java:

public class MainActivity extends AppCompatActivity {

    RecyclerView rvQuestions;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rvQuestions = findViewById(R.id.rvQuestions);
        setQuestions();
    }

    private void setQuestions() {
        ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
        Call<List<QuestionModel>> call = apiInterface.getRandomQuestions(5);
        call.enqueue(new Callback<List<QuestionModel>>() {
            @Override
            public void onResponse(Call<List<QuestionModel>> call, Response<List<QuestionModel>> response) {
                int status = response.code();
                ArrayList<QuestionModel> questionModels = (ArrayList<QuestionModel>) response.body();
                setRecyclerView(questionModels);
            }

            @Override
            public void onFailure(Call<List<QuestionModel>> call, Throwable t) {

            }
        });
    }

    private void setRecyclerView(ArrayList<QuestionModel> questionModels) {
        rvQuestions.setLayoutManager(new LinearLayoutManager(MainActivity.this));
        QuestionsAdapter questionsAdapter = new QuestionsAdapter(questionModels);
        rvQuestions.setAdapter(questionsAdapter);
    }
}

 

We are almost done, here's our final project structure:

retrofit-android-json-post-api-example
Retrofit Android Example App
Now we just need to edit the manifest and add our Activity as launcherActivity and add internet access permission to allow Retrofit API calls, here's the manifest.xml:

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

    <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">
        <activity android:name=".models.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


We can now run our App, here's a screenshot:
JSON-response-from-API-call-Android-App
Android App Retrofit Example


We learned how we can integrate Retrofit in our Android app and make GET and POST calls, get JSON Response, Parse it automatically using Gson converter. Retrofit is very helpful and I highly recommend it. Hope this tutorial helped you! Cheers. If you have any questions, feel free to drop them below, I be happy to help.

Sunday

Schedule MySQL Database Backup Automatically using Cron Job - Linux Server

Vishal Shrestha
Database backup is one of the most important tasks of server maintenance. Taking database backup in a Linux server manually whenever we want a backup in not for cools users :D. Database backup should be taken periodically in fixed intervals, and we here like to automate out periodic tasks. In this tutorial we will take a look at Cron Jobs and Crontabs in Linux; and see how we can schedule periodic complete Database backups of our MySQL Databases using Cron.
Alright so let's get into it:

Taking-MySQL-Database-backup-in-Linux-using-Cron
MySQL Database Backup in Linux

1. Install Cron
Cron should be installed as a part of base system, but due to some issues it may not be available for you. Type crontab -a in your terminal and hit enter, if you see crontab command not found then you need to install crontab. If your system is Debian, then you can install Cron using :
sudo apt-get install cron

If you are using a Redhat based system, use:

yum install cronie

Now you should have Cron installed. Let's go to the next step.

2. Setting up Database backup in Crontab
Now that we have installed Cron installed in out Linux system we are ready to schedule the MySQL Database backup
Note: If you are not familiar with Crontab/Cronjobs, I recommend watching our 5 minute tutorial : Cron Job.

Usually, you should open your personal crontab file using crontab -e command, however if you are root user and decide to choose system wide crontab file, you need to edit the crontab file located in /etc/crontab. Whatever you choose to do, you should have crontab file open now. To take backup use the following command:

12 30 * * * username mysqldump -umysqlusername -pmysqluserpwd | gzip >/home/directory/to/backup/db_`date '+\%d-\%m-\%Y'`.sql.gz
The above commands backs up your all databases everyday at 12:30 AM for the user that you entered after -u in the command above. The last part (db_`date '+\%d-\%m-\%Y'`.sql.gz) is the database name. The `date '+\%d-\%m-\%Y'` appends the date to db_ so your database bacakup won't be overwritten, if you create a static name, your latest database back will overwrite previous database backup.

3. More Cron Job Time constraints
Some of the common time constraints that you can add in Cron are:
You can learn about the parameters of Cron job in our tutorial video: Cron Job.
 
Running Cron job Yearly
@yearly /scripts/script.sh

Running Cron job Monthly
@monthly /scripts/script.sh

Running Cron job Weekly
@weekly /bin/script.sh

Running Cron job Daily
@daily /scripts/script.sh

Running Cron job Hourly
@hourly /scripts/script.sh

Running Cron job on Reboot
@reboot /scripts/script.sh

Running Cron job at 5AM Daily
0 5 * * * /bin/sh backup.sh

Running Cron job at 12AM & 12PM Daily
0 12,24 * * * /scripts/script.sh

Running Cron job Every Minute
* * * * *  /scripts/monitor.sh

Running Cron job Every Monday at 2AM
0 2 * * mon  /scripts/script.sh

Running Cron job Every 30 Minutes
*/30 * * * * /scripts/monitor.sh

Running Cron job Every 2 Hours
0 */5 * * * /scripts/script.sh

Running Cron job Every 30 Seconds
* * * * * /scripts/script.sh
* * * * *  sleep 30; /scripts/script.sh

Running Cron job on Selected Months
* * * jan, mar, april, jun * /script/mons.sh

Running Cron job on Selected Days at 3PM
0, 15 * * sun, wed /script/check.sh

Running Cron job on first Sunday of every Month
0 2 * * sun  [ $(date +%d) -le 07 ] && /script/script.sh

Running Multiple Scripts in a Single cron
* * * * * /scripts/script.sh; /scripts/scrit2.sh

So, this is it for this tutorial, you should now be able to backup your MySQL Database using Crontab. If you have any problems, feel free to comment below. Cheers!

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.

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