Android Getting Started with Firebase – Registration and Login (Part 1)

    Firebase is a mobile-backend-as-a-service that provides several features for building powerful mobile apps. Firebase has three core services: a realtime database, user authentication and hosting. With it's Android SDK, you can use these services to build powerful apps without writing a single line of server code.
   Firebase company was acquired by Google in October 2014 and then, at I/O 2016, Google introduced an all new & updated version of Firebase, offering a comprehensive solution for creating a back-end infrastructure for mobile and the web.

Firebase overview

    All main features of Firebase can be seen at the image below:

    All features are available for Android and iOS development, except for Test Lab which is not supported for iOS devices. Some of the features are not supported yet for web applications.
    The Firebase SDK supports programming in C++, Java, JavaScript, JavaScript/Node.js, Objective-C, and Swift. Angular, Backbone, Ember and React are supported through bindings to the database. Google added a number of helper libraries: FirebaseUI, Geofire, Firebase Queue, FirebaseJobDispatcher. Their name indicates what their purpose is. Firebase also supports importing large JSON data sets and integration with ElasticSearch.
    In this post, I will present the way to using "Authentication" feature in Android development. With it, you can create a simple application with login and registration screens and saving all user account to an online database.
    DEMO VIDEO:

Enabling Firebase Authentication

    Firstly, in order to use Firebase in your Android application, please go to it's Homepage and login with your Google account.
    After that, you will see "Get Started for free" button, click it, you will be redirected to this page:
 
    Click at "Create new project" and fill your app information to text fields (Project name, Country):
    Choose Android platform and fill your app package name and finger-print (optional):

    After this step, file named google-service.json will be downloaded to your computer and this is your project page in Firebase:
    Click "Set up Sign in method" to go to Sign In Method tab and enable "Email/Password" entry:
    And we'll have this result:

Android project configuration

    When starting a new Android project, make sure that your app package name is same as defined in the project's page on Firebase (here is info.devexchanges.firebaselogin).
    Put google-services.json file to your app folder:

    Open your project level build.gradle and add Google play services class-path:
dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
   Open application level build.gradle to adding Google play services dependency and at the bottom of file, adding apply plugin: 'com.google.gms.google-services':
dependencies {
    compile 'com.google.firebase:firebase-auth:9.4.0'
}
 
apply plugin: 'com.google.gms.google-services'
   Important Note: Make sure that you have installed Google play services packages in your Android SDK, only then you will be able to sync gradle successfully:

Building the Registration Activity

    In this post, I will present the way to make a sign up screen, users can create their own accounts in your app and data will be saved in Firebase database.
    We use Firebase authentication through FirebaseAuth class. In onCreate() of your Activity, initializing it through this code:
auth = FirebaseAuth.getInstance();
    In registration, FirebaseAuth has an important method which you'll use is createUserWithEmailAndPassword(). When called it, handling registration result (success or failed) by using OnCompleteListener<TResult> interface. Checking it's success or not, only need to override onComplete(@NonNull Task<AuthResult> task) method.
    Source code for registration activity is simple like this:
RegisterActivity.java
package info.devexchanges.firebaselogin;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;

public class RegisterActivity extends AppCompatActivity {

    private View btnLogin;
    private View btnSignUp;
    private ProgressDialog progressDialog;
    private TextInputLayout email;
    private TextInputLayout password;
    private FirebaseAuth auth;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_register);

        //Get Firebase auth instance
        auth = FirebaseAuth.getInstance();

        btnLogin = findViewById(R.id.login);
        btnSignUp = findViewById(R.id.sign_up);
        email = (TextInputLayout) findViewById(R.id.email_field);
        password = (TextInputLayout) findViewById(R.id.password_field);

        //go to Login Activity
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
            }
        });

        //sign up a new account
        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!Utils.hasText(email)) {
                    Utils.showToast(RegisterActivity.this, "Please input your email");
                } else if (!Utils.hasText(password)) {
                    Utils.showToast(RegisterActivity.this, "Please input your password");
                } else {
                    //requesting Firebase server
                    showProcessDialog();
                    auth.createUserWithEmailAndPassword(Utils.getText(email), Utils.getText(password))
                            .addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
                                @Override
                                public void onComplete(@NonNull Task<AuthResult> task) {
                                    if (!task.isSuccessful()) {
                                        progressDialog.dismiss();
                                        Utils.showToast(RegisterActivity.this, "Register failed!");
                                    } else {
                                        Utils.showToast(RegisterActivity.this, "Register successful!");
                                        startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                                        progressDialog.dismiss();
                                        finish();
                                    }
                                }
                            });
                }
            }
        });
    }

    private void showProcessDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Register");
        progressDialog.setMessage("Register a new account...");
        progressDialog.show();
    }
}
    And it's layout (xml) file:
activity_register.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:background="#00BCD4"
    android:orientation="vertical"
    android:padding="@dimen/activity_horizontal_margin">

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="30dp"
        android:contentDescription="@null"
        android:src="@drawable/firebase" />

    <android.support.design.widget.TextInputLayout
        android:id="@+id/email_field"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Email"
            android:inputType="textEmailAddress"
            android:singleLine="true"
            android:textColor="@android:color/white" />

    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/password_field"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:focusableInTouchMode="true"
            android:hint="Password"
            android:imeActionId="@+id/login"
            android:inputType="textPassword"
            android:singleLine="true"
            android:textColor="@android:color/white" />

    </android.support.design.widget.TextInputLayout>

    <Button
        android:id="@+id/sign_up"
        style="?android:textAppearanceSmall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:background="#FFCA28"
        android:text="Register"
        android:textColor="@android:color/black"
        android:textStyle="bold" />

    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:background="@null"
        android:text="Go To Login"
        android:textAllCaps="false"
        android:textSize="15dp" />

</LinearLayout>
    There are some necessary files in this project. Firstly is Utils.java which providing some standardized string methods:
Utils.java
package info.devexchanges.firebaselogin;

import android.content.Context;
import android.support.design.widget.TextInputLayout;
import android.widget.Toast;

public class Utils {
    public static boolean hasText(TextInputLayout inputLayout) {
        return !inputLayout.getEditText().getText().toString().trim().equals("");
    }

    public static String getText(TextInputLayout inputLayout) {
        return inputLayout.getEditText().getText().toString().trim();
    }

    public static void showToast(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }
}
    Then, the login screen is still a blank Activity, I will complete it in Part 2 of this tutorial (coming soon).
LoginActivity.java

package info.devexchanges.firebaselogin;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

public class LoginActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        /**
         * It will be completed in nex post.
         * Coming soon!
         */
    }
}
    Important Note: Never forget to request Internet permission for your application:
<uses-permission android:name="android.permission.INTERNET" />
    I use TextInputLayout to make the text field - a widget from Design support library, so you must add this dependency to your app-level build.gradle:
compile 'com.android.support:design:24.2.0'

Running this application

     To running any application which using Firebase, you should take a glance at the prerequisites in Firebase oficial website:
  • An Android device running Google Play services 9.0.0 or later 
  • The Google Play services SDK from the Android SDK Manager 
  • Android Studio 1.5 or higher An Android Studio project and it's package name.
    In an understandable way, you should run this app in your real device, which usually installed Google Play services. This is output in my Samsung Galaxy Tab 4:
    If registration successful, you'll be redirect to Login screen and the success Toast message is shown:

    If you login to Firebase console, you can see the user created with the email id you have given the android app:
When app has just created: there is no user registered
A new user registered

Conclusions

    Through this post, I hope that you can understanding the overview of Firebase and creating a simple registering screen to get and store data in this online database. Up to next post, I will guide about login screen and get user information from Firebase to displayed it on your Android app. Project source code will also available at the next post!

Android - Facebook Integration Sample: Login and get User Profile

    Social media integration is one of the most popular topics that we can see in applications programming. Like another social networks, Facebook provides powerful API for a lot of platform, including mobiles OS in general and Android in particular. As we can see in many applications which needing user dentifiable information (account),  they allow us to create a new account from Facebook ID (Login with Facebook). By this way, apps will use oAuth to get our public information through connecting and communicating with Facebook SDK.
    Through this post, I would like to present a sample project that by login with your Facebook account process, user can get the profile information responding in Graph API and show data to views.
    DEMO VIDEO:

Register your app


    All apps that use the Facebook SDK must be registered with Facebook. Log in to the Facebook Developers website and click Create a New App in the top right corner. With some simple steps, enter your new app name, select category, platform (Android), app's package name and launching Activity name..., make sure you remember the values you entered.
    Key hashes field will be opened and we must fill it. Launch Terminal (in Mac, Linux) or Command Prompt (in Windows) and type this command:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
    After enter password for Android debug.keystore (default is android), a key hash has been generated:
    Copy and paste it to App register form, make sure Single Sign On is set to Yes and click the Save Changes button. Your app is now registered:
    And our app dashboard will be like this:

Add Facebook SDK to Project

  The Facebook SDK is available on Maven Central. In order to use it, open app/build.gradle and add this dependency (the lastest version of sdk in this article time is 4.7.0):
compile 'com.facebook.android:facebook-android-sdk:4.7.0'

Add the Application ID

    As you can see above, each created app has a it's own ID and we must declared it in Android project. So, open strings resource file (strings.xml) and add app id value:     We need do something in AndroidManifest.xml. First, adding application ID meta-data just above </application> tag:     Define FacebookActivity as another Activity that belongs to our app:     And set Internet permission for app:

Designing project layout

    In project main activity, I put a LoginButton object to connect with a Facebook account after click and after this process, user profile will be get and show to TextView, specially, user profile picture will be show by ProfilePictureView. Our layout file like this:

Programmatically coding


    The SDK needs to be initialized before using any of its methods. You can do so by calling sdkInitialize() method and passing the application's context to it. Put this line in Activity onCreate():
FacebookSdk.sdkInitialize(getApplicationContext());
    After that, initialize an instance of CallbackManager using the CallbackManager.Factory.create() method:
callbackManager = CallbackManager.Factory.create();
    Now, set a call back to handle results of the login attempts, register it with CallbackManager instance above. Implements FacebookCallBack interface, we have ButtonLogin registerCallback:
        btnLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

            @Override
            public void onSuccess(LoginResult loginResult) {
                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {

                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                Log.v("Main", response.toString());
                                setProfileToView(object);
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,gender, birthday");
                request.setParameters(parameters);
                request.executeAsync();
            }

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

            @Override
            public void onError(FacebookException exception) {
                Toast.makeText(MainActivity.this, "error to Login Facebook", Toast.LENGTH_SHORT).show();
            }
        });
    The responding data is in JSONObject, parsing it based on key name and set to views:
private void setProfileToView(JSONObject jsonObject) {
        try {
            email.setText(jsonObject.getString("email"));
            gender.setText(jsonObject.getString("gender"));
            facebookName.setText(jsonObject.getString("name"));

            profilePictureView.setPresetSize(ProfilePictureView.NORMAL);
            profilePictureView.setProfileId(jsonObject.getString("id"));
            infoLayout.setVisibility(View.VISIBLE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    Overriding onActivityResult() to get data in CallbackManager:
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
    Finally, we have full code for main Activity:
package info.devexchanges.facebookintegration;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.facebook.login.widget.ProfilePictureView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    private LoginButton btnLogin;
    private CallbackManager callbackManager;
    private ProfilePictureView profilePictureView;
    private LinearLayout infoLayout;
    private TextView email;
    private TextView gender;
    private TextView facebookName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());

        setContentView(R.layout.activity_main);

        btnLogin = (LoginButton)findViewById(R.id.login_button);
        email = (TextView)findViewById(R.id.email);
        facebookName = (TextView)findViewById(R.id.name);
        gender = (TextView)findViewById(R.id.gender);
        infoLayout = (LinearLayout)findViewById(R.id.layout_info);
        profilePictureView = (ProfilePictureView)findViewById(R.id.image);

        btnLogin.setReadPermissions(Arrays.asList("public_profile, email, user_birthday"));
        callbackManager = CallbackManager.Factory.create();

        // Callback registration
        btnLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

            @Override
            public void onSuccess(LoginResult loginResult) {
                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        new GraphRequest.GraphJSONObjectCallback() {

                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                Log.v("Main", response.toString());
                                setProfileToView(object);
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,gender, birthday");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {
                
            }

            @Override
            public void onError(FacebookException exception) {
                Toast.makeText(MainActivity.this, "error to Login Facebook", Toast.LENGTH_SHORT).show();
            }
        });
    }

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

    private void setProfileToView(JSONObject jsonObject) {
        try {
            email.setText(jsonObject.getString("email"));
            gender.setText(jsonObject.getString("gender"));
            facebookName.setText(jsonObject.getString("name"));

            profilePictureView.setPresetSize(ProfilePictureView.NORMAL);
            profilePictureView.setProfileId(jsonObject.getString("id"));
            infoLayout.setVisibility(View.VISIBLE);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
    Our result after login Facebook and fetching data:

Conclusions

    Through this post, I presented a simple solution to login and get user information from a Facebook account. For further approach, you can go to Facebook Developer site to read more about Android SDK to deep understanding it. By this, you can find out the way to fetch not only user profile but also get the friends list or posting status, sharing link,...to your Facebook wall. Hope you like this topic, finally, you can see my project on @Github and check this link to read about integration Google+, Twitter and Google Play services,...in your Android app.


Integrating with Google Plus (Google+ Login) on Android application

Integrating with Google Plus (Google+ Login) on Android application

    In this small tip, we are going to see how can we use Google Plus API.
    The Google Plus API allows you to connect with more users by integrating public  user information into your Android application. With Google Plus API you can add Google+ sign-In to your Android application and improve registration and sign-in conversion with a fast and secure authentication option for users. After this process, you can get user email, name, profile picture (avatar),...from Google Account served for your own purposes, for example, use this in a account register process.
    This API has some requiments in device hardware and Android SDK version, see Integration Google + Prerequisites for specific details.
Source code now available on GoogleDrive.

1. Enable Google+ API on Google Console

    Firstly, to integration Google+ login in your app, you must Enable this API.
    Step 1: Generate a SHA-1 fingerprint by java keytool
Go to Java JRE installed folder (usally is "C:\Program Files\Java\jre1.8.0_45\bin", open Command Prompt and type following command:
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
After this process, we'll see SHA-1 key like this:
    Step 2: go to Google API console, login with your google account and create a new project.
    Step 3: On the left bar, choose API & Auth entry, click at Google+ API and anabled it:
    Step 4: Choose Credentials from left side bar, and click Create new Client ID Button. A popup appears to create our own ID.
    Step 5: Choose Installed application in Application type entry and fill all form with your data:

    Step 6: After clicking Create Client ID, we'll have result like this:

2. Creating a Project

     Description: In this project, after click at SignInButton of Google+ API, app will redirect to server and get user information after validation process. App will display it to screen.
     Make a simple layout, include a SignInButton and a profile layout in activity_main.xml:
     In order to connect to Google Play Services, we need a GoogleApiClient Object and initialize it when app start:
     Activity must implement 2 intefaces ConnectionCallbacks and OnConnectionFailedListener to "listen" any change from server. In our activity programmatically code, implement these methods: onConnectionFailed()onConnected()onConnectionSuspended():

     The integration process (start with invoking googleApiClient.connect()  and stop when googleApiClient.disconnect() called) should be suitable with activity life cycle, so we implement onStart() and onStop() methods like this:
protected void onStart() {
        super.onStart();
        googleApiClient.connect();
    }

    protected void onStop() {
        super.onStop();
        if (googleApiClient.isConnected()) {
            googleApiClient.disconnect();
        }
    }
     Connect to server and sign in to Google Account with resolveSignInError() method:
/**
     * Method to resolve any sign in errors
     * */
    private void resolveSignInError() {
        if (mConnectionResult.hasResolution()) {
            try {
                mIntentInProgress = true;
                mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
            } catch (IntentSender.SendIntentException e) {
                mIntentInProgress = false;
                googleApiClient.connect();
            }
        }
    }
     After get responding information from Google Play Services, parsing data and display to views:
     /**
      * Getting user's information: name, email, profile picture (avatar)
      * */
     private void getUserInformation() {
        try {
            if (Plus.PeopleApi.getCurrentPerson(googleApiClient) != null) {
                Person person = Plus.PeopleApi
                        .getCurrentPerson(googleApiClient);
                String personName = person.getDisplayName(); // user account name
                String avatarUrl = person.getImage().getUrl(); // profile image url
                String alanguage = person.getLanguage();
                String email = Plus.AccountApi.getAccountName(googleApiClient); // account Email

                //update data to TextViews
                this.userName.setText(personName);
                this.language.setText(alanguage);
                this.email.setText(email);

               //loading image (avatar) to ImageView from URL by Picasso
                Picasso.with(this)
                        .load(avatarUrl)
                        .placeholder(R.mipmap.ic_launcher)
                        .error(R.mipmap.ic_launcher)
                        .into(avatar);

            } else {
                Log.e(TAG, "profile is null");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
     We also provide the way logging out from server and clear account information (after click Log Out Button):
/**
     * Sign out from google account
     * */
    private void signOutGooglePlusAccount() {
        if (googleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(googleApiClient);
            googleApiClient.disconnect();
            googleApiClient.connect();
            layoutAction(false);
        }
    }
     Finally, we have full MainActivity.java code:
package devexchanges.info.googleplus;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;
import com.squareup.picasso.Picasso;


public class MainActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {

    private SignInButton btnSignIn;
    private View btnLogout;
    private TextView userName;
    private ImageView avatar;
    private TextView language;
    private TextView email;
    private ViewGroup profileLayout;

    private static final int RC_SIGN_IN = 0;
    private static final String TAG = MainActivity.class.getSimpleName();

    private boolean mIntentInProgress;
    private boolean mSignInClicked;
    private ConnectionResult mConnectionResult;

    // Google client to communicate with Google
    private GoogleApiClient googleApiClient;


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

        userName = (TextView) findViewById(R.id.username);
        btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
        btnLogout = (View) findViewById(R.id.btn_logout);
        language = (TextView)findViewById(R.id.language);
        avatar = (ImageView) findViewById(R.id.image);
        email = (TextView) findViewById(R.id.email);

        profileLayout = (LinearLayout) findViewById(R.id.profile_layout);

        btnSignIn.setOnClickListener(onLoginListener());
        btnLogout.setOnClickListener(onLogoutListener());

        //initializing google api client when start
        googleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).
                addOnConnectionFailedListener(this).addApi(Plus.API, Plus.PlusOptions.builder().
                build()).addScope(Plus.SCOPE_PLUS_LOGIN).build();
    }

    private View.OnClickListener onLoginListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "login clicked!");
                signInGooglePlusAccount();
            }
        };
    }

    private View.OnClickListener onLogoutListener() {
        return new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signOutGooglePlusAccount();
                Log.i(TAG, "logout clicked!");
            }
        };
    }

    protected void onStart() {
        super.onStart();
        googleApiClient.connect();
    }

    protected void onStop() {
        super.onStop();
        if (googleApiClient.isConnected()) {
            googleApiClient.disconnect();
        }
    }
 
 @Override
    protected void onActivityResult(int requestCode, int responseCode,
                                    Intent intent) {
        if (requestCode == RC_SIGN_IN) {
            if (responseCode != RESULT_OK) {
                mSignInClicked = false;
            }

            mIntentInProgress = false;

            if (!googleApiClient.isConnecting()) {
                googleApiClient.connect();
            }
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        Log.i(TAG, "onConnectionFailed");
        if (!result.hasResolution()) {
            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
                    0).show();
            return;
        }

        if (!mIntentInProgress) {
            // Store the ConnectionResult for later usage
            mConnectionResult = result;

            if (mSignInClicked) {
                // The user has already clicked 'sign-in' so we attempt to resolve all
                // errors until the user is signed in, or they cancel.
                resolveSignInError();
            }
        }

    }

    @Override
    public void onConnected(Bundle arg0) {
        mSignInClicked = false;
        Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();

        // Get user's information
        getUserInformation();

        // Update the UI after signin
        layoutAction(true);

    }

    @Override
    public void onConnectionSuspended(int arg0) {
        googleApiClient.connect();
        layoutAction(false);
    }

    /**
     *showing/hiding Button Login and Profile Layout
     * */
    private void layoutAction(boolean isSignedIn) {
        if (isSignedIn) {
            btnSignIn.setVisibility(View.GONE);
            profileLayout.setVisibility(View.VISIBLE);
        } else {
            btnSignIn.setVisibility(View.VISIBLE);
            profileLayout.setVisibility(View.GONE);
        }
    }

    /**
     * Sign in into google+
     * */
    private void signInGooglePlusAccount() {
        if (!googleApiClient.isConnecting()) {
            mSignInClicked = true;
            resolveSignInError();
        }
    }

    /**
     * Method to resolve any sign in errors
     * */
    private void resolveSignInError() {
        if (mConnectionResult.hasResolution()) {
            try {
                mIntentInProgress = true;
                mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
            } catch (IntentSender.SendIntentException e) {
                mIntentInProgress = false;
                googleApiClient.connect();
            }
        }
    }

    /**
     * Getting user's information: name, email, profile picture (avatar)
     * */
    private void getUserInformation() {
        try {
            if (Plus.PeopleApi.getCurrentPerson(googleApiClient) != null) {
                Person person = Plus.PeopleApi
                        .getCurrentPerson(googleApiClient);
                String personName = person.getDisplayName(); // user account name
                String avatarUrl = person.getImage().getUrl(); // profile image url
                String alanguage = person.getLanguage();
                String email = Plus.AccountApi.getAccountName(googleApiClient); // account Email

                //update data to TextViews
                this.userName.setText(personName);
                this.language.setText(alanguage);
                this.email.setText(email);

               //loading image (avatar) to ImageView from URL by Picasso
                Picasso.with(this)
                        .load(avatarUrl)
                        .placeholder(R.mipmap.ic_launcher)
                        .error(R.mipmap.ic_launcher)
                        .into(avatar);

            } else {
                Log.e(TAG, "profile is null");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Sign out from google account
     * */
    private void signOutGooglePlusAccount() {
        if (googleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(googleApiClient);
            googleApiClient.disconnect();
            googleApiClient.connect();
            layoutAction(false);
        }
    }
}

3. Running application

     In this project, I use Picasso to loading image from URL, so local gradle build file (usally is app/build.gradle) beyond Google Play Service dependency, there must also include Picasso's:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0 rc2"

    defaultConfig {
        applicationId "devexchanges.info.googleplus"
        minSdkVersion 14
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.google.android.gms:play-services:7.5.0' //google play service
    compile 'com.squareup.picasso:picasso:2.5.2' //picasso
}
     Some screenshots for this sample project:

Android Twitter Integration using oAuth

Android Twitter Integration using oAuth

    Android allows your application to connect to Twitter and share data or any kind of updates on twitter. Integrating Twitter with your Android Application is essential to attract more users and it makes users to login with their Twitter Account, also you can use their Twitter Profile Image with your App.
    In this tutorial, I will present how to integrate Twitter in your android application using twitter oAuth procedure with a Java Twitter library called Twitter4J.

1. Integration Twitter SDK

    Create a new application using Twitter SDK by go to dev.twitter.com/apps/new. Login with your account and you will see this form:
    After filling all forms (at call back URL you can give a dummy url) with your informations, Twitter will notice that you created a new project successful. Select Settings tab, select your permission (access type):
    Go to Keys and Access Tokens tab, you will see Consumer Key and Consumer Secret key:
Copy them and we'll use in Android project.

2. Download and install library

 
    There is unofficial Twiter SDK library is Twitter4J. It is widely used for its simplicity and convenience, instead of official SDK.
    Download this lastest library version at it's Homepage.
    Create a new Android Project and put jar file downloaded above (twitter4j-core-4.0.4.jar) to your app/libs folder (we'll use it in app module).
    Right click at jar file, select "Add as a Library...", Android Studio will auto-sync gradle for our project. For more details, see "How to Import Jar Library to Android Studio" post.

3. Coding Project

 
    For inject views (not have to use findViewbyId() method) in whole application, I use ButterKnife library and Picasso to loading image from Url to ImageView. So we must add dependencies to "app/build.gradle" like this:
    In this project, I use 2 AsynTasks to connect/sending request to Twitter server and get response from it. First, we must declare a TwitterFactory object based on Consumner Key and Consumer Secret Key by following code:

twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
 
    After that, call getOauthRequestToken() method, we will receive a RequestToken object and make a URL in String style from getAuthorizationURL():

try {
       requestToken = twitter.getOAuthRequestToken();
       oauthURL = requestToken.getAuthorizationURL();
        } catch (TwitterException e) {
            e.printStackTrace();
        }
 
    Put all of above codes in 1st AsyncTask, and in onPostExcute, we'll receive an Oauth URL and show it to a WebView. Full code:
    As you can see, in line 77, I invoked 2nd AsyncTask to get access token from server. Remember that, after 1st AsyncTask finished, we'll see a WebView in Dialog like this:
    By pressing Authorize app button, 2nd AsyncTask were started. In onPostExcute, we call back data (a twitter4j.User object) to main thread. Open your 1st AsyncTask file (GetTwitterTokenTask.java) and paste this code below it:
    In main thread (MainActivity), we'll inject views, call AsyncTasks after click Login Button, display/loading data to views, logout from Twitter by click Logout Button. Source code:

    Because of not saving RequestToken and AccessToken values, my logout()  method has nothing special (only invisible Login Button and hiding data layout). If your save these values (usally in SharedPreference), you would remove their values in this method.

4. Running Application

 
    Open AndroidManifest, put these permission before running app:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    Some screen shots:
pic name pic name
(sorry for ads)
Using Google Maps API v2 to get current Location in Android

Using Google Maps API v2 to get current Location in Android

 
    The great power of mobile applications software, is that it gives us the opportunity to develop many ideas that use hardware features, in order to complete simple everyday tasks. One idea that is implemented in a very good way in the mobile applications world, is the use of maps and the location based applications, that help us in multiple ways in our every day life. So, the use of maps is very important in various mobile applications.
    Google provides  a library (Google Play Services) for using Google Maps and many others features in your application. The following description is based on the Google Maps Android API v2 which provides significant improvements to the older API version.
    The library provides MapFragment and MapView classes to displaying the map component.
    In this post, I will present how to "embed" Google Map in your app and find/update our current location when we have moved.

1. Making SHA-1 Fingerprint

   Firstly, you must make a SHA-1 Fingerprint to create a new Google Map API key. Go to java keytool location folder (In Windows, it usally is "C:\Program Files\Java\jre1.8.0_45\bin") and run Command Prompt here. Type this command to create it:
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
So we'll have a SHA-1 key:

2. Create a Google Maps API key

    Step 1: Go to Google Developer Console, login with your Google account and create a New Project. In this case, I named it is "Place Picker".
    Step 2: In project Dashboard, On the left sidebar, select API & auth/API. Select Google Map API and Google Place API for Android and enable it.
    Step 3: Now, back to Dashboard, select Credentials from left sidebar and click "Create a new key" under Public API access entry. When alert dialog shows, click "Android Key".
    Step 4: Paste above SHA-1 key and your project’s package name separated by semicolon(;):
    Step 5: After click create, we'll have a new project key:
Okey, we have finished Settings in Google Developer Console, now, we will create an android project to use this API key.

3. Creating Android Project

    My project package is info.devexchanges.googlelocation (same as description in Developer Console page). Min-sdk I used is 14.
    In this, I complete 3 tasks:
- Display a Google Map as a MapFragment and put it in an activity.
- Find user current location and update it when moved.
- Showing user current address based on the Location (longitude and latitude).
    Declaring an activity layout which contains a MapFragment and 2 TextViews (display location and address):
activity_location.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <fragment
        android:id="@+id/map"
        class="com.google.android.gms.maps.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.7" />

    <TextView
        android:id="@+id/location"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.1" />

    <TextView
        android:id="@+id/address"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="0.2" />
</LinearLayout>
    In programmatically code, for update current location, I use OnMyLocationChangeListener interface, make a method with this datatypes to detect current location, adding marker with this place like this:
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener() {
        return new GoogleMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
                double longitude = location.getLongitude();
                double latitude = location.getLatitude();

                Marker marker;
                marker = map.addMarker(new MarkerOptions().position(loc));
                map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
                locationText.setText("You are at [" + longitude + " ; " + latitude + " ]");

                //get current address by invoke an AsyncTask object
                new GetAddressTask(LocationActivity.this).execute(String.valueOf(latitude), String.valueOf(longitude));
            }
        };
    }
      And after create a GoogleMap object, we must call  map.setOnMyLocationChangeListener(myLocationChangeListener()) to handling location changes event.
    By getting address components from a [latitude, longitude] pair, we'll use GeoCoder class to parsing it by getFromLocation() method. Our result after this method is a List of Address objects (we set this List has max only one element by call geocoder.getFromLocation(latitude, longitude, 1)).
    This whole process is placed in an AsyncTask. In doInBackground(), we parse address and return a String result.
    In onPostExcute(), calling back data to main thread UI to display them later.
    Full code for this custom AsyncTask:
GetAddressTask.java
package info.devexchanges.googlelocation;

import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class GetAddressTask extends AsyncTask<String, Void, String> {

    private LocationActivity activity;

    public GetAddressTask(LocationActivity activity) {
        super();
        this.activity = activity;
    }

    @Override
    protected String doInBackground(String... params) {
        Geocoder geocoder;
        List<Address> addresses;
        geocoder = new Geocoder(activity, Locale.getDefault());

        try {
            addresses = geocoder.getFromLocation(Double.parseDouble(params[0]), Double.parseDouble(params[1]), 1);

            //get current Street name
            String address = addresses.get(0).getAddressLine(0);

            //get current province/City
            String province = addresses.get(0).getAdminArea();

            //get country
            String country = addresses.get(0).getCountryName();

            //get postal code
            String postalCode = addresses.get(0).getPostalCode();

            //get place Name
            String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL

            return "Street: " + address + "\n" + "City/Province: " + province + "\nCountry: " + country
                    + "\nPostal CODE: " + postalCode + "\n" + "Place Name: " + knownName;

        } catch (IOException ex) {
            ex.printStackTrace();
            return "IOE EXCEPTION";

        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
            return "IllegalArgument Exception";
        }

    }

    /**
     * When the task finishes, onPostExecute() call back data to Activity UI and displays the address.
     * @param address
     */
    @Override
    protected void onPostExecute(String address) {
        // Call back Data and Display the current address in the UI
        activity.callBackDataFromAsyncTask(address);
    }
}
    And code of LocationActivity:
LocationActivity.java
package info.devexchanges.googlelocation;

import android.app.Activity;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


public class LocationActivity extends Activity {

    private TextView locationText;
    private TextView addressText;
    private GoogleMap map;

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

        locationText = (TextView) findViewById(R.id.location);
        addressText = (TextView) findViewById(R.id.address);

        //replace GOOGLE MAP fragment in this Activity
        replaceMapFragment();
    }

    private void replaceMapFragment() {
        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();

        // Enable Zoom
        map.getUiSettings().setZoomGesturesEnabled(true);

        //set Map TYPE
        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        //enable Current location Button
        map.setMyLocationEnabled(true);

        //set "listener" for changing my location
        map.setOnMyLocationChangeListener(myLocationChangeListener());
    }

    private GoogleMap.OnMyLocationChangeListener myLocationChangeListener() {
        return new GoogleMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
                double longitude = location.getLongitude();
                double latitude = location.getLatitude();

                Marker marker;
                marker = map.addMarker(new MarkerOptions().position(loc));
                map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
                locationText.setText("You are at [" + longitude + " ; " + latitude + " ]");

                //get current address by invoke an AsyncTask object
                new GetAddressTask(LocationActivity.this).execute(String.valueOf(latitude), String.valueOf(longitude));
            }
        };
    }

    public void callBackDataFromAsyncTask(String address) {
        addressText.setText(address);
    }
}
    We must add this dependency in "app/build.gradle" file to use GoogleMap API:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.google.android.gms:play-services:7.5.0' //add this line to use Google Map API
}

4. Running application

    Finally, this will be make this "screen": :D

(Sorry for have ads link)