Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: Android

Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: Android
Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Sms Bomber Android Source Code

Sms Bomber Android Source Code


Download Source Code :

Link

Sample App :

Link  

0

Admob EU Consent Implementation

Admob EU Consent Implementation





Since Google Announce New Policy EU User. But Some Of US Dont Understand What we Do So let's Start Today We Start How To Comply EU Users for Admob.

Here We Implement Consent sdk which prompt user which ads type they want .

Let's Start.



Lets Start.

First Login Your Admob Account 

Then Open Menu = > Blocking Controls =>  EU User Consent

And Select Custom Ads Provider and Select 12 Ads Provider.



Then Save.

Now Let's Start Coding In Our App.

Open Your build.gradle and add this consent library . 
implementation 'com.google.android.ads.consent:consent-library:1.0.3'
 
Then 
 
Currently i am loading ads in my main activity so first i call the consent methods.
 
  

    private ConsentForm form;
Boolean Adtype=false;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        constant=new Constant(getApplicationContext());
          final ConsentInformation consentInformation = ConsentInformation.getInstance(MainActivity.this);
            String[] publisherIds = {"YOUR_PUBLISHER_ID"};
       
             consentInformation.requestConsentInfoUpdate(publisherIds, new ConsentInfoUpdateListener() {
                    @Override
                    public void onConsentInfoUpdated(ConsentStatus consentStatus) {
                        // User's consent status successfully updated.
                        Log.d("ok", consentInformation.toString());
                    }

                    @Override
                    public void onFailedToUpdateConsentInfo(String errorDescription) {
                        // User's consent status failed to update.
                    }
                });
           showAdmob();
showADS();

        }

public void showAdmob(){
     URL privacyUrl = null;
        try {
            // TODO: Replace with your app's privacy policy URL.
            privacyUrl = new URL("APP_PRIVACYURL_OF_YOUR_SITE");
        } catch (MalformedURLException e) {
            e.printStackTrace();
            // Handle error.
        }

        ConsentForm.Builder builder = new ConsentForm.Builder(MainActivity.this, privacyUrl);

        builder.withListener(new ConsentFormListener() {
            @Override
            public void onConsentFormLoaded() {

                form.show();


            }

            @Override
            public void onConsentFormOpened() {

            }

            @Override
            public void onConsentFormClosed(
                    ConsentStatus consentStatus, Boolean userPrefersAdFree) {

                if(consentStatus.name().equalsIgnoreCase("PERSONALIZED")){
Adtype=true;
     showADS();
 

                }
                else {
Adtype=false;
    showADS();
                }
            }

            @Override
            public void onConsentFormError(String errorDescription) {

            }
        });
        builder.withPersonalizedAdsOption();
        builder.withNonPersonalizedAdsOption();
        form = builder.build();

        form.load();

}

//======By Default Admob Use Non Peronalised Ads but Here Confimation box ask from EU User Which Ads They Want===
//====If Non Relevant ads selected then we pass bundle with "npa" => "1" in adbuilder===
//=====Then It Will Display the Ads also we call The Admob Ads===============

   public void showADS(){
        AdRequest request;
        if(Adtype){
            Bundle extras = new Bundle();
            extras.putString("npa", "1");
            request = new AdRequest.Builder()
                    .addNetworkExtrasBundle(AdMobAdapter.class, extras)
                    .build();
        }
        else{
            request = new AdRequest.Builder().build();
        }
        final InterstitialAd mInterstitialAd;
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId("YOUR_ADS_UNIT);
        mInterstitialAd.loadAd(request);
        mInterstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                mInterstitialAd.show();

            }

            @Override
            public void onAdFailedToLoad(int errorCode) {
            }

            @Override
            public void onAdOpened() {
            }

            @Override
            public void onAdLeftApplication() {
            }

            @Override
            public void onAdClosed() {
            }
        });


    }
2

Android Input Form Example

Android Input Form Example


Today We Start Android Basic Input Types Like : -

1.Edittext  (Input Box Taking Value From User).
2.spinner (Spinner is a dropdown For Taking Value From User)
3.Radio ( Radio a option button for selecting one value from multiple values)
4.Button ( Button For Submitting our Data).


Now Let's Start.


First Create A New Android Project :  



Android Project

Now Open activity_main.xml file and Delete Everything Old Code We creating from Scratch.

android signup layout



 Now Make One LinearLayout with Orientation Vertical .

 Code : 

<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android" >
</LinearLayout> 

Like this : 
  

Here i LinearLinear Layout Which is Perfect for beginning.  I add Orientation vertical so that my all child item inside linear layout comes one after another.

Let's Add Some Input Elements Like Edittext,Button,Radio,Spinner .
<LinearLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <EditText
        android:layout_margin="10dp"
        android:hint="Username"
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <EditText
        android:id="@+id/password"
        android:hint="Password"
        android:layout_margin="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <RadioGroup
        android:id="@+id/gender"
        android:layout_margin="10dp"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <RadioButton
            android:id="@+id/male"
            android:layout_weight="1"
            android:text="Male"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        <RadioButton
            android:id="@+id/female"
            android:layout_weight="1"
            android:text="Female"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </RadioGroup>
    <TextView
        android:text="Age"
        android:layout_margin="10dp"
        android:textAlignment="center"
        android:textSize="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Spinner
        android:id="@+id/age"
        android:layout_margin="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/submit"
        android:text="Submit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

Our Final Design Look Like This : 

Now Let's Code in JAVA for Taking Values from this Input When Click on Submit .

MainActivity.java


package androidbasic.supercoders.in.androidbasic;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {


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

        //-----Declaring Input Element and Finding in Our Layout View----
        final EditText edit_username=(EditText)findViewById(R.id.username);
        final EditText edit_password=(EditText)findViewById(R.id.password);
        final RadioGroup Gender=(RadioGroup) findViewById(R.id.gender);
        final RadioButton Male=(RadioButton) findViewById(R.id.male);
        final RadioButton FeMale=(RadioButton) findViewById(R.id.female);
        final Spinner Ages=(Spinner)findViewById(R.id.age);
        Button Submit=(Button)findViewById(R.id.submit);

        //==========Now Setting Value in Our DropDown Spinner==============
        //======For This We Have To Create A ArrayAdapter with Type String=====
        //===ArrayAdapter is Java Class And its Constructor Takes 3 Param
        //1. Current Class Context,2. Our Textview Layout ,3. Our List of Items in string.


        //====First Create a List of Item for age  ==

        List<String > list=new ArrayList<>();
        for(int i=10;i<50;i++){
            list.add(String.valueOf(i));
        }

        ArrayAdapter<String> arrayAdapter=new ArrayAdapter<>(MainActivity.this,android.R.layout.simple_dropdown_item_1line,list);

        //====Now Set the Adapter To Spinner by Using SetAdapter Method

        Ages.setAdapter(arrayAdapter);

        //====Set On Click Listener For Button ===

        Submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //===Now Doing Some Validation====

                //====We Can Get Value of Edit Text By using method gettext==

                if(edit_username.getText().toString().isEmpty()){
                    edit_username.setError("Please Enter Username");
                }
                else if(edit_password.getText().toString().isEmpty()){
                    edit_password.setError("Please Enter Username");
                }
                else if(!Male.isChecked() && !FeMale.isChecked()){

                    //===Toast I Used Here For Small Message Display==
                    Toast.makeText(MainActivity.this, "Please Select Gender", Toast.LENGTH_SHORT).show();
                 }
                 else{
                    Toast.makeText(MainActivity.this, edit_username.getText().toString(), Toast.LENGTH_SHORT).show();
                    Toast.makeText(MainActivity.this, edit_password.getText().toString(), Toast.LENGTH_SHORT).show();
                    Toast.makeText(MainActivity.this, Ages.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();

                    RadioButton selectedGender=(RadioButton)findViewById(Gender.getCheckedRadioButtonId());
                    Toast.makeText(MainActivity.this,selectedGender.getText().toString() , Toast.LENGTH_SHORT).show();
                }
            }
        });


    }
}

Here is Our Final Result 

final result


Android Development Basic

Android Development Basic

Android Project Structure


Android Project Structure -

Before we Start to make our first Android app, we first see the basic parts of an Android application project, in order to recognize them and be able to understand them better.


AndroidManifest.xml

Androidmanifest.xml

 

AndroidManifest is A xml file Which information of our app. it contains : -

1. App Permission.
2. Our Running Activites which we have to Register in AndroidManifest.xml
3. Our Broadcaster
4. Our Receiver
5. Our Services.
 

Activities

android activity

 

The Activities are the main Java classes with a layout design file  , that contain the Android code with which we are going to develop, what do we want the application to do.

Res Directory

android res

 


Res Directory also called Resource directory where all our resource file be stored like design,layout,images,menu etc.

  

Layouts 

android layout

 

The Layouts are the xml files, that contain the Android xml code with which we are going to develop, how will our application UI look like.

Values

android values

 

The Values are Also XML file Which Contain The Values of Strings,Style, Colors in To Use them in Your App.

Following are Thing Comes in Values : -

– Animation Resources
– Color State List Resource

android color




– Drawable Resources

android drawable


– Layout Resource

android layout




– Menu Resource

android menu






– String Resources

android string



– Style Resource 

android style



Drawables 

 A drawable resource is a directory in res which contain our images,layout drawable,shapes , vector graphics.
Following are The Things Comes is Drawable : -

Bitmap File
-  A bitmap graphic file (.png, .jpg, or .gif). Creates a Bitmap Drawable.
Nine-Patch File
-  A PNG file with stretchable regions to allow image resizing based on content (.9.png). Creates a Nine Patch Drawable.
Layer List
-  A Drawable that manages an array of other Drawables. These are drawn in array order, so the element with the largest index is be drawn on top. Creates a LayerDrawable.
State List
-  An XML file that references different bitmap graphics for different states (for example, to use a different image when a button is pressed). Creates a StateListDrawable.
Level List
-  An XML file that defines a drawable that manages a number of alternate Drawables, each assigned a maximum numerical value. Creates a Level List Drawable.
Transition Drawable
-  An XML file that defines a drawable that can cross-fade between two drawable resources. Creates a Transition Drawable.
Inset Drawable
- An XML file that defines a drawable that insets another drawable by a specified distance. This is useful when a View needs a background drawble that is smaller than the View’s actual bounds.
Clip Drawable
- An XML file that defines a drawable that clips another Drawable based on this Drawable’s current level value. Creates a Clip Drawable.
Scale Drawable
-  An XML file that defines a drawable that changes the size of another Drawable based on its current level value. Creates a Scale Drawable
Shape Drawable
- An XML file that defines a geometric shape, including colors and gradients. Creates a Shape Drawable.


build.gradle

build.gradle is a file which contain information of our project library,modules,
application id,version name,version code etc.


build.gradle

 

Android Hello World Example

Start Android Studio and Create a new Project.

android hello world

 Select Minimum Api Level  (Api Level Means Which Lowest Android Which You Want to Run That App).

android  api

Android Activity (Selecting Here Simple Empty Activity)

android empty activity

Android Launcher Activity Name 

mainactivity

Android Project is Ready Now Click on Green Play Button To Run Your Android Project.

Make Sure You Created Your Emulator. 
Or Connected Your Device With USB Debugging is Permission is  (For Enable USB Debugging .
Just Go To Phone-> Setting -> About -> Click on Build Number 7 times .
 then back then you see a developer option just enable the usb debugging)

android project ready

Android Hello World Example. 

android devices
 

android hello world

Install Android Studio

Today For Some User It's Difficult To Setup Android Studio.

In This I Will Show How To Install Android Studio.

 
On Windows 
and On Ubuntu.

Let's Start
For Ubuntu : -
Install JDK 6 or Later. (Better To Use Latest Version)

command : -

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
sudo apt-get install oracle-java8-set-default

Now Let's Download Android SDK from Here For Ubuntu.

https://developer.android.com/sdk/index.html

After Installing Java and Downloading Android Studio.

Now Extract The file to home directory.

For This.

Use : tar zxvf android.tar.gz /home/Your_user_directory/


Let set The Path For android Studio and Java.

Now Open Your Bashrc file by Running This Code (Not in Root User).

sudo gedit ~/.bashrc

Paste This Line To Bottom of The File.

//please check your sdk location in file manager first

export ANDROID_HOME=/home/Your_Username/Android/Sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
export JAVA_HOME=/usr/lib/jvm/java-8-oracle

now save and close this file.

after that reload the file for system.
so run this command.

source ~/.bashrc

Now Open Your android studio.

By Running the command.

android-studio/bin/studio.sh.

Then Follow This Screens.

android studio setup
 

android studio setup

android studio setup



android studio setup

please check you android-studio location first in my case it in home user directory.

now this was fresh install so you have to select do not import setting.
after that update some libraries.

Now its Ready To Use.

For Windows :

Installing android on Windows Does not required lots of thing.
Just download
jdk: -

http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

and
android studio 

Then simply Run the executable file
.
https://developer.android.com/sdk/index.html

All will Done by window automatic.

Android TabLayout Tutorial

Android TabLayout Tutorial

android tab layout

Android Tab  Layout is The Popular Layout in Android. We See This Layout in Many Example of Application Like Whatsapp. 

Tab Layout Contain Features Like Swapping Fragment With Out Destroying Fragment Means We Run Multi Fragment Simultaneously.

Each Tab in Tab Activity is A Fragment Which We Add In Our Activity Using View Pager.

Lets Start Create Today a Simple Tab Fragment With Three Tab and Each Tab Had its Own Fragment.


Step 1. Open Android Studio and Create a New Project.

android studio project


Step 2 . Select Minimum Sdk Version

Select Minimum Sdk Version
Step 3 .  Select Tabbed Activity

tab activity

Step 4 . Select Navigation Style.

Here Navigation is Three Types :-

1.Swipe Views : - Means No Tab Coming On Top.
2.Action Bar Tabs : - Means Activity with Top Tabs.
3.Action Bar Spinner : - Select Option for Switiching Tabs.

Meanwhile After This All Your Finger Swipe Will Work in All.

tab bar

Step 5 . Now Our Project is Created But We Need To Implement Fragment.


Step 7. Create 3 Blank Fragment.

blank fragment

Step 8. This is Our New Project Structure.


Step 9. Now i am Going to Create a List With Fragment Datatype And Add the List in Viewpager Adapter.

Let's See.

//============Creating A List Of Fragments=============

    List<Fragment> fragments=new ArrayList<>();
        fragments.add(new HomeFragment());
        fragments.add(new ProfileFragment());
        fragments.add(new ContactFrament());


Now Passing List in Constructor for Page Adapter
 
//===========passing list in contstructor for in fragment page Adapter====
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),fragments);


This Our Page Adapter Class
 
    public class SectionsPagerAdapter extends FragmentPagerAdapter {
        List<Fragment> fragmentList=new ArrayList<>();

        public SectionsPagerAdapter(FragmentManager fm,List<Fragment> fragments) {
            super(fm);
            fragmentList=fragments;
        }


        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return fragmentList.get(position);
        }


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

Now Our Final Main Activity Code
 
package lichpit.supercoders.in.tablayoutexample;

import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

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.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements HomeFragment.OnFragmentInteractionListener,ProfileFragment.OnFragmentInteractionListener,ContactFrament.OnFragmentInteractionListener{

    /**
     * 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;

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

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        List fragments=new ArrayList<>();
        fragments.add(new HomeFragment());
        fragments.add(new ProfileFragment());
        fragments.add(new ContactFrament());


        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),fragments);

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


        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            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.fragment_main, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {
        List fragmentList=new ArrayList<>();

        public SectionsPagerAdapter(FragmentManager fm,List fragments) {
            super(fm);
            fragmentList=fragments;
        }


        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return fragmentList.get(position);
        }


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

Our activity_main.xml
 
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_weight="1"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            app:title="@string/app_name">

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

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

            <android.support.design.widget.TabItem
                android:id="@+id/tabItem"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/tab_text_1" />

            <android.support.design.widget.TabItem
                android:id="@+id/tabItem2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/tab_text_2" />

            <android.support.design.widget.TabItem
                android:id="@+id/tabItem3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/tab_text_3" />

        </android.support.design.widget.TabLayout>
    </android.support.design.widget.AppBarLayout>

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

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

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

Now Here I Don't Write My Fragment Code Because it Simple Blank Fragment.

Final Output :

android tablayout example

You Can Change Title of Tab By Editing The Text from Tabitem in activity_main.xml.

 
            <android.support.design.widget.TabItem
                android:id="@+id/tabItem3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="YOUR_TAB_TITLE" />

Download Complete Source Code : - Download
0

Android Paytm Integration

Android Paytm Integration


Day By Paytm Usage Increasing Fastly and Many Shopping cart and sites start accepting paytm payment accept even irctc start accepting paytm payment. 

Today lets we Start integrating paytm gateway in Our Android App.

Let's Start!.

First Signup a Business Account They Need some Docs and Infromation of PAN ,GST , etc. But Dont Worry if You Don't Have this Paytm Also Provide sandbox signup without any of these documents.

Step :1 
Visit Here and Signup : - Paytm Business Signup
 
Click On Start Application Then This Popup Will Open.

paytm payment gateway

Step 2 :

Click Continue.

Signup for Business Account Or Sanbox Account Option on Top Available.

paytm payment gateway


Step 3 : After Signup Copy Our Credentials .

paytm payment gateway


Step : 4 (Server Works Now!)

Download Paytm Checksum utlities from here : Link : Download Paytm PHP Utlity

Upload The file on Local Sever or Live Server (if you have live server).

Currently i am Using Xampp Server. and Address is  (http://192.168.43.110)

Here is all Utlity file after extracted.
paytm php

Step 7 : 

Copying the php directory to /opt/lampp/htdocs/ (my local server).
paytm php
Step 8 :

Editing generateChecksum.php  with our Credential of paytm .

I Just Edit Credential and Change print_r function to json_encode to get Result in Json format and parse in android.



<?php
header("Pragma: no-cache");
header("Cache-Control: no-cache");
header("Expires: 0");
// following files need to be included
require_once("./lib/config_paytm.php");
require_once("./lib/encdec_paytm.php");
$checkSum = "";

// below code snippet is mandatory, so that no one can use your checksumgeneration url for other purpose .

$paramList = array();

$paramList["MID"] = 'xxxxxxxxxxxxx'; //Provided by Paytm
$paramList["ORDER_ID"] = 'ORDER0000001'; //unique OrderId for every request
$paramList["CUST_ID"] = 'CUST00001'; // unique customer identifier 
$paramList["INDUSTRY_TYPE_ID"] = 'xxxxxxxxxxx'; //Provided by Paytm
$paramList["CHANNEL_ID"] = 'WAP'; //Provided by Paytm
$paramList["TXN_AMOUNT"] = '1.00'; // transaction amount
$paramList["WEBSITE"] = 'xxxxxxxx';//Provided by Paytm
$paramList["CALLBACK_URL"] = 'https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp';//Provided by Paytm
$paramList["EMAIL"] = 'abc@gmail.com'; // customer email id
$paramList["MOBILE_NO"] = '9999999999'; // customer 10 digit mobile no.

$checkSum = getChecksumFromArray($paramList,PAYTM_MERCHANT_KEY);
$paramList["CHECKSUMHASH"] = $checkSum;

echo json_encode($paramList);

?> 

Step 9: (Simple Android App with Paytm integration).

Start Android Studio and Create a new Project.

paytm android


Step 10 : Add two Library of android ( 1 .paytm sdk, 2 .volley ) in build.gradle
Also Add the Internet Permission first in AndroidManifest.xml

in AndroidManifest.xml 

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

in build.gradle
 
 compile 'com.android.volley:volley:1.1.0'
    compile 'com.paytm:pgplussdk:1.1.3'

volley paytm


Then Sync now.

Step : 11 Create Layout 


 
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".MainActivity">
<LinearLayout
    android:padding="10dp"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <ImageView
        android:src="@drawable/books"
        android:layout_width="100dp"
        android:layout_height="100dp" />
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <TextView
            android:padding="10dp"
            android:text="Book Sample"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
            <TextView
                android:textColor="#000"
                android:padding="10dp"
                android:text="Rs 25.00"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
        </LinearLayout>
        <Button
            android:layout_gravity="end"
            android:layout_margin="5dp"
            android:padding="10dp"
            android:textColor="#fff"
            android:background="@color/colorPrimary"
            android:text="Buy"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</LinearLayout>

</android.support.constraint.ConstraintLayout>

server code for creating checksum

  
   public void ServerResponse(){
        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest sr = new StringRequest(com.android.volley.Request.Method.POST, "http://192.168.43.110/Php/generateChecksum.php", new com.android.volley.Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //progressDialog.dismiss();
                try {
                    Map<String,String> map=new HashMap<>();
                    JSONObject jsonObj = new JSONObject(response);
                    for(int i=0;i<jsonObj.length();i++){
                        map.put("MID",jsonObj.getString("MID"));
                        map.put("ORDER_ID",jsonObj.getString("ORDER_ID"));
                        map.put("CUST_ID",jsonObj.getString("CUST_ID"));
                        map.put("INDUSTRY_TYPE_ID",jsonObj.getString("INDUSTRY_TYPE_ID"));
                        map.put("CHANNEL_ID",jsonObj.getString("CHANNEL_ID"));
                        map.put("TXN_AMOUNT",jsonObj.getString("TXN_AMOUNT"));
                        map.put("WEBSITE",jsonObj.getString("WEBSITE"));
                        map.put("CALLBACK_URL",jsonObj.getString("CALLBACK_URL"));
                        map.put("EMAIL",jsonObj.getString("EMAIL"));
                        map.put("MOBILE_NO",jsonObj.getString("MOBILE_NO"));
                        map.put("CHECKSUMHASH",jsonObj.getString("CHECKSUMHASH"));
                        PaytmPay(map);
                    }



                } catch (JSONException e) {
                    Toast.makeText(MainActivity.this, "Failed To Parse Response", Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
                Log.d("Response", response);

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("Errors", String.valueOf(error));
            }
        });
        queue.add(sr);
        sr.setRetryPolicy(new DefaultRetryPolicy(
                20000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }

Payment Method Foy Paytm

    public void PaytmPay(Map<String,String> paramMap) {
        PaytmPGService Service = null;
        Service = PaytmPGService.getStagingService();
        PaytmOrder Order = new PaytmOrder((HashMap<String, String>) paramMap);
        Service.initialize(Order, null);
        Service.startPaymentTransaction(this, true, true, new PaytmPaymentTransactionCallback() {

            @Override
            public void someUIErrorOccurred(String inErrorMessage) {
                Log.d("LOG", "UI Error Occur.");
                Toast.makeText(getApplicationContext(), " UI Error Occur. ", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onTransactionResponse(Bundle inResponse) {
                Log.d("LOG", "Payment Transaction : " + inResponse);
                Toast.makeText(getApplicationContext(), "Payment Transaction response "+inResponse.toString(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void networkNotAvailable() {
                Log.d("LOG", "UI Error Occur.");
                Toast.makeText(getApplicationContext(), " UI Error Occur. ", Toast.LENGTH_LONG).show();
            }

            @Override
            public void clientAuthenticationFailed(String inErrorMessage) {
                Log.d("LOG", "UI Error Occur.");
                Toast.makeText(getApplicationContext(), " Severside Error "+ inErrorMessage, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onErrorLoadingWebPage(int iniErrorCode,
                                              String inErrorMessage, String inFailingUrl) {
                Log.d("LOG",inErrorMessage);
            }
            @Override
            public void onBackPressedCancelTransaction() {
                Log.d("LOG","Back");
// TODO Auto-generated method stub
            }

            @Override
            public void onTransactionCancel(String inErrorMessage, Bundle inResponse) {
                Log.d("LOG", "Payment Transaction Failed " + inErrorMessage);
                Toast.makeText(getBaseContext(), "Payment Transaction Failed ", Toast.LENGTH_LONG).show();
            }

        });

    }

Complete MainActivity.java Code :
package paytmdemo.supercoders.in.paytmpaymentgateway;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.paytm.pgsdk.PaytmClientCertificate;
import com.paytm.pgsdk.PaytmOrder;
import com.paytm.pgsdk.PaytmPGService;
import com.paytm.pgsdk.PaytmPaymentTransactionCallback;

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

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

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=(Button)findViewById(R.id.pay);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ServerResponse();
            }
        });
    }

    public void ServerResponse(){
        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest sr = new StringRequest(com.android.volley.Request.Method.POST, "http://192.168.43.110/Php/generateChecksum.php", new com.android.volley.Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //pro   gressDialog.dismiss();
                try {
                    Map<String,String> map=new HashMap<>();
                    JSONObject jsonObj = new JSONObject(response);
                    for(int i=0;i<jsonObj.length();i++){
                        map.put("MID",jsonObj.getString("MID"));
                        map.put("ORDER_ID",jsonObj.getString("ORDER_ID"));
                        map.put("CUST_ID",jsonObj.getString("CUST_ID"));
                        map.put("INDUSTRY_TYPE_ID",jsonObj.getString("INDUSTRY_TYPE_ID"));
                        map.put("CHANNEL_ID",jsonObj.getString("CHANNEL_ID"));
                        map.put("TXN_AMOUNT",jsonObj.getString("TXN_AMOUNT"));
                        map.put("WEBSITE",jsonObj.getString("WEBSITE"));
                        map.put("CALLBACK_URL",jsonObj.getString("CALLBACK_URL"));
                        map.put("EMAIL",jsonObj.getString("EMAIL"));
                        map.put("MOBILE_NO",jsonObj.getString("MOBILE_NO"));
                        map.put("CHECKSUMHASH",jsonObj.getString("CHECKSUMHASH"));
                        PaytmPay(map);
                    }



                } catch (JSONException e) {
                    Toast.makeText(MainActivity.this, "Failed To Parse Response", Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
                Log.d("Response", response);

            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("Errors", String.valueOf(error));
            }
        });
        queue.add(sr);
        sr.setRetryPolicy(new DefaultRetryPolicy(
                20000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }

    public void PaytmPay(Map<String,String> paramMap) {
        PaytmPGService Service = null;
        Service = PaytmPGService.getStagingService();
        PaytmOrder Order = new PaytmOrder((HashMap<String, String>) paramMap);
        Service.initialize(Order, null);
        Service.startPaymentTransaction(this, true, true, new PaytmPaymentTransactionCallback() {

            @Override
            public void someUIErrorOccurred(String inErrorMessage) {
                Log.d("LOG", "UI Error Occur.");
                Toast.makeText(getApplicationContext(), " UI Error Occur. ", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onTransactionResponse(Bundle inResponse) {
                Log.d("LOG", "Payment Transaction : " + inResponse);
                Toast.makeText(getApplicationContext(), "Payment Transaction response "+inResponse.toString(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void networkNotAvailable() {
                Log.d("LOG", "UI Error Occur.");
                Toast.makeText(getApplicationContext(), " UI Error Occur. ", Toast.LENGTH_LONG).show();
            }

            @Override
            public void clientAuthenticationFailed(String inErrorMessage) {
                Log.d("LOG", "UI Error Occur.");
                Toast.makeText(getApplicationContext(), " Severside Error "+ inErrorMessage, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onErrorLoadingWebPage(int iniErrorCode,
                                              String inErrorMessage, String inFailingUrl) {
                Log.d("LOG",inErrorMessage);
            }
            @Override
            public void onBackPressedCancelTransaction() {
                Log.d("LOG","Back");
// TODO Auto-generated method stub
            }

            @Override
            public void onTransactionCancel(String inErrorMessage, Bundle inResponse) {
                Log.d("LOG", "Payment Transaction Failed " + inErrorMessage);
                Toast.makeText(getBaseContext(), "Payment Transaction Failed ", Toast.LENGTH_LONG).show();
            }

        });

    }


}

Output : 

Paytm payment GatewayPaytm payment Gateway


Download Complete Source Code : - 

Download Paytm Payment Gateway Source Code
0