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);
    }

}