Login & Registration in Android with MySQL and PHP using Volley

Starting with Login and Registration we required Volley Library you can find it over here:

 compile 'com.android.volley:volley:1.0.0'

Check this Video Representation :

Since mcxiaoki library is depricated and no longer being maintained, please use official version from jCenter.
lets begin with the Laoyout:
We have two layouts inside the fragments since we are using ViewPager so there will be one Activity hosting Two Fragments

screenshot_20160925-224056 screenshot_20160925-224052

1st : Starting with Build.Gradle the dependency we required to run our application. There might be chaces of some dependecy is not required for login and sighup but since i am developing a application so i needed to add these dependency for future development so you can just choose which one is required for you and which one is not.

 

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.2'

    defaultConfig {
        applicationId 'com.infiniteloops.photographer'
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 3
        versionName '0.0.3'
    }
    signingConfigs {
        release {
        }
    }
    buildTypes {
        release {
            signingConfig signingConfigs.release
            minifyEnabled false
            debuggable false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
            minifyEnabled false
            debuggable true
        }
    }
    lintOptions {
        checkReleaseBuilds true
        abortOnError false
        disable 'InvalidPackage'
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile('de.keyboardsurfer.android.widget:crouton:1.8.5@aar') {
        exclude group: 'com.google.android', module: 'support-v4'
    }
    compile 'com.android.support:design:23.4.0'
    compile 'com.android.support:support-v13:23.4.0'
    compile 'com.android.support:recyclerview-v7:23.4.0'
    compile 'com.android.support:palette-v7:23.4.0'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:cardview-v7:23.4.0'
    compile 'com.astuetz:pagerslidingtabstrip:1.0.1'
    compile 'com.weiwangcn.betterspinner:library-material:1.1.0'
    compile 'com.jakewharton:butterknife:7.0.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.google.guava:guava:19.0-rc2'
    compile 'com.makeramen:roundedimageview:2.2.1'
    compile 'com.nineoldandroids:library:2.4.0'
    compile 'com.daimajia.easing:library:1.0.2'
    compile 'com.daimajia.androidanimations:library:1.1.3@aar'
    compile 'com.android.support:support-v4:23.4.0'
    compile 'com.google.android.gms:play-services-auth:9.4.0'
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'
    compile 'com.google.firebase:firebase-messaging:9.4.0'
    compile 'com.google.android.gms:play-services:9.4.0'
    compile 'com.lorentzos.swipecards:library:1.0.9@aar'
    compile 'com.github.lawloretienne:quickreturn:0.0.3'
    compile 'com.github.bumptech.glide:glide:3.5.1'
    compile project(':universal-image-loader-1.8.6-with-sources')

}

2nd : Let’s talk about Android Manifest file so there it is with only two activities
1. MainActivity which is our home Activity
2. And LoginActivity which is holding two fragments

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

    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/Theme.AppCompat.Light.NoActionBar.FullScreen">
        <activity android:name=".Activity.Login_Activity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

3rd: LoginActivity Code follow below the only thing you need to care about is Login_Activty Adapters and Model MainActivity is a stuff where you need to your Home Layout.

package com.infiniteloops.photographer.Activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.infiniteloops.photographer.R;
import com.infiniteloops.photographer.fragments.Login_Fragment;
import com.infiniteloops.photographer.fragments.Signup_Fragment;
import com.infiniteloops.photographer.utils.SessionManager;


public class Login_Activity extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private LinearLayout pager_indicator;
    private int dotsCount;
    private ImageView[] dots;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // If the Android version is lower than Jellybean, use this call to hide
        // the status bar.
        if (Build.VERSION.SDK_INT < 16) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
        SessionManager sm = new SessionManager(Login_Activity.this);
        if(sm.isLoggedIn()){
            startActivity(new Intent(Login_Activity.this, MainActivity.class));
        }
        setContentView(R.layout.login_activity_layout);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);


        //Dots ViewPager
        pager_indicator = (LinearLayout) findViewById(R.id.viewPagerCountDots);

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {

                Log.d("###onPageSelected, pos ", String.valueOf(position));
                for (int i = 0; i < dotsCount; i++) {
                    dots[i].setImageDrawable(getResources().getDrawable(R.drawable.non_selected_dots));
                }

                dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selected_dots));

                if (position + 1 == dotsCount) {

                } else {

                }


            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

        setPageViewIndicator();

        //
    }

    /**
     * A placeholder fragment containing a simple view.
     */

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a Signup_Fragment (defined as a static inner class below).
            Fragment fr=null;
            switch (position){
                case 0:
                    fr =  Signup_Fragment.newInstance(position);
                break;
                case 1:
                    fr =  Login_Fragment.newInstance(position);
                break;

            }
            return fr;
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "SECTION 1";
                case 1:
                    return "SECTION 2";
            }
            return null;
        }
    }

    private void setPageViewIndicator() {

        Log.d("###setPageViewIndicator", " : called");
        dotsCount = 2;
        dots = new ImageView[dotsCount];

        for (int i = 0; i < dotsCount; i++) {
            dots[i] = new ImageView(this);
            dots[i].setImageDrawable(getResources().getDrawable(R.drawable.non_selected_dots));

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );

            params.setMargins(4, 0, 4, 0);

            final int presentPosition = i;
            dots[presentPosition].setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    mViewPager.setCurrentItem(presentPosition);
                    return true;
                }

            });


            pager_indicator.addView(dots[i], params);
        }

        dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selected_dots));
    }

}

4th : Faragments Classes

package com.infiniteloops.photographer.fragments;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.infiniteloops.photographer.Activity.MainActivity;
import com.infiniteloops.photographer.R;
import com.infiniteloops.photographer.ReUseablity;
import com.infiniteloops.photographer.utils.SessionManager;

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

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Login_Fragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */

    private static final String TAG = Login_Fragment.class.getSimpleName();
    @Bind(R.id.email)
    EditText email;
    @Bind(R.id.password)
    EditText password;
    @Bind(R.id.sighnup)
    AppCompatButton login;

    //Signin button
    private ProgressDialog pDialog;
    private static final String ARG_SECTION_NUMBER = "section_number";


    public Login_Fragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static Login_Fragment newInstance(int sectionNumber) {
        Login_Fragment fragment = new Login_Fragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.login_fragment, container, false);
        //TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        //textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        pDialog = new ProgressDialog(getActivity());
        pDialog.setCancelable(false);

        ButterKnife.bind(this, rootView);
        return rootView;
    }
    @OnClick(R.id.sighnup)
    public void login(){
        login_user(email.getText().toString(),password.getText().toString());
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    public void successLogin() {
        startActivity(new Intent(getContext(), MainActivity.class));
        SessionManager sm = new SessionManager(getContext());
        sm.setLogin(true);
        getActivity().finish();


    }

    private void login_user(final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_register";

        pDialog.setMessage("Please wait ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                ReUseablity.REGISTER_USER, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    int error = jObj.getInt("err-code");
                    if (error == 0) {
                        // User successfully stored in MySQL
                        // Now store the user in sqlite
                        ReUseablity.showToast(getContext(), "Become a Photographer :");

                        successLogin();
                        getActivity().finish();
                    } else {

                        // Error occurred in registration. Get the error
                        // message
                        String errorMsg = jObj.getString("message");
                        ReUseablity.showToast(getContext(),
                                errorMsg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("ERROR", "Registration Error: " + error.getMessage());
                ReUseablity.showToast(getContext(),
                        error.getMessage());
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                SharedPreferences spf = ReUseablity.getSharedPrefValue(getContext());
                Map<String, String> params = new HashMap<String, String>();
                params.put("email", email);
                params.put("password", password);
                params.put("method", "user_login");
                params.put("token", spf.getString(ReUseablity.LOGIN_TOKEN, "asna"));
                return params;
            }
        };

        // Adding request to request queue
        //Idea_Application.getInstance().addToRequestQueue(strReq, tag_string_req);
        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(strReq);
    }

    //
    private void showDialog() {
        if (!((Activity) getContext()).isFinishing()) {
            //show dialog
            if (!pDialog.isShowing())
                pDialog.show();
        }
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
}

5th : SighupFragment.java are given Belo

package com.infiniteloops.photographer.fragments;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.SyncStateContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatButton;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.infiniteloops.photographer.Activity.MainActivity;
import com.infiniteloops.photographer.R;
import com.infiniteloops.photographer.ReUseablity;
import com.infiniteloops.photographer.utils.SessionManager;

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

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Signup_Fragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */

    //Image request code
    private int PICK_IMAGE_REQUEST = 1;

    //storage permission code
    private static final int STORAGE_PERMISSION_CODE = 123;

    //Bitmap to get image from gallery
    private Bitmap bitmap;

    //Uri to store the image uri
    private Uri filePath;

    private static final String TAG = Signup_Fragment.class.getSimpleName();

    //Signin button
    private ProgressDialog pDialog;
    private static final String ARG_SECTION_NUMBER = "section_number";
    @Bind(R.id.profile)
    ImageView profile;
    @Bind(R.id.name)
    EditText name;
    @Bind(R.id.email)
    EditText email;
    @Bind(R.id.password)
    EditText password;
    @Bind(R.id.sighnup)
    AppCompatButton sighnup;

    public Signup_Fragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static Signup_Fragment newInstance(int sectionNumber) {
        Signup_Fragment fragment = new Signup_Fragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.signup_fragment, container, false);
        requestStoragePermission();
        //TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        //textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        pDialog = new ProgressDialog(getActivity());
        pDialog.setCancelable(false);

        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick(R.id.sighnup)
    public void onClick() {
        registerUser(name.getText().toString(), email.getText().toString(), password.getText().toString(), "");

    }

    public void successLogin() {
        startActivity(new Intent(getContext(), MainActivity.class));
        SessionManager sm = new SessionManager(getContext());
        sm.setLogin(true);
        getActivity().finish();

    }

    private void registerUser(final String name, final String email, final String password, final String user_avatar) {
        // Tag used to cancel the request
        String tag_string_req = "req_register";

        pDialog.setMessage("Registering ...");
        showDialog();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                ReUseablity.REGISTER_USER, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());
                hideDialog();

                try {
                    JSONObject jObj = new JSONObject(response);
                    int error = jObj.getInt("err-code");
                    if (error == 0) {
                        // User successfully stored in MySQL
                        // Now store the user in sqlite
                        ReUseablity.showToast(getContext(), "Registration Successfull :");
                        SharedPreferences.Editor ed = ReUseablity.editSharedPrefValue(getContext());
                        //ed.putString(ReUseablity.USER_ID, jObj.getString("user"));
                        ed.commit();
                        // Launch login activity
                        successLogin();
                        getActivity().finish();
                    } else {

                        // Error occurred in registration. Get the error
                        // message
                        String errorMsg = jObj.getString("message");
                        ReUseablity.showToast(getContext(),
                                errorMsg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("ERROR", "Registration Error: " + error.getMessage());
                ReUseablity.showToast(getContext(),
                        error.getMessage());
                hideDialog();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting params to register url
                String image = getStringImage(bitmap);

                SharedPreferences spf = ReUseablity.getSharedPrefValue(getContext());
                Map<String, String> params = new HashMap<String, String>();
                params.put("name", name);
                params.put("email", email);
                params.put("password", password);
                params.put("profile", image);
                params.put("method", "register_app_user");
                params.put("token", spf.getString(ReUseablity.LOGIN_TOKEN, "asna"));
                return params;
            }
        };

        // Adding request to request queue
        //Idea_Application.getInstance().addToRequestQueue(strReq, tag_string_req);
        RequestQueue requestQueue = Volley.newRequestQueue(getContext());
        requestQueue.add(strReq);
    }
    public String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }
    //
    private void showDialog() {
        if (!((Activity) getContext()).isFinishing()) {
            //show dialog
            if (!pDialog.isShowing())
                pDialog.show();
        }
    }

    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }
    //method to show file chooser
    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }

    //handling the image chooser activity result
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == getActivity().RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
                profile.setImageBitmap(bitmap);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //method to get the file path from uri
    public String getPath(Uri uri) {
        Cursor cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        String document_id = cursor.getString(0);
        document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
        cursor.close();

        cursor = getActivity().getContentResolver().query(
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
        cursor.moveToFirst();
        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        cursor.close();

        return path;
    }


    //Requesting permission
    private void requestStoragePermission() {
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
            return;

        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
            //If the user has denied the permission previously your code will come to this block
            //Here you can explain why you need this permission
            //Explain here why you need this permission
        }
        //And finally ask for the permission
        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
    }


    //This method will be called when the user will tap on allow or deny
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        //Checking the request code of our request
        if (requestCode == STORAGE_PERMISSION_CODE) {

            //If permission is granted
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //Displaying a toast
                Toast.makeText(getContext(), "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
            } else {
                //Displaying another toast if permission is not granted
                Toast.makeText(getContext(), "Oops you just denied the permission", Toast.LENGTH_LONG).show();
            }
        }
    }

    @OnClick(R.id.profile)
    public void fileChooser() {
        showFileChooser();

    }


}

6th : Customizung Layouts for the above Code

Login_activity_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".Activity.Login_Activity">


    <android.support.v4.view.ViewPager android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" />
    <View android:layout_above="@+id/viewPagerIndicator" android:layout_width="fill_parent" android:layout_height="0.5dp" android:background="@color/whitesmoke"/>

    <RelativeLayout android:elevation="2dp" android:id="@+id/viewPagerIndicator" android:layout_width="match_parent" android:layout_height="45dp" android:layout_alignParentBottom="true" android:layout_marginTop="5dp" android:gravity="center">

        <LinearLayout android:id="@+id/viewPagerCountDots" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerHorizontal="true" android:gravity="center" android:orientation="horizontal" />

    </RelativeLayout>

</RelativeLayout>

LoginLayout.xml (Fragment)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:listbuddies="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:padding="10dp" android:background="@drawable/parallax" android:orientation="vertical" android:layout_gravity="center" android:gravity="center" android:layout_height="match_parent">

    <ImageView android:src="@drawable/logo" android:layout_width="75dp" android:layout_gravity="center" android:id="@+id/profile" android:layout_height="75dp" />

    <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content">

    <EditText android:id="@+id/email" android:textColor="@color/whitesmoke" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="email" />
</android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content">

    <EditText android:id="@+id/password" android:textColor="@color/whitesmoke" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Password" />
</android.support.design.widget.TextInputLayout>
    <android.support.v7.widget.AppCompatButton android:layout_width="match_parent" android:layout_gravity="center" android:gravity="center" android:id="@+id/sighnup" android:text="Login" android:textColor="@color/whitesmoke" android:background="@color/transparent_black_eighty" android:layout_height="wrap_content" />
</LinearLayout>

SignupLaout.xml (Fragment)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:listbuddies="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:padding="10dp" android:gravity="center" android:background="@drawable/parallax" android:orientation="vertical" android:layout_height="match_parent">

    <ImageView android:src="@drawable/logo" android:layout_width="75dp" android:layout_gravity="center" android:id="@+id/profile" android:layout_height="75dp" />
    <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content">

        <EditText android:id="@+id/name" android:textColor="@color/whitesmoke" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Name" />

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

    <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content">

    <EditText android:id="@+id/email" android:textColor="@color/whitesmoke" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="email" />
</android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout android:layout_width="match_parent" android:layout_height="wrap_content">

    <EditText android:id="@+id/password" android:textColor="@color/whitesmoke" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Password" />
</android.support.design.widget.TextInputLayout>
    <android.support.v7.widget.AppCompatButton android:layout_width="match_parent" android:layout_gravity="center" android:gravity="center" android:id="@+id/sighnup" android:text="SignUp" android:textColor="@color/whitesmoke" android:background="@color/transparent_black_eighty" android:layout_height="wrap_content" />
</LinearLayout>

main_layout.xml (Fragment)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".Activity.MainActivity">

    <!-- activity view -->
    <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/background_tab">


        //You put what you want in this layout

    </FrameLayout>

</LinearLayout>

Note : If anything you are not able to find in your Layout or in Activity you can just find everyhting in my Github Repo :
https://github.com/ansarisufiyan777/Photography

In your Server we have databse schema is given below :

capture
Fire below query in your server PHPMyAdmin or any other database you using

-- phpMyAdmin SQL Dump
-- version 4.0.10.7
-- http://www.phpmyadmin.net
--
-- Host: localhost:3306
-- Generation Time: Sep 27, 2016 at 06:01 AM
-- Server version: 5.6.29-76.2-log
-- PHP Version: 5.4.31

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `wagmaadl_blog`
--

-- --------------------------------------------------------

--
-- Table structure for table `blog_users`
--

CREATE TABLE IF NOT EXISTS `blog_users` (
 `id` int(10) NOT NULL AUTO_INCREMENT,
 `name` varchar(1000) NOT NULL,
 `email` varchar(1000) NOT NULL,
 `password` varchar(1000) NOT NULL,
 `profile` varchar(1000) NOT NULL,
 `date_of_creation` varchar(100) NOT NULL,
 `device_token` varchar(1000) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=22 ;

--
-- Dumping data for table `blog_users`
--

INSERT INTO `blog_users` (`id`, `name`, `email`, `password`, `profile`, `date_of_creation`, `device_token`) VALUES
(13, 'asna', 'asssaas1@gmail.com', '82b4d1de09cdafffe17abaf65124ec9f', '', '2016-09-23 09:00:15', 'jhjsdvjd'),
(12, 'asna', 'asssaas@gmail.com', '82b4d1de09cdafffe17abaf65124ec9f', '', '2016-09-23 08:58:44', 'jhjsdvjd'),
(11, '', '', 'd41d8cd98f00b204e9800998ecf8427e', '', '2016-09-23 08:54:46', 'jhjsdvjd'),
(10, '', '', 'd41d8cd98f00b204e9800998ecf8427e', '', '2016-09-23 08:54:39', 'jhjsdvjd'),
(14, 'asna', 'asssaas11@gmail.com', '82b4d1de09cdafffe17abaf65124ec9f', '', '2016-09-23 09:03:21', '5CdHwjeOek'),
(15, 'Ansari sufiyan ', 'Ansarisufiyan777@gmail.com ', '82b4d1de09cdafffe17abaf65124ec9f', '', '2016-09-23 13:47:45', 'AT6ESUQE1F'),
(16, 'Asna Euphoria ', 'asnastudio777@gmail.com ', '82b4d1de09cdafffe17abaf65124ec9f', '', '2016-09-23 14:09:15', '8LGoT8nqqL'),
(17, 'Alan Walker ', 'alanwalaker@gmail.com', '82b4d1de09cdafffe17abaf65124ec9f', '', '2016-09-25 10:10:22', 'wDpcSwqyCs'),
(18, 'armin', 'armin', 'cf3384d079ddcb4ca02fadab6be9802d', '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAIaA8cDASIA\nAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA\nAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3\nODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm\np6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA\nAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx\nBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK\nU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3\nuLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD5uz1x\nyRjjp1PHOPTn9OtNCgE4GMdOc56+/GMn65oOcbepOeenQ5r9yv2NvhH8KPFP7M3w217xH8LvAHiX\nVtQ/4TH7Vret+DPCutaheY+IXjbRj/xN9a8P+vJ9QSDgjcf7YxmN/s3CSxaeidnr/eaTavrqnZb6', '2016-09-25 14:09:41', '5TQLGyTkSq'),
(19, 'arminv', 'arminv', 'e65f454a166b1b433af0771f733c4362', '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCARZAvwDASIA\nAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQA\nAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3\nODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm\np6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEA\nAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSEx\nBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElK\nU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3\nuLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD8g/2n\nPG/ixPj98bY08S6qqr8Q/FKKovrjaqprF8oVQJMKFAUADjG0DG014p/wm/i7/oZtV/8ABhdf/HK9\nG/ae/wCTgvjb/wBlB8Wf+nq8rxiv5HrtqvW63qTd3e/8Wb3bfWK+TfXU/gutCn9Yrv2cG3Vm2+WO', '2016-09-25 14:11:48', 'CTNfvKCWag'),
(20, 'okey', 'okey', '8795c748789888942a34659930cec654', 'http://infiniteloops.info/blog/volley/uploads/20.png', '2016-09-25 14:14:43', 'JQva1HXEVf'),
(21, 'india', 'india@gmail.com', '11a98374ebec8e0c7a54751d2161804d', 'http://infiniteloops.info/blog/volley/uploads/21.png', '2016-09-25 14:22:39', 'BfE1mWOX5Y');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Now lets talk about an API which we are using in our project :

we have only one api index.php and we are pointing it by passing a method name which we need to executes on the server side
Advantages:
1: Saves time
2: Reduces multiple files creation
3: Easy to change and add an Addidtional code

<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include("config.php");
function generateRandomString($length = 10)
{
 $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
 $randomString = '';
 for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString; } function get_user_data($uid) { $uid = mysql_real_escape_string($uid); if (empty($uid)) return NULL; $user = mysql_fetch_assoc(mysql_query("select * from `blog_users` where `id`='$uid'")); return $user; //return array("message" => $user,"login_token" => $login_token, "err-code" => "0");
}
function get_email($email) {
 $email = mysql_real_escape_string($email);
 if (empty($email))
   return NULL;
 $user = mysql_fetch_assoc(mysql_query("select * from `blog_users` where `email`='$email'"));
 return $user;
 //return  array("message" => $user,"login_token" => $login_token, "err-code" => "0");
}
function register_app_user($data)
{
 //$data = json_decode($data);
 $name = $data['name'];
 $email = $data['email'];
 $password = $data['password'];
 $profile = $data['profile'];
 $login_token = generateRandomString(10);
 $user = get_email($email);
 $id = getFileName();
 $path = "uploads/$id.png";
 $actualpath = "http://infiniteloops.info/blog/volley/$path";
 if($user)
 {
   return array("err-code"=>300,"message"=>"This email is already exist. Please try with another email.");
 }
 else
 {
   $query = "insert  into `blog_users` (`name`,`email`,`password`,`device_token`,`profile`,`date_of_creation`) values('$name','$email',md5('$password'),'$login_token','$actualpath',NOW())";
   if(mysql_query($query))
   {
     $u_id = mysql_insert_id();
     file_put_contents($path,base64_decode($profile));
     $result = mysql_fetch_assoc(mysql_query("select * from blog_users where id='$u_id'"));
     return array("err-code"=>0,"message"=>"Thank You! You are successfully signed-up.","user"=>$result);
   }
   else
   {
     return array("err-code"=>300,"message"=>"Please try again.");
   }
 }
}
function user_login($data)
{
 $email = $data['email'];
 $password = md5($data['password']);
 $query = "select * FROM blog_users where email='$email' and password='$password'";
 if($user = mysql_fetch_assoc(mysql_query($query)))
 {
   return array("err-code"=>0,"message"=>"Successfully login","user"=>$user);
 }
 else
 {
   return array("message" => "Login failed. Please check email or password." , "err-code" => "300");
 }
}
$req = @file_get_contents('php://input');
$method = $_POST['method'];
if(isset($method))
{
 if (function_exists($method))
 {
   echo json_encode($method($_POST));
 }
 else
 {
   echo "method not exist";
 }
}
else
{
 echo "method not set ".$method;
}
//ImagickPixel
/*
		We are generating the file name
		so this method will return a file name for the image to be upload
	*/
	function getFileName(){
		$sql = "SELECT max(id) as id FROM blog_users";
		$result = mysql_fetch_array(mysql_query($sql));
		mysql_close($con);
		if($result['id']==null)
			return 1;
		else
			return ++$result['id'];
	}
  
?>

And now our Config files contains our database informations and Credentials:

<?php $con = mysql_connect('localhost', 'wagmaadl_blog', 'password') or die('Unable to connect. Check your connection parameters');; $sel_db = mysql_select_db('wagmaadl_blog', $con); ?>

For full code fork me on GITHUB I love it