Monday 26 December 2016

Alert Dialog in Android

Alert Dialog in Android

In some conditions in your application you ask the decisions of user like yes or no. By taking the user response in the same activity  and within changing the screen(activity) you can use a alert dialog.

Create a new project in Android Studio.

File --> New Android -->Application Project

Next, Select Target Device

After that, Select Activity
And then Click finish.

* For, alert dialog you need to create a object  of AlertDialogBuilder which an inner class of AlertDialog. see below,

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

Then, you have to set yes or no buttons

like this:

alertDialogBuilder.setPositiveButton(CharSequence text,
   DialogInterface.OnClickListener listener)
alertDialogBuilder.setNegativeButton(CharSequence text,
   DialogInterface.OnClickListener listener)


For 2 Buttons(Yes or no):

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="end.sample.webviewandroid.MainActivity">

    <TextView
        android:textSize="20sp"
        android:textColor="#000000"
        android:text="Welcome to MainActivity"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>


MainActivity.java:

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);

        // Setting Dialog Title
        alertDialog.setTitle("Confirm Exit...");

        // Setting Dialog Message
        alertDialog.setMessage("Are you sure you want exit?");

        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.ic_launcher);

        // Setting Positive "Yes" Button
        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {

                // Write your code here to invoke YES event
                Toast.makeText(getApplicationContext(), "YES", Toast.LENGTH_SHORT).show();
            }
        });

        // Setting Negative "NO" Button
        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // Write your code here to invoke NO event
                Toast.makeText(getApplicationContext(), "NO", Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();

    }
}



 

For 3 Buttons(Yes or no or cancel):

 activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="end.sample.webviewandroid.MainActivity">

    <TextView
        android:textSize="20sp"
        android:textColor="#000000"
        android:text="Welcome to MainActivity"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>


MainActivity.java:

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);

        // Setting Dialog Title
        alertDialog.setTitle("Confirm Exit...");

        // Setting Dialog Message
        alertDialog.setMessage("Are you sure you want exit?");

        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.ic_launcher);

        // Setting Positive "Yes" Button
        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {

                // Write your code here to invoke YES event
                Toast.makeText(getApplicationContext(), "YES", Toast.LENGTH_SHORT).show();
            }
        });

        // Setting Negative "NO" Button
        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // Write your code here to invoke NO event
                Toast.makeText(getApplicationContext(), "NO", Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();

    }
}



Full Code:

MainActivity.java

package end.sample.webviewandroid;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Button twobuttons, threebuttons;

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

        twobuttons  = (Button) findViewById(R.id.twobuttons);
        twobuttons.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gototwobuttons();
            }
        });

        threebuttons  = (Button) findViewById(R.id.threebuttons);
        threebuttons.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotothreebuttons();
            }
        });
    }

    private void gototwobuttons() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);

        // Setting Dialog Title
        alertDialog.setTitle("Confirm Exit...");

        // Setting Dialog Message
        alertDialog.setMessage("Are you sure you want exit?");

        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.ic_launcher);

        // Setting Positive "Yes" Button
        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {

                // Write your code here to invoke YES event
                Toast.makeText(getApplicationContext(), "YES", Toast.LENGTH_SHORT).show();
            }
        });

        // Setting Negative "NO" Button
        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // Write your code here to invoke NO event
                Toast.makeText(getApplicationContext(), "NO", Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    private void gotothreebuttons() {

        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);

        // Setting Dialog Title
        alertDialog.setTitle("Save Data...");

        // Setting Dialog Message
        alertDialog.setMessage("Do you want to save this data?");

        // Setting Icon to Dialog
        alertDialog.setIcon(R.drawable.ic_launcher);

        // Setting Positive "Yes" Button
        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // User pressed YES button. Write Logic Here
                Toast.makeText(getApplicationContext(), "YES",
                        Toast.LENGTH_SHORT).show();
            }
        });

        // Setting Negative "NO" Button
        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // User pressed No button. Write Logic Here
                Toast.makeText(getApplicationContext(), "NO", Toast.LENGTH_SHORT).show();
            }
        });

        // Setting Netural "Cancel" Button
        alertDialog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // User pressed Cancel button. Write Logic Here
                Toast.makeText(getApplicationContext(), "Cancel",
                        Toast.LENGTH_SHORT).show();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }
}
 


activity_main.xml:

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="end.sample.webviewandroid.MainActivity">

    <TextView
        android:textSize="20sp"
        android:textColor="#000000"
        android:text="Welcome to MainActivity"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>



Output:

output will be like this:



For 2 Buttons


For 3 Buttons

 Done.




Android Splash Screen

Android Splash Screen


Most Android Apps uses Android Splash Screen before launching application Activity. Android splash screen is used to display a logo or company name or brand for an app. In this blog we are going to discuss about implementing an Android Splash Screen.

1. Android Splash screen

Create a new project in Android Stuido.

File --> New Android -->Application Project


Next, Select Target Device


After that, Select Activity






And then Click finish.

For Splash Screen we are creating a SplashActivity. Create a new class in your package and name it as SplashAcivity.java.

Open Manifest.xml, and make your splash screen activity as Launcher activity.

      <activity android:name=".SpalshActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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


2. Now, create a activity layout file for Splash Screen and write this code.

activity_spalsh.xml

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

    <ImageView
        android:src="@drawable/ic_launcher"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TextView
        android:text="Spalsh Screen"
        android:textSize="20sp"
        android:textColor="#000000"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"/>

</RelativeLayout>

3.In SplashActivity.java

Declare a variable for time
private static int TIME_DONE = 4000;

in OnCreate() method, write this

new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                // This method will be executed once the timer is over
                // Start your app main activity
                Intent i = new Intent(SpalshActivity.this, MainActivity.class);
                startActivity(i);

                // close this activity
                finish();
            }
        }, TIME_DONE);



Full Code:


activity_splash:

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

    <ImageView
        android:src="@drawable/ic_launcher"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <TextView
        android:text="Spalsh Screen"
        android:textSize="20sp"
        android:textColor="#000000"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"/>

</RelativeLayout>


SpalshActivity.java:

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

public class SpalshActivity extends Activity {

    private static int TIME_DONE = 4000;

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

        new Handler().postDelayed(new Runnable() {

            /*
             * Showing splash screen with a timer. This will be useful when you
             * want to show case your app logo / company
             */

            @Override
            public void run() {
                // This method will be executed once the timer is over
                // Start your app main activity
                Intent i = new Intent(SpalshActivity.this, MainActivity.class);
                startActivity(i);

                // close this activity
                finish();
            }
        }, TIME_DONE);

    }
}



activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="end.sample.webviewandroid.MainActivity">

    <TextView
        android:textSize="20sp"
        android:textColor="#000000"
        android:text="Welcome to MainActivity"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>
 

 
MainActivity.java:

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


public class MainActivity extends AppCompatActivity {

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

Mainfest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="end.sample.android">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".SpalshActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <activity android:name=".MainActivity"/>

    </application>

</manifest>


3. Now run the code.

4. Output:

Output will be like this,




After 4 seconds automatically go to MainActivity.java

Done.








Sunday 25 December 2016

Android Webview

Android - Webview

Android’s WebView allows you to integrate a webpage as a part of the app. WebView comes with all the features that of a desktop browser like managing history, cookies, HTML5 support and lot more.

1. Create a new project 

    Android Studio --> Open --> Create  a new project


Then, select the Target devices


Next, Select Activity


Then,Click on finish.

 After creation of project, open Manifest.xml (left side top):

 And write Internet permission.

<uses-permission android:name="android.permission.INTERNET"/>

1. Now open
   activity_main.xml: 

   <WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>


2. In  MainActivity.java

  Initialize the webview

  WebView webView;

  webView = (WebView) findViewById(R.id.webview);
  webView.loadUrl("http://www.gmail.com/);


  Add the extra features to webview

  webView.getSettings().setJavaScriptEnabled(true);
  webView.loadUrl(postUrl);
  webView.setHorizontalScrollBarEnabled(false);



 Full Code:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="end.sample.webviewandroid.MainActivity">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </WebView>

</RelativeLayout>



MainActivity.java:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;

public class MainActivity extends AppCompatActivity {

    private String url = "https://www.google.co.in/?gfe_rd=cr&ei=x7iFWIz0C4vy8AeCsZ3QBw&gws_rd=ssl";
    WebView webView;

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

        webView = (WebView) findViewById(R.id.webview);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl(url);

    }
}



Manifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="end.sample.webviewandroid">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Now, Run the code.

Output:

Output will be like this


Friday 23 December 2016

Facebook login from android application

Facebook Login in Android Application


Facebook login provides a convenient way for people to log  into app without having to go through a signup process.

Using the latest version of  Facebook SDK's of android, it takes only a few minutes to add this feature to your android app.

In this blog, you will learn how to add a Facebook login into your android app and handle the event to log a user in using Facebook login.

 1. Register your app:

    All apps that use the Facebook SDK's must be registered with Facebook Account.

    - First login into Facebook Developer Page https://developers.facebook.com/


    - Click on login and Click a create a new app in the top right.

    - You will get a form that asks for the App's Display name, Contact email and Category.

    - Enter the required fields and click the "Create App ID". See below:



    - In the next screen, you are able to see your Application ID. Make a note of it. 

    - Because you will be need it later in your Facebook project. 

    - Next, Click on Settings (Left side on top):  Settings ---> Basic

    - Click on Add Platform, select Android.

    - Now Enter the Google Play Package Name of your app and the name of your Activity name.   

    - Key Hashes: After that to fill the key hash filed, open a command prompt window and run the key tool command to generate a  key hash using the Debug key store.
Debug Keystore:

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | 
openssl sha1 -binary | openssl base64
 
Then it asks for password
The default password for the debug key store is android.
 
- The output of a command should be a 28 Characters string.Copy it.
- Go back to your browser, paste the string in to key hashes field.
 
 
- Make sure single sign on is set to yes and click the save changes button.
 
 
- Now, your app is registered with Facebook. 
 

2. Add Facebook SDK into your Project.

The Facebook SDK's is available on Maven Central. To use this repository, 
edit the build.gradle file in your project's app directory and add the following 
code to it. Before the list of dependencies.
 
See below, 
 
2.1. Create a New Project: 
 
 
 2.2. Click next, And select minimum SDk for your app
 
 
 2.3. Next, Select the activity
 
 
2.4.Click on Next, And finish button.
 

2.5. Now go to build.gradle(Module: app):


2.6. Add the following code.

   repositories {
        mavenCentral()
    }
 
2.7. Now you can add the Facebook SDK to your project as a compile dependency.
 
    - For that you need to go Facebook developer page and copy it
 
 Add compile 'com.facebook.android:facebook-android-sdk:[4,5)' to your build.gradle.
  


 
 2.8. Remember that the name of this class and packge name that it belongs should 
    be match the values you entered while registering your app with Facebook.


    - In your activities layout, create the Facebook login button
 

    activity_main.xml:
 
    <com.facebook.login.widget.LoginButton
    android:id="@+id/loginbutton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/> 
 
   - In your MainActivity, declare the Facebook widget.
 
   private LoginButton loginButton;  
 
   In, oncreate method,
 
   loginButton = (LoginButton) findViewById(R.id.loginbutton);
 
 
  * Declare a CallbackManager on another field. The CallbackManager, as ts name 
    suggests is uses to manage the callbacks use in the app.
 
    - i.e. private CallbackManager callbackManager; 
 
  After that,
  - The SDk need to initialized before using any of its method. You can do so by 
  calling SDK Initialize. and passing the application context to it. 

  For this step create the Today Class and it needs to extends from Application Class.
 
 public class Today extends Application {
 
 @Override
    public void onCreate() {
        super.onCreate();
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);
    }
  }  
 
 
 And, this call need to call in Manifest.xml 
 So, give the name in Application fied. See Below image: 
    
 - Now, Initialize your instance of callbackManager using the callbackManager.Facoty create method.
    
 - In your MainActivity, 
    
    callbackManager = CallbackManager.Factory.create();
 
    and
 
    loginButton = (LoginButton) findViewById(R.id.loginbutton);
 
After this step, for getting email from Facebook account we need to add permission 
on Callbackmanager.
 
So, we can write the code like this:
 
  loginButton.setReadPermissions(Arrays.asList("email")); 
    
 - Its the time to create the callback to handle the results of login attemtpts and 
   register it with the callbackManager.
    
 - Custom CallBack should implement FacebookCallback. The interface has methods to handle 
   each possible outcome of a login attempt.
    
 Now, implement the callbackManager method,
    
 loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

            @Override
            public void onSuccess(LoginResult loginResult) {
                
            }

            @Override
            public void onCancel() {
                
            }

            @Override
            public void onError(FacebookException error) {
               
            }
        });
    
    
  - If the login attempt is successful, onSuccess is called.
  - If the user cancel the login attmept, onCanel is called.
  - If an error occurs, then onError is called.
 
- To register the customCallbacks, use the registerCallback method.
 
 So, if onSuccess is called, 
 
    - When the onSuccess() is called, a loginResult is passed as a parameter by using 
this code.
    
So, in this onSuccess(), implement the below code:
  
    
            @Override
            public void onSuccess(LoginResult loginResult) {

                System.out.println("onSuccess");

                String accessToken = loginResult.getAccessToken().getToken();
                Log.i("accessToken", accessToken);

                GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), 
new GraphRequest.GraphJSONObjectCallback() {

                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        Log.i("LoginActivity", response.toString());
                        // Get facebook data from login
                        Bundle bFacebookData = getFacebookData(object);
                    }
                });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location");
                request.setParameters(parameters);
                request.executeAsync();
            } 
 
 
 After this step, create the getFacebookData() method.
 
  private Bundle getFacebookData(JSONObject object) {

        Bundle bundle = new Bundle();

        try {

            if (object.has("email"))

                bundle.putString("email", object.getString("email"));

            Log.e("email", object.getString("email"));

            goMainScreen();

        } catch (JSONException e) {
            e.printStackTrace();
            progressDialog.cancel();
        }

        return bundle;
    }
 
 
 - By tapping the loginButton starts off a new Activity, which returns a result. To 
   receive and handle the result, override the onActivity result method of your activity.
  
 - And pass its parameter to the onActivity method of callbackmanager.
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
 
 
- Now, finish the coding part, then add the Facebook ApplicationId into your 
 
   res -> values -> strings.xml
 
  <string name="facebook_app_id">your app ID</string> 
 

- Edit the Manifest.xml

 *  Add a uses-permission element to the manifest:

   <uses-permission android:name="android.permission.INTERNET"/>

 *  Add a meta-data element to the application element:

   
    <meta-data 
         android:name="com.facebook.sdk.ApplicationId" 
         android:value="@string/facebook_app_id"/>
    
 * Add FacebookActivity to your AndroidManifest.xml: 

    <activity 
          android:name="com.facebook.FacebookActivity"
          android:configChanges=
                 "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
          android:label="@string/app_name" />
 
 
Here, its the Full code
 
activity_main.xml:
 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<com.facebook.login.widget.LoginButton
                android:id="@+id/loginbutton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

<RelativeLayout 
 
 
TodayApp.java:
 
public class Todayapp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);
    }
}
 
 
MainActivity.java:
 
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

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

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

import java.sql.Array;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    private LoginButton loginButton;
    private CallbackManager callbackManager;
    private ProgressDialog progressDialog;

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

        callbackManager = CallbackManager.Factory.create();

        loginButton = (LoginButton) findViewById(R.id.loginbutton);

        loginButton.setReadPermissions(Arrays.asList("email"));

        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

            @Override
            public void onSuccess(LoginResult loginResult) {

                System.out.println("onSuccess");
                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setMessage("Loading...");
                progressDialog.show();

                String accessToken = loginResult.getAccessToken().getToken();
                Log.i("accessToken", accessToken);

                GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
                new GraphRequest.GraphJSONObjectCallback() {

                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        Log.i("LoginActivity", response.toString());
                        // Get facebook data from login
                        Bundle bFacebookData = getFacebookData(object);
                    }
                });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {
                Toast.makeText(getApplicationContext(), "login cancelled", Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onError(FacebookException error) {
                Toast.makeText(getApplicationContext(), "login Error", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private Bundle getFacebookData(JSONObject object) {

        Bundle bundle = new Bundle();

        try {

            if (object.has("email"))

                bundle.putString("email", object.getString("email"));

            Log.e("email", object.getString("email"));

            goMainScreen();

        } catch (JSONException e) {
            e.printStackTrace();
            progressDialog.cancel();
        }

        return bundle;
    }

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

Manifest.xml:
 

Add internet permission
 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="your app package name">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:name=".Todayapp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
 
 


strings.xml:
 
 <string name="facebook_app_id">Replace with your Facebook ApplicatioId</string>
 


 * Now, build and run. Your app is ready. Enjoy.


    
  
 

 
  
 
 








Thursday 22 December 2016

Privacy Polciy for MusicFind

Welcome to MusicFind.

  By using MusicFind app, we are no intended to any user private information.