Thursday, 13 October 2016

How to add back arrow button in toolbar android

How to add back array button in toolbar android

1.add toolbar in layout xml file first

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="48dp"
/>
   
2.In activity file give reference to toolbar

Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    //What to do on back clicked
    onBackPressed();
    }
});

Wednesday, 12 October 2016

Android Searchview in the toolbar

How to add searchview to toolbar in android
***********************************************************
add below gradle dependencies

compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:recyclerview-v7:23.0.1'
compile 'org.immutables:gson:2.1.0.alpha'
***********************************************************
manifest file

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

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

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

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

</manifest>
******************************************************************
menu file
search icon added to it

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:compat="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_search"
        android:title="Search"
        android:icon="@drawable/ic_search_white_24dp"
        compat:showAsAction="ifRoom"/>

</menu>
**********************************************************************
Locations.java
custom object locations are created

public class Locations {
    public String location_name;
    public String location_id;
    public Locations(){

    }
    public Locations(String location_name, String location_id){
        this.location_id = location_id;
        this.location_name = location_name;
    }
    public String getLocation_name() {
        return location_name;
    }

    public void setLocation_name(String location_name) {
        this.location_name = location_name;
    }

    public String getLocation_id() {
        return location_id;
    }

    public void setLocation_id(String location_id) {
        this.location_id = location_id;
    }
}
***********************************************************************
MainActivity file
public class MainActivity extends AppCompatActivity {
    Toolbar toolbar;

    ArrayList<Locations> locationses = new ArrayList<Locations>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Locations locations1=new Locations();
        locations1.setLocation_id("1");
        locations1.setLocation_name("vijayanagar");
        Locations locations2=new Locations();
        locations2.setLocation_id("2");
        locations2.setLocation_name("rajajinagar");
        Locations locations3=new Locations();
        locations3.setLocation_id("3");
        locations3.setLocation_name("ramurthy nagar");
        Locations locations4=new Locations();
        locations4.setLocation_id("4");
        locations4.setLocation_name("jayanagar");
        Locations locations5=new Locations();
        locations5.setLocation_id("5");
        locations5.setLocation_name("jcnagar");

        locationses.add(locations1);
        locationses.add(locations2);
        locationses.add(locations3);
        locationses.add(locations4);
        locationses.add(locations5);
        toolBarData();

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_search, menu);


        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        switch (id) {

            case android.R.id.home:
                finish();
                break;

            case R.id.action_search:
                loadToolBarSearch();
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    private void toolBarData() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("MaterialDialogSearchView");
        toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        setSupportActionBar(toolbar);
    }

    public void loadToolBarSearch() {


        ArrayList<Locations> locationStored = SharedPreference.loadList(MainActivity.this, Utils.PREFS_NAME, Utils.KEY_COUNTRIES);

        View view = MainActivity.this.getLayoutInflater().inflate(R.layout.view_toolbar_search, null);
        LinearLayout parentToolbarSearch = (LinearLayout) view.findViewById(R.id.parent_toolbar_search);
        ImageView imgToolBack = (ImageView) view.findViewById(R.id.img_tool_back);
        final EditText edtToolSearch = (EditText) view.findViewById(R.id.edt_tool_search);
        ImageView imgToolMic = (ImageView) view.findViewById(R.id.img_tool_mic);
        final ListView listSearch = (ListView) view.findViewById(R.id.list_search);
        final TextView txtEmpty = (TextView) view.findViewById(R.id.txt_empty);

        Utils.setListViewHeightBasedOnChildren(listSearch);

        edtToolSearch.setHint("Search your country");

        final Dialog toolbarSearchDialog = new Dialog(MainActivity.this, R.style.MaterialSearch);
        toolbarSearchDialog.setContentView(view);
        toolbarSearchDialog.setCancelable(false);
        toolbarSearchDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        toolbarSearchDialog.getWindow().setGravity(Gravity.BOTTOM);
        toolbarSearchDialog.show();

        toolbarSearchDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        locationStored = (locationStored != null && locationStored.size() > 0) ? locationStored : new ArrayList<Locations>();
        final SearchAdapter searchAdapter = new SearchAdapter(MainActivity.this, locationStored, false);

        listSearch.setVisibility(View.VISIBLE);
        listSearch.setAdapter(searchAdapter);


        listSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {

                Locations locations = (Locations)adapterView.getItemAtPosition(position);
                SharedPreference.addList(MainActivity.this, Utils.PREFS_NAME, Utils.KEY_COUNTRIES,locations );
                edtToolSearch.setText(locations.getLocation_name());
                listSearch.setVisibility(View.GONE);


            }
        });
        edtToolSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                listSearch.setVisibility(View.VISIBLE);
                searchAdapter.updateList(locationses, true);


            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                ArrayList<Locations> filterList = new ArrayList<Locations>();
                boolean isNodata = false;
                if (s.length() > 0) {
                    for (int i = 0; i < locationses.size(); i++) {


                        if (locationses.get(i).getLocation_name().toLowerCase().startsWith(s.toString().trim().toLowerCase())) {

                            filterList.add(locationses.get(i));

                            listSearch.setVisibility(View.VISIBLE);
                            searchAdapter.updateList(filterList, true);
                            isNodata = true;
                        }
                    }
                    if (!isNodata) {
                        listSearch.setVisibility(View.GONE);
                        txtEmpty.setVisibility(View.VISIBLE);
                        txtEmpty.setText("No data found");
                    }
                } else {
                    listSearch.setVisibility(View.GONE);
                    txtEmpty.setVisibility(View.GONE);
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        imgToolBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toolbarSearchDialog.dismiss();
            }
        });

        imgToolMic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    edtToolSearch.setText("");
            }
        });
    }
}
***************************************************************************8
sharedpreference class, am using this class to save recent searches

package com.takeoffandroid.materialdialogsearchview;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class SharedPreference {

    // Avoid magic numbers.
    private static final int MAX_SIZE = 2;


    public SharedPreference() {
        super();
    }




    public static void storeList(Context context,String pref_name, String key, List<Locations> locations) {

        SharedPreferences settings;
        SharedPreferences.Editor editor;
        settings = context.getSharedPreferences(Utils.PREFS_NAME, Context.MODE_PRIVATE);
        editor = settings.edit();
        Gson gson = new Gson();
        String jsonFavorites = gson.toJson(locations);
        editor.putString(key, jsonFavorites);
        editor.apply();
    }



    public static ArrayList<Locations> loadList(Context context,String pref_name, String key) {

        SharedPreferences settings;
        List<Locations> favorites=new ArrayList<>();
        settings = context.getSharedPreferences(pref_name, Context.MODE_PRIVATE);
    if (settings.contains(key)) {
            Gson gson = new Gson();
            String jsonFavorites = settings.getString(key, null);
            Log.d("gson====",jsonFavorites);
            Type type = new TypeToken<List<Locations>>(){}.getType();
            favorites = gson.fromJson(jsonFavorites, type);
            return (ArrayList<Locations>) favorites;
        } else{
            return null;
        }
    }


    public static void addList(Context context, String pref_name, String key,Locations locations) {
        List<Locations> favorites = loadList(context, pref_name, key);

        if (favorites == null){
            favorites = new ArrayList<Locations>();
        }

        if(favorites.size() > MAX_SIZE) {
            //favorites.clear();
            favorites.remove(favorites.get(0));
            deleteList(context, pref_name);
        }

        Set<String> location_keys = new HashSet<String>();
        if(favorites.size()==0){
            favorites.add(locations);
        }if(favorites.size()>0) {
//check it out
            for(int index =0; index<favorites.size(); index++){
                location_keys.add(favorites.get(index).getLocation_id());
            }
        }
        if (!location_keys.contains(locations.getLocation_id())){
            favorites.add(locations);
        }
        storeList(context, pref_name, key, favorites);

    }


    public static void deleteList(Context context, String pref_name){

        SharedPreferences myPrefs = context.getSharedPreferences(pref_name,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = myPrefs.edit();
        editor.clear();
        editor.apply();
    }
}
***********************************************************************
search adapter to bind arraylist of custom objects (Locations)

public class SearchAdapter extends BaseAdapter {

    private Context mContext;
    private ArrayList<String> mCountries;
    private LayoutInflater mLayoutInflater;
    private boolean mIsFilterList;
    private ArrayList<Locations> locationsArrayList;

    public SearchAdapter(Context context, ArrayList<Locations> locationsArrayList, boolean isFilterList) {
        this.mContext = context;
        this.locationsArrayList =locationsArrayList;
        this.mIsFilterList = isFilterList;
    }


    public void updateList(ArrayList<Locations> filterList, boolean isFilterList) {
        this.locationsArrayList = filterList;
        this.mIsFilterList = isFilterList;
        notifyDataSetChanged ();
    }

    @Override
    public int getCount() {
        return locationsArrayList.size();
    }

    @Override
    public Locations getItem(int position) {
        return locationsArrayList.get(position);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        ViewHolder holder = null;
        if(v==null){

            holder = new ViewHolder();

            mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            v = mLayoutInflater.inflate(R.layout.list_item_search, parent, false);
            holder.txtCountry = (TextView)v.findViewById(R.id.txt_country);
            v.setTag(holder);
        } else{

            holder = (ViewHolder) v.getTag();
        }

        holder.txtCountry.setText(locationsArrayList.get(position).getLocation_name());

        Drawable searchDrawable,recentDrawable;

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            searchDrawable = mContext.getResources().getDrawable(R.drawable.ic_magnify_grey600_24dp, null);
            recentDrawable = mContext.getResources().getDrawable(R.drawable.ic_backup_restore_grey600_24dp, null);

        } else {
            searchDrawable = mContext.getResources().getDrawable(R.drawable.ic_magnify_grey600_24dp);
            recentDrawable = mContext.getResources().getDrawable(R.drawable.ic_backup_restore_grey600_24dp);
        }
        if(mIsFilterList) {
            holder.txtCountry.setCompoundDrawablesWithIntrinsicBounds(searchDrawable, null, null, null);
        }else {
            holder.txtCountry.setCompoundDrawablesWithIntrinsicBounds(recentDrawable, null, null, null);

        }
        return v;
    }

}

class ViewHolder{
     TextView txtCountry;
}
***************************************************************************************
utils class to save shared preferences name 

public class Utils {

    public static final String PREFS_NAME = "TAKEOFFANDROID";

    public static final String KEY_COUNTRIES = "Countries";

    public static final int REQUEST_CODE = 1234;

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }


    public static boolean isConnectedNetwork (Context context) {

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService (Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo () != null && cm.getActiveNetworkInfo ().isConnectedOrConnecting ();

    }
}
*********************************************************************************
toolbar in main_layout.xml

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    android:fitsSystemWindows="true"
    android:background="?attr/colorPrimary"/>

*********************************************************************************
toolbarsearch.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/white"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="horizontal"
        android:paddingLeft="16dp"
        android:paddingRight="16dp">

        <ImageView
            android:id="@+id/img_tool_back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_arrow_left_grey600_24dp"/>

        <EditText
            android:id="@+id/edt_tool_search"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:background="@null"
            android:hint="Choose your city"
            android:textColorHint="@color/secondary_text"
            android:textColor="@color/secondary_text"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            android:singleLine="true"
            android:textSize="16sp"/>

        <ImageView
            android:id="@+id/img_tool_mic"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_microphone_grey600_24dp"/>
    </LinearLayout>


</LinearLayout>
*********************************************************************************
list_item_search.xml

<TextView
    android:id="@+id/txt_country"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:padding="16dp"
    android:textColor="@color/primary_text"
    android:textSize="16sp"
    android:drawablePadding="20dp"/>
*********************************************************************************
view_toolbar_search.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/parent_toolbar_search"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/trans_black_25"
    android:orientation="vertical">

    <include layout="@layout/include_toolbar_search"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1.5dp"
        android:background="@color/chrome_grey"/>


    <ListView
        android:id="@+id/list_search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:scrollbars="vertical"
        android:divider="@android:color/transparent"
        android:visibility="gone"/>

    <TextView
        android:id="@+id/txt_empty"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/secondary_text"
        android:background="@color/white"
        android:padding="20dp"
        android:gravity="center"
        android:visibility="gone"/>

</LinearLayout>
*****************************************************************************

Saturday, 1 October 2016

JAVA: USING HASHSET TO COUNT UNIQUE ELEMENTS.

COUNT UNIQUE ELEMENTS USING HASHSET IN JAVA

//sometimes you may come across requirement to count unique objects.
//In that case one of the solution is to create a hashset field/attribute in the class.
//For eg. animal is a class with name variable. zoo is a class which holds collections of animals.
//so if i want to count unique animals in zoo. i added hashset in the zoo class. 
//set is a collection which holds only unique elements. but lists holds duplicate values.

import java.util.ArrayList;
import java.util.HashSet;
class Animal{
String name;
public Animal(String name){
this.name = name;
}
}
class Zoo{
//list of animals present in zoo, multiple animals of same species also present in zoo
ArrayList<Animal> animalList = new ArrayList<Animal>();
//to track unique animals hashset is one of the solution
HashSet<String> uniqueAnimals = new HashSet<String>();
}

public class TestZoo{
public static void main(String[] args){
Animal elephant = new Animal("elephant");
Animal dog = new Animal("dog");
//dog repeated twice
Animal anotherDog = new Animal("dog");
Animal crocodile = new Animal("crocodile");
//crocodile repeated twice
Animal anotherCrocodile = new Animal("crocodile");
//add all animals to zoo
Zoo zoo = new Zoo();
ArrayList<Animal> addAnimalsTOzoo = new ArrayList<Animal>();
addAnimalsTOzoo.add(elephant);
addAnimalsTOzoo.add(dog);
addAnimalsTOzoo.add(anotherDog);
addAnimalsTOzoo.add(crocodile);
addAnimalsTOzoo.add(anotherCrocodile);
zoo.animalList = addAnimalsTOzoo; 
//use hashset to count unique animals
HashSet<String> countUniqueAnimals = new HashSet();
countUniqueAnimals.add(elephant.name);
countUniqueAnimals.add(dog.name);
countUniqueAnimals.add(anotherDog.name);
countUniqueAnimals.add(crocodile.name);
countUniqueAnimals.add(anotherCrocodile.name);
zoo.uniqueAnimals = countUniqueAnimals;
System.out.println("unique animals count = "+zoo.uniqueAnimals.size());
}
}


Wednesday, 28 September 2016

Nested RecyclerView or Inner Recycler View in android

Nested RecyclerView Example

Recyclerview is a flexible view for providing a limited window into a large data set.

I am going to display below layout using two recycler views(nested recycler views).





Follow below steps to achieve Nested/Inner Recycler view.

1.copy these dependencies and paste it to app level grade file

compile 'com.android.support:appcompat-v7:24.2.1'
        compile 'com.android.support:recyclerview-v7:24.2.+'
        compile 'com.android.support:cardview-v7:24.2.+'

make sure youd have 24+ android sdk.

/******************************************************************************/
2.copy these model classes

a.EventInformationClass, this class contains dates list and its events list

    public class EventInformation {
    
    private ArrayList<EventDates> eventsDatesList = new ArrayList<>();

    public ArrayList<EventDates> getEventsDatesList() {
        return eventsDatesList;
    }

    public void setEventsDatesList(ArrayList<EventDates> eventsDatesList) {
        this.eventsDatesList = eventsDatesList;
    }
}


b.EventDate class, this class contains list of dates(headings), it contains the list of events on that date.

public class EventDates {
    private String date;
    private ArrayList<Events> eventsArrayList;

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public ArrayList<Events> getEventsArrayList() {
        return eventsArrayList;
    }

    public void setEventsArrayList(ArrayList<Events> eventsArrayList) {
        this.eventsArrayList = eventsArrayList;
    }
}

c.Events class, this class contains event name and event id

public class Events {
    private String eventId;
    private String eventName;

    public String getEventId() {
        return eventId;
    }

    public void setEventId(String eventId) {
        this.eventId = eventId;
    }

    public String getEventName() {
        return eventName;
    }

    public void setEventName(String eventName) {
        this.eventName = eventName;
    }
}
/************************************************************************/

3.create layouts

a.activity_main.xml, this layout corresponds to main activity

<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">
        <android.support.v7.widget.RecyclerView
           android:id="@+id/event_recycler_view_parent"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:scrollbars="vertical" />
</RelativeLayout>

b.event_list_parent_item.xml, this layout corresponds to parent info(here am showing only date and (parent)recyclerview)

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

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

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

</RelativeLayout>

c.event_list_child_item.xml, this layout corresponds to list of events under each dates

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <android.support.v7.widget.CardView
        android:layout_margin="10dp"
        android:layout_width="match_parent"
        android:layout_height="48dp">
        <TextView
            android:id="@+id/event_list_event_name"
            android:paddingLeft="10dp"
            android:layout_gravity="center_vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </android.support.v7.widget.CardView>

</LinearLayout>

/***************************************************************************************/
4.create main activity, data is in json. you should import import org.json.*; to parse json into objects (i deliberately left some data. ex: id and name.)

public class MainActivity extends AppCompatActivity {

    RecyclerView event_recycler_view_parent;
    EventListParentAdapter event_list_parent_adapter;
    
    String jsonString = "{\n" +
            "    \"Id\" : \"1\",\n" +
            "    \"Name\" : \"Ganesha\",\n" +
            "    \"Location\" : \"Bengaluru\",\n" +
            "    \"Event info\" : [ \n" +
            "\t\t\t\t\t\t{\n" +
            "\t\t\t\t\t\t\t\"Date\" : \"29-9-16\",\n" +
            "\t\t\t\t\t\t\t\"events\" : [ \n" +
            "\t\t\t\t\t\t\t\t\t\t\t{\n" +
            "\t\t\t\t\t\t\t\t\t\t\t\t\"eventId\" : \"1\",\n" +
            "\t\t\t\t\t\t\t\t\t\t\t\t\"eventName\" : \"event one\"\n" +
            "\t\t\t\t\t\t\t\t\t\t\t}, \n" +
            "\t\t\t\t\t\t\t\t\t\t\t{\n" +
            "\t\t\t\t\t\t\t\t\t\t\t\t\"eventId\" : \"2\",\n" +
            "\t\t\t\t\t\t\t\t\t\t\t\t\"eventName\" : \"event two\"\n" +
            "\t\t\t\t\t\t\t\t\t\t\t}\n" +
            "\t\t\t\t\t\t\t\t\t\t]\n" +
            "\t\t\t\t\t\t}, \n" +
            "\t\t\t\t\t\t{\n" +
            "\t\t\t\t\t\t\t\"Date\" : \"30-9-16\",\n" +
            "\t\t\t\t\t\t\t\"events\" : [ \n" +
            "\t\t\t\t\t\t\t\t\t\t\t{\n" +
            "\t\t\t\t\t\t\t\t\t\t\t\t\"eventId\" : \"3\",\n" +
            "\t\t\t\t\t\t\t\t\t\t\t\t\"eventName\" : \"event three\"\n" +
            "\t\t\t\t\t\t\t\t\t\t\t}, \n" +
            "\t\t\t\t\t\t\t\t\t\t\t{\n" +
            "\t\t\t\t\t\t\t\t\t\t\t\t\"eventId\" : \"4\",\n" +
            "\t\t\t\t\t\t\t\t\t\t\t\t\"eventName\" : \"event four\"\n" +
            "\t\t\t\t\t\t\t\t\t\t\t}\n" +
            "\t\t\t\t\t\t\t\t\t\t]\n" +
            "\t\t\t\t\t\t}\n" +
            "\t\t\t\t\t]\n" +
            "}";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ArrayList<EventDates> eventDatesArrayList;
        EventInformation eventInformation = new EventInformation();;
        
         try {
             //pasing jason data
            JSONObject jsonObject = new JSONObject(jsonString);
            JSONArray jsonDatesArray = jsonObject.getJSONArray("Event info");
            eventDatesArrayList = new ArrayList<>();
            for (int indexDates=0;indexDates<jsonDatesArray.length();indexDates++){
                EventDates eventDates = new EventDates();
                JSONObject jsonDateobject = jsonDatesArray.getJSONObject(indexDates);
                String date = jsonDateobject.getString("Date");
                eventDates.setDate(date);
                JSONArray jsonArrayevents = jsonDateobject.getJSONArray("events");
                ArrayList<Events> eventsArrayList = new ArrayList<>();
                for (int indexEvents=0;indexEvents<jsonArrayevents.length();indexEvents++){
                    Events events = new Events();
                    JSONObject eventObj = jsonArrayevents.getJSONObject(indexEvents);
                    events.setEventId(eventObj.getString("eventId"));
                    events.setEventName(eventObj.getString("eventName"));
                    eventsArrayList.add(events);
                }
                eventDates.setEventsArrayList(eventsArrayList);
                eventDatesArrayList.add(eventDates);
            }
            eventInformation.setEventsDatesList(eventDatesArrayList);
            Log.d("message",eventInformation.toString());
        }catch (Exception e){

        }
        //parent recyclerview
        event_recycler_view_parent = (RecyclerView) findViewById(R.id.event_recycler_view_parent);
        event_list_parent_adapter = new EventListParentAdapter(eventInformation,MainActivity.this);
        event_recycler_view_parent.setHasFixedSize(true);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        event_recycler_view_parent.setLayoutManager(mLayoutManager);
        event_recycler_view_parent.setItemAnimator(new DefaultItemAnimator());
        event_recycler_view_parent.setAdapter(event_list_parent_adapter);


    }
}
/*******************************************************************************/
5.copy adapters
  EventListParentAdapter class, this used for parent data(date)
  
  public class EventListParentAdapter extends     RecyclerView.Adapter<EventListParentAdapter.MyViewHolder> {

    //private List<Movie> moviesList;

    private EventInformation eventInformation;
    private Activity activity;

    public EventListParentAdapter(EventInformation eventInformation,Activity activity) {
        this.eventInformation = eventInformation;
        this.activity = activity;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.event_list_parent_item, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        EventDates eventDates = eventInformation.getEventsDatesList().get(position);
        holder.event_list_parent_date.setText(eventDates.getDate());

        LinearLayoutManager hs_linearLayout = new LinearLayoutManager(this.activity, LinearLayoutManager.VERTICAL, false);
        holder.event_recycler_view_child.setLayoutManager(hs_linearLayout);
        holder.event_recycler_view_child.setHasFixedSize(true);
        EventListChildAdapter eventListChildAdapter = new EventListChildAdapter(this.activity,eventInformation.getEventsDatesList().get(position).getEventsArrayList());
        holder.event_recycler_view_child.setAdapter(eventListChildAdapter);

    }

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

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView event_list_parent_date;
        public RecyclerView event_recycler_view_child;

        public MyViewHolder(View view) {
            super(view);
            event_list_parent_date = (TextView) view.findViewById(R.id.event_list_parent_date);
            event_recycler_view_child = (RecyclerView)view.findViewById(R.id.event_recycler_view_child);
        }
    }
}
/******************************************************************************//
6.copy EventListChildAdapter class , it is used to child data

public class EventListChildAdapter extends RecyclerView.Adapter<EventListChildAdapter.MyViewHolder> {

    //private List<Movie> moviesList;

    private EventInformation eventInformation;
    private ArrayList<Events> eventsArrayList;
    private Activity activity;

    public EventListChildAdapter(Activity activity,ArrayList<Events> eventsArrayList) {
        this.eventsArrayList = eventsArrayList;
        this.activity = activity;
    }

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

    @Override
    public void onBindViewHolder(final MyViewHolder holder,final int position) {
        Events events = eventsArrayList.get(position);
        holder.event_list_event_name.setText(events.getEventName());
        holder.event_list_event_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("event name=",eventsArrayList.get(position).getEventName());
            }
        });



    }

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

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView event_list_event_name;


        public MyViewHolder(View view) {
            super(view);
            event_list_event_name = (TextView) view.findViewById(R.id.event_list_event_name);

        }
    }
}


/**************************************************************************************/


Keywords: inner recycler view, nested recycler view , recyclerview within recyclerview