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