Thursday 7 December 2017

Encryption Decryption Example Android Using AES Alogirthm







activity_main.xml
-------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="android.anil.com.demoencryptiondecryption.MainActivity">


    <EditText
        android:id="@+id/editText_value"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter any  value!"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/button_encryption"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Encrypt" />

    <TextView
        android:id="@+id/textView_disencry"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="" />

    <Button
        android:id="@+id/button_discryption"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Decrypt" />

    <TextView
        android:id="@+id/textView_disde"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="" />
</LinearLayout>

AESHelper.Java
------------------
package android.anil.com.demoencryptiondecryption.utils;

import android.util.Base64;
import android.util.Log;

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by Anil .
 */

public class AESHelper {

    private static final String TAG = "AESCrypt";

    //AESCrypt-ObjC uses CBC and PKCS7Padding
    private static final String AES_MODE = "AES/CBC/PKCS7Padding";
    private static final String CHARSET = "UTF-8";

    //AESCrypt-ObjC uses SHA-256 (and so a 256-bit key)
    private static final String HASH_ALGORITHM = "SHA-256";

    //AESCrypt-ObjC uses blank IV (not the best security, but the aim here is compatibility)
    private static final byte[] ivBytes = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};

    //togglable log option (please turn off in live!)
    public static boolean DEBUG_LOG_ENABLED = false;


    /**
     * Generates SHA256 hash of the password which is used as key
     *
     * @param password used to generated key
     * @return SHA256 of the password
     */
    private static SecretKeySpec generateKey(final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        final MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM);
        byte[] bytes = password.getBytes("UTF-8");
        digest.update(bytes, 0, bytes.length);
        byte[] key = digest.digest();

        log("SHA-256 key ", key);

        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        return secretKeySpec;
    }


    /**
     * Encrypt and encode message using 256-bit AES with key generated from password.
     *
     * @param password used to generated key
     * @param message  the thing you want to encrypt assumed String UTF-8
     * @return Base64 encoded CipherText
     * @throws GeneralSecurityException if problems occur during encryption
     */
    public static String encrypt(final String password, String message)
            throws GeneralSecurityException {

        try {
            final SecretKeySpec key = generateKey(password);

            log("message", message);

            byte[] cipherText = encrypt(key, ivBytes, message.getBytes(CHARSET));

            //NO_WRAP is important as was getting \n at the end
            String encoded = Base64.encodeToString(cipherText, Base64.NO_WRAP);
            log("Base64.NO_WRAP", encoded);
            return encoded;
        } catch (UnsupportedEncodingException e) {
            if (DEBUG_LOG_ENABLED)
                Log.e(TAG, "UnsupportedEncodingException ", e);
            throw new GeneralSecurityException(e);
        }
    }


    /**
     * More flexible AES encrypt that doesn't encode
     *
     * @param key     AES key typically 128, 192 or 256 bit
     * @param iv      Initiation Vector
     * @param message in bytes (assumed it's already been decoded)
     * @return Encrypted cipher text (not encoded)
     * @throws GeneralSecurityException if something goes wrong during encryption
     */
    public static byte[] encrypt(final SecretKeySpec key, final byte[] iv, final byte[] message)
            throws GeneralSecurityException {
        final Cipher cipher = Cipher.getInstance(AES_MODE);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
        byte[] cipherText = cipher.doFinal(message);

        log("cipherText", cipherText);

        return cipherText;
    }


    /**
     * Decrypt and decode ciphertext using 256-bit AES with key generated from password
     *
     * @param password                used to generated key
     * @param base64EncodedCipherText the encrpyted message encoded with base64
     * @return message in Plain text (String UTF-8)
     * @throws GeneralSecurityException if there's an issue decrypting
     */
    public static String decrypt(final String password, String base64EncodedCipherText)
            throws GeneralSecurityException {

        try {
            final SecretKeySpec key = generateKey(password);

            log("base64EncodedCipherText", base64EncodedCipherText);
            byte[] decodedCipherText = Base64.decode(base64EncodedCipherText, Base64.NO_WRAP);
            log("decodedCipherText", decodedCipherText);

            byte[] decryptedBytes = decrypt(key, ivBytes, decodedCipherText);

            log("decryptedBytes", decryptedBytes);
            String message = new String(decryptedBytes, CHARSET);
            log("message", message);


            return message;
        } catch (UnsupportedEncodingException e) {
            if (DEBUG_LOG_ENABLED)
                Log.e(TAG, "UnsupportedEncodingException ", e);

            throw new GeneralSecurityException(e);
        }
    }


    /**
     * More flexible AES decrypt that doesn't encode
     *
     * @param key               AES key typically 128, 192 or 256 bit
     * @param iv                Initiation Vector
     * @param decodedCipherText in bytes (assumed it's already been decoded)
     * @return Decrypted message cipher text (not encoded)
     * @throws GeneralSecurityException if something goes wrong during encryption
     */
    public static byte[] decrypt(final SecretKeySpec key, final byte[] iv, final byte[] decodedCipherText)
            throws GeneralSecurityException {
        final Cipher cipher = Cipher.getInstance(AES_MODE);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
        byte[] decryptedBytes = cipher.doFinal(decodedCipherText);

        log("decryptedBytes", decryptedBytes);

        return decryptedBytes;
    }


    private static void log(String what, byte[] bytes) {
        if (DEBUG_LOG_ENABLED)
            Log.d(TAG, what + "[" + bytes.length + "] [" + bytesToHex(bytes) + "]");
    }

    private static void log(String what, String value) {
        if (DEBUG_LOG_ENABLED)
            Log.d(TAG, what + "[" + value.length() + "] [" + value + "]");
    }


    /**
     * Converts byte array to hexidecimal useful for logging and fault finding
     *
     * @param bytes
     * @return
     */
    private static String bytesToHex(byte[] bytes) {
        final char[] hexArray = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
                '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] hexChars = new char[bytes.length * 2];
        int v;
        for (int j = 0; j < bytes.length; j++) {
            v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }


}


MainActivity.Java
-----------------------------

package android.anil.com.demoencryptiondecryption;

import android.anil.com.demoencryptiondecryption.utils.AESHelper;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText editTextValue;
    Button encryptButton, decryptButton;
    TextView disEncrypt, disDiscry;
    String enValue;
    String encryptedString;
    String KEY = "ABCDEFGHIJKLMNOPQRSWXYZ0123456789";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        encryptButton = findViewById(R.id.button_encryption);
        editTextValue = findViewById(R.id.editText_value);
        disEncrypt = findViewById(R.id.textView_disencry);
        disDiscry = findViewById(R.id.textView_disde);
        decryptButton = findViewById(R.id.button_discryption);
        encryptButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                enValue = editTextValue.getText().toString();
                if (enValue != null && !enValue.isEmpty()) {

                    encryptedString = encryption(enValue);
                    disEncrypt.setText(encryptedString);

                } else {
                    Toast.makeText(MainActivity.this, "Please Enter value", Toast.LENGTH_SHORT).show();
                }

            }
        });
        decryptButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String decryptedString = decryption(encryptedString);
                disDiscry.setText(decryptedString);

            }
        });
    }

    public String encryption(String strNormalText) {
        String normalTextEnc = "";
        try {
            normalTextEnc = AESHelper.encrypt(KEY, strNormalText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return normalTextEnc;
    }

    public String decryption(String strEncryptedText) {
        String strDecryptedText = "";
        try {
            strDecryptedText = AESHelper.decrypt(KEY, strEncryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strDecryptedText;
    }
}





Monday 14 August 2017

Recyclerview Radiobutton Android Tutorial









build.gradle
-----------------
 compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.jakewharton:butterknife:8.5.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
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="com.anilsoft.anil.MainActivity">

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

</RelativeLayout>
layout_data.xml
--------------------
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    card_view:cardElevation="5dp"
    card_view:cardUseCompatPadding="true">

    <RadioButton
        android:id="@+id/rview_radiobutton"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:scaleType="fitXY" />


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="15dp">

        <TextView
            android:id="@+id/textView_rvname"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="74dp"
            android:layout_marginStart="74dp"
            android:text="TextView"
            android:textSize="17sp" />

        <TextView
            android:id="@+id/textView_rvloc"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="74dp"
            android:layout_marginStart="74dp"
            android:text="A"
            android:textSize="17sp" />
    </LinearLayout>

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

Utils.Java
----------------
package com.anilsoft.anil.utils;

import com.anilsoft.anil.model.Student;

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

/**
 * Created by Anil on 8/14/2017.
 */

public class Utils {

    public static List<Student> loadStudentData() {
        List<Student> llStudentList = new ArrayList<>();
        llStudentList.add(new Student("Anil", "Tadipatri,RayalaSeema"));
        llStudentList.add(new Student("Aswartha", "Jammalamadugu,RayalaSeema"));
        llStudentList.add(new Student("Jayachandra", "Chittor,RayalaSeema"));
        llStudentList.add(new Student("Mahendra", "Kadapa,RayalaSeema"));
        llStudentList.add(new Student("Kishore", "Rajampeta,RayalaSeema"));
        llStudentList.add(new Student("Rakesh", "Nandyala,RayalaSeema"));
        llStudentList.add(new Student("Suresh", "Kurnool,RayalaSeema"));
        llStudentList.add(new Student("Sudhakar", "Ananthapur,RayalaSeema"));
        llStudentList.add(new Student("Prasad", "Ananthapur,RayalaSeema"));
        return llStudentList;
    }
}
Student.Java
------------------
package com.anilsoft.anil.model;

/**
 * Created by Anil on 8/14/2017.
 */

public class Student {
    String name;
    String location;

    public Student(String name, String location) {
        this.name = name;
        this.location = location;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}

StudentAdapter.Java
------------------------
package com.anilsoft.anil.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.anilsoft.anil.R;
import com.anilsoft.anil.model.Student;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Anil on 8/14/2017.
 */

public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.StudentVH> {
    Context context;
    List<Student> list;
    public int mSelectedItem = -1;

    public StudentAdapter(Context context, List<Student> list) {
        this.context = context;
        this.list = list;
    }


    @Override
    public StudentVH onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_data, parent, false);

        return new StudentVH(view);
    }

    @Override
    public void onBindViewHolder(StudentVH holder, int position) {
        holder.rviewRadiobutton.setChecked(position == mSelectedItem);
        holder.loadData(position);


    }

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

    public class StudentVH extends RecyclerView.ViewHolder {
        @BindView(R.id.textView_rvname)
        TextView textViewRvname;
        @BindView(R.id.textView_rvloc)
        TextView textViewRvloc;
        @BindView(R.id.rview_radiobutton)
        RadioButton rviewRadiobutton;


        public StudentVH(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);


        }

        void loadData(final int position) {
            textViewRvname.setText(list.get(position).getName());
            textViewRvloc.setText(list.get(position).getLocation());
            View.OnClickListener listener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mSelectedItem = getAdapterPosition();
                    notifyDataSetChanged();
                    Toast.makeText(context, "" + list.get(position).getName() + "\n" + list.get(position).getLocation(), Toast.LENGTH_SHORT).show();


                }
            };
            rviewRadiobutton.setOnClickListener(listener);
            itemView.setOnClickListener(listener);
        }
    }

}

MainActivity.Java
---------------------------
package com.anilsoft.anil;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.anilsoft.anil.adapter.StudentAdapter;
import com.anilsoft.anil.utils.Utils;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.recyclerview_demo)
    RecyclerView recyclerviewDemo;

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


    }

    private void loadStudentInformation() {
        StudentAdapter studentAdapter = new StudentAdapter(MainActivity.this, Utils.loadStudentData());
        recyclerviewDemo.setLayoutManager(new LinearLayoutManager(this));
        recyclerviewDemo.setAdapter(studentAdapter);
    }
}






Friday 17 February 2017

Recyclerview with Tabs using Viewpager Example Android

Android Applications In earlier days we  are using  ActionBar Tabs over ViewPager   But this ActionBar Tabs is deprecated in material design(Introduced Android 5.0(Lollipop)).

 So for that we need to use Android Material Design Tabs for implementing tabs in our app.
We have  to seen  like Google Play Store , Whatsapp and many applications  are using Android Material Design Tabs.

Today I’m discussing how to implement this Material Design Tabs in our application.







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"
    tools:context="com.anil.anil.recyclerviewwithtabs.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        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:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay"></android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tablayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabGravity="fill"
            app:tabMode="fixed" />
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        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"
        android:visibility="gone"
        app:srcCompat="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>

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

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

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


    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
layout_tomarrow.xml
--------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


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

list_row.xml
------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:orientation="vertical"
    android:padding="16dp">

    <TextView
        android:id="@+id/country_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Name"
        android:textSize="20sp" />


    <TextView
        android:id="@+id/country_iso"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ISo"
        android:textSize="16sp" />

</LinearLayout>

Today.java
--------------
package com.pass.anil.recyclerviewwithtabs.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.anil.anil.recyclerviewwithtabs.R;
import com.anil.anil.recyclerviewwithtabs.adapter.RVAdapter;
import com.anil.anil.recyclerviewwithtabs.model.Student;

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

/**
 * Created by Anil on 2/17/2017.
 */

public class Today extends Fragment {
    RecyclerView student_rview;
    List<Student> list_student;
    RVAdapter rvAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.layout_today, container, false);
        loadStudent();
        student_rview = (RecyclerView) view.findViewById(R.id.recyclerview);

        rvAdapter = new RVAdapter(getActivity(), list_student);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        student_rview.setLayoutManager(layoutManager);
        student_rview.setAdapter(rvAdapter);

        return view;
    }

    void loadStudent() {
        list_student = new ArrayList<>();
        list_student.add(new Student("Anil", "Tadipatri"));
        list_student.add(new Student("Bhaskar", "Tadipatri"));
        list_student.add(new Student("Manohar", "Tadipatri"));
        list_student.add(new Student("Gopal", "Tadipatri"));
        list_student.add(new Student("Krishna", "Tadipatri"));
        list_student.add(new Student("JayaRam", "Tadipatri"));
        list_student.add(new Student("Kadiri", "Tadipatri"));
//        rvAdapter.notifyDataSetChanged();

    }
}
Yesterday.Java
----------------------
package com.pass.anil.recyclerviewwithtabs.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.anil.anil.recyclerviewwithtabs.R;
import com.anil.anil.recyclerviewwithtabs.adapter.RVAdapter;
import com.anil.anil.recyclerviewwithtabs.model.Student;

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

/**
 * Created by Anil on 2/17/2017.
 */

public class Yesterday extends Fragment {
    RecyclerView student_rview;
    List<Student> list_student;
    RVAdapter rvAdapter;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.layout_yesterday, container, false);
        loadStudent();
        student_rview = (RecyclerView) view.findViewById(R.id.recyclerview);

        rvAdapter = new RVAdapter(getActivity(), list_student);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        student_rview.setLayoutManager(layoutManager);
        student_rview.setAdapter(rvAdapter);

        return view;
    }

    void loadStudent() {
        list_student = new ArrayList<>();
        list_student.add(new Student("Adi Reddy", "S.G.Palli"));
        list_student.add(new Student("N.Swamy", "S.G.Palli"));
        list_student.add(new Student("Sriram", "S.G.Palli"));
        list_student.add(new Student("Ram", "S.G.Palli"));

//        rvAdapter.notifyDataSetChanged();

    }
}

Tomarrow.Java
----------------------
package com.pass.anil.recyclerviewwithtabs.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.anil.anil.recyclerviewwithtabs.R;
import com.anil.anil.recyclerviewwithtabs.adapter.RVAdapter;
import com.anil.anil.recyclerviewwithtabs.model.Student;

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

/**
 * Created by Anil on 2/17/2017.
 */

public class Tomorrow extends Fragment {
    RecyclerView student_rview;
    List<Student> list_student;
    RVAdapter rvAdapter;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.layout_tommarow, container, false);
        loadStudent();
        student_rview = (RecyclerView) view.findViewById(R.id.recyclerview);

        rvAdapter = new RVAdapter(getActivity(), list_student);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        student_rview.setLayoutManager(layoutManager);
        student_rview.setAdapter(rvAdapter);

        return view;
    }

    void loadStudent() {
        list_student = new ArrayList<>();
        list_student.add(new Student("Mahesh", "Pappaka"));
        list_student.add(new Student("Anand", "Pappaka"));
        list_student.add(new Student("Aravind", "Pappaka"));
        list_student.add(new Student("Prasanth", "Pappaka"));
        list_student.add(new Student("Kiran", "Pappaka"));
        list_student.add(new Student("Charan", "Pappaka"));

//        rvAdapter.notifyDataSetChanged();

    }
}

Student.Java
-------------------
package com.anil.anil.recyclerviewwithtabs.model;

/**
 * Created by Anil on 2/17/2017.
 */

public class Student {
    String name,add;

    public Student(String name, String add) {
        this.name = name;
        this.add = add;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAdd() {
        return add;
    }

    public void setAdd(String add) {
        this.add = add;
    }
}

ItemViewHolder.Java
--------------------------
package com.anil.anil.recyclerviewwithtabs.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.anil.anil.recyclerviewwithtabs.R;
import com.anil.anil.recyclerviewwithtabs.model.Student;

public class ItemViewHolder extends RecyclerView.ViewHolder {

    public TextView name_TextView;
    public TextView iso_TextView;


    public ItemViewHolder(View itemView) {
        super(itemView);
        itemView.setClickable(true);
        name_TextView = (TextView) itemView.findViewById(R.id.country_name);
        iso_TextView = (TextView) itemView.findViewById(R.id.country_iso);

    }

    public void bind(Student student) {
        name_TextView.setText(student.getName());
        iso_TextView.setText(student.getAdd() );

    }


}

RVAdapter.Java
-------------------
package com.pass.anil.recyclerviewwithtabs.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.anil.anil.recyclerviewwithtabs.R;
import com.anil.anil.recyclerviewwithtabs.model.Student;

import java.util.List;

/**
 * Created by Anil on 2/17/2017.
 */

public class RVAdapter extends RecyclerView.Adapter<ItemViewHolder> {
    Context mcContext;
    List<Student> studentList;

    public RVAdapter(Context mcContext, List<Student> studentList) {
        this.mcContext = mcContext;
        this.studentList = studentList;
    }


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

    @Override
    public void onBindViewHolder(ItemViewHolder holder, int position) {
        Student student = studentList.get(position);
        holder.bind(student);
    }

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

MainActivity.Java
---------------------------
package com.anil.anil.recyclerviewwithtabs;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.anil.anil.recyclerviewwithtabs.adapter.ViewPagerAdapter;
import com.anil.anil.recyclerviewwithtabs.fragments.Today;
import com.anil.anil.recyclerviewwithtabs.fragments.Tomorrow;
import com.anil.anil.recyclerviewwithtabs.fragments.Yesterday;

public class MainActivity extends AppCompatActivity {

    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


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

        setupViewPager(mViewPager);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
        tabLayout.setupWithViewPager(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);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new Today(), "Today");
        adapter.addFragment(new Yesterday(), "Yesterday");
        adapter.addFragment(new Tomorrow(), "Tomorrow");
        viewPager.setAdapter(adapter);

    }


}


                                        

Wednesday 31 August 2016

Pick Image from Camera or Gallery -Android

 in this tutorial I will be showing how to get an Image from the user's Camera or from his gallery.

In this Tutorial User will have two choices:
Capture photo/ image from camera in Android
Choose photo/ image from gallery in Android

User will need to choose one option from the above two options and then depending on the option chosen by the user, we will either capture an image from the camera or open the gallery.









activity_main.xml
--------------------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
android:orientation="vertical"
  
tools:context="com.sgp.anil.takephotocameraandgallery.MainActivity">

    <
Button
       
android:id="@+id/button_takephoto"
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="30dp"
       
android:text="Select Photo" />

    <
ImageView
       
android:id="@+id/imageView_show"
       
android:layout_width="250dp"
       
android:layout_height="250dp"
       
android:layout_gravity="center_horizontal"
       
android:layout_marginTop="25dp" />
</
LinearLayout>

Utility.Java
-------------------------
package com.sgp.anil.takephotocameraandgallery;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

/**
 * Created by Anil on 31/08/16.
 */
public class Utility {
   
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
   
public static final int MY_PERMISSIONS_REQUEST_CAMERA = 124;

   
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
   
public static boolean checkPermission(final Context context) {
       
int currentAPIVersion = Build.VERSION.SDK_INT;
       
if (currentAPIVersion >= Build.VERSION_CODES.M) {
           
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
               
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                           
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);


                }
else {
                    ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                           
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                }
                
return false;
            }
else if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
               
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.CAMERA)) {
                    ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA);

                }
else {
                    ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.CAMERA}, MY_PERMISSIONS_REQUEST_CAMERA);

                }
               
return false;
            }
else {
               
return true;
            }
        }
else {
           
return true;
        }
    }
}

MainActivity.Java
---------------------------
package com.sgp.anil.takephotocameraandgallery;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    Button
takephotobtn;
    ImageView
imageView;
   
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
   
private String userChoosenTask;

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
        setContentView(R.layout.
activity_main);
       
takephotobtn = (Button) findViewById(R.id.button_takephoto);
       
imageView = (ImageView) findViewById(R.id.imageView_show);
       
takephotobtn.setOnClickListener(new View.OnClickListener() {
           
@Override
           
public void onClick(View view) {
                takePhoto();


            }
        });
    }

   
@Override
   
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
       
switch (requestCode) {
           
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE & Utility.MY_PERMISSIONS_REQUEST_CAMERA:
               
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {


                   
if (userChoosenTask.equals("Take Photo Gallery"))
                        galleryIntent();
                }
else {
                   
//code for deny
               
}
               
break;

           
case Utility.MY_PERMISSIONS_REQUEST_CAMERA:
               
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                   
if (userChoosenTask.equals("Take Photo Camera"))
                        cameraIntent();

                }
else {
                   
//code for deny
               
}
               
break;
        }
    }

   
private void takePhoto() {
       
final CharSequence[] items = {"Take Photo Camera", "Take Photo Gallery"};

        AlertDialog.Builder builder =
new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(
"Add Photo!");
        builder.setItems(items,
new DialogInterface.OnClickListener() {
           
@Override
           
public void onClick(DialogInterface dialog, int item) {
               
boolean result = Utility.checkPermission(MainActivity.this);

               
if (items[item].equals("Take Photo Camera")) {
                   
userChoosenTask = "Take Photo Camera";
                   
if (result)
                        cameraIntent();

                }
else if (items[item].equals("Take Photo Gallery")) {
                   
userChoosenTask = "Take Photo Gallery";
                   
if (result)
                        galleryIntent();

                }
            }
        });
        builder.show();
    }

   
private void galleryIntent() {
        Intent intent =
new Intent();
        intent.setType(
"image/*");
        intent.setAction(Intent.
ACTION_GET_CONTENT);//
       
startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_FILE);
    }

   
private void cameraIntent() {
        Intent intent =
new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent,
REQUEST_CAMERA);
    }

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

       
if (resultCode == Activity.RESULT_OK) {
           
if (requestCode == SELECT_FILE)
                onSelectFromGalleryResult(data);
           
else if (requestCode == REQUEST_CAMERA)
                onCaptureImageResult(data);
        }
    }

   
private void onCaptureImageResult(Intent data) {
        Bitmap thumbnail = (Bitmap) data.getExtras().get(
"data");
        ByteArrayOutputStream bytes =
new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.
JPEG, 90, bytes);

        File destination =
new File(Environment.getExternalStorageDirectory(),
                System.currentTimeMillis() +
".jpg");

        FileOutputStream fo;
       
try {
            destination.createNewFile();
            fo =
new FileOutputStream(destination);
            fo.write(bytes.toByteArray());
            fo.close();
        }
catch (FileNotFoundException e) {
            e.printStackTrace();
        }
catch (IOException e) {
            e.printStackTrace();
        }

       
imageView.setImageBitmap(thumbnail);
    }

   
@SuppressWarnings("deprecation")
   
private void onSelectFromGalleryResult(Intent data) {

        Bitmap bm =
null;
       
if (data != null) {
           
try {
                bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
            }
catch (IOException e) {
                e.printStackTrace();
            }
        }

       
imageView.setImageBitmap(bm);
    }

}

Encryption Decryption Example Android Using AES Alogirthm

activity_main.xml ------------------------- <?xml version="1.0" encoding="utf-8"?> <LinearLayou...