Wednesday, 15 March 2017

Android Recycler View Example

    Android RecyclerView is more advanced version of ListView with improved performance and other benefits. In this tutorial we are going to learn how to render a simple RecyclerView with a custom layout. We’ll also learn writing a adapter class and row click listener.
    Open build.gradle and add recycler view and card view dependency. Then after rebuild the project.
build.gradle

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:25.0.1'
    compile 'com.android.support:design:25.0.1'
    compile 'com.android.support:cardview-v7:25.0.1'
    compile 'com.android.support:recyclerview-v7:25.0.1'
}
    Open res->values->styles.xml and added this below card view style into your styles file.
styles.xml

<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="CardViewDefault" parent="CardView">
        <item name="cardElevation">3dp</item>
        <item name="contentPadding">5dp</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_marginTop">5dp</item>
        <item name="android:layout_marginLeft">5dp</item>
        <item name="android:layout_marginRight">5dp</item>
        <item name="android:layout_marginBottom">5dp</item>
    </style>

</resources>
    Open res->layout->activity_main.xml then after added this below line of code into your activity_main.xml file. here main componet is recycler view.
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"
    android:background="#e7e7e7"
    tools:context="com.androidsimplifycodes.example.RecyclerView.RecyclerActivity">

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

</LinearLayout>
    Create an layout xml named list_item.xml with the below line of code. This layout file renders a single row in recycler view by displaying images into card view.
list_item.xml

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

    <android.support.v7.widget.CardView
        style="@style/CardViewDefault">

        <ImageView
            android:id="@+id/ivImage"
            android:layout_width="wrap_content"
            android:layout_height="300dp"
            android:contentDescription="@null"
            android:scaleType="fitXY"
            android:src="@drawable/img2" />

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

</LinearLayout>
    RecyclerModel is class use for the data storage. For example here stored scale bitmap into this model class.
RecyclerModel.java

package com.androidsimplifycodes.example.RecyclerView;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class RecyclerModel {

    private Bitmap bitmapResource;

    public Bitmap getBitmapResource() {
        return bitmapResource;
    }

    public void setGetBitmapResource(Context context, int getBitmapResource) {
        this.bitmapResource = Bitmap.createScaledBitmap(
                BitmapFactory.decodeResource(context.getResources(), getBitmapResource),
                500,
                500,
                false);
    }
}
RecyclerAdapter.java

package com.androidsimplifycodes.example.RecyclerView;

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.ImageView;
import android.widget.Toast;

import com.androidsimplifycodes.example.R;

import java.util.ArrayList;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    private Context context;
    private ArrayList<RecyclerModel> list;

    RecyclerAdapter(Context context, ArrayList<RecyclerModel> list) {
        // give reference to the Activity context and list into the adapter
        this.context = context;
        this.list = list;
    }

    @Override
    public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.list_item, parent, false));
    }

    @Override
    public void onBindViewHolder(final RecyclerAdapter.ViewHolder holder, int position) {
        holder.ivImage.setImageBitmap(list.get(position).getBitmapResource());

        holder.ivImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // for the displaying the current item position when click.
                Toast.makeText(context, String.valueOf(holder.getAdapterPosition()), Toast.LENGTH_SHORT).show();
            }
        });
    }

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

    class ViewHolder extends RecyclerView.ViewHolder {

        ImageView ivImage;

        ViewHolder(View itemView) {
            super(itemView);
            initView(itemView);
        }

        private void initView(View rootView) {
            ivImage = (ImageView) rootView.findViewById(R.id.ivImage);
        }
    }
}
RecyclerActivity.java

package com.androidsimplifycodes.example.RecyclerView;

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

import com.androidsimplifycodes.example.R;

import java.util.ArrayList;

public class RecyclerActivity extends AppCompatActivity {

    protected RecyclerView rvSelectItem;
    protected ArrayList<RecyclerModel> list;
    protected RecyclerModel recyclerModel;

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

        // initialize array list
        list = new ArrayList<>();

        recyclerModel = new RecyclerModel();
        recyclerModel.setGetBitmapResource(this, R.drawable.img2);
        list.add(recyclerModel);

        recyclerModel = new RecyclerModel();
        recyclerModel.setGetBitmapResource(this, R.drawable.img5);
        list.add(recyclerModel);

        recyclerModel = new RecyclerModel();
        recyclerModel.setGetBitmapResource(this, R.drawable.img4);
        list.add(recyclerModel);

        recyclerModel = new RecyclerModel();
        recyclerModel.setGetBitmapResource(this, R.drawable.img5);
        list.add(recyclerModel);

        recyclerModel = new RecyclerModel();
        recyclerModel.setGetBitmapResource(this, R.drawable.img2);
        list.add(recyclerModel);

        recyclerModel = new RecyclerModel();
        recyclerModel.setGetBitmapResource(this, R.drawable.img4);
        list.add(recyclerModel);

        // LinearLayoutManager user for set Recycler View HORIZONTAL Or VERTICAL
        // for example LinearLayoutManager.VERTICAL Or LinearLayoutManager.HORIZONTAL
        LinearLayoutManager manager = new LinearLayoutManager(RecyclerActivity.this, LinearLayoutManager.HORIZONTAL, false);
        rvSelectItem.setLayoutManager(manager);
        // set Our RecyclerAdapter into setAdapter() method.
        rvSelectItem.setAdapter(new RecyclerAdapter(this, list));
    }

    private void initView() {
        rvSelectItem = (RecyclerView) findViewById(R.id.rvSelectItem);
    }
}
Output :


Tuesday, 14 March 2017

Android ListView Example

    Android listview is view we can use for to set your data into vertically fashion one by one item element with customizable xml.
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.androidsimplifycodes.example.MainActivity">

    <ListView
        android:id="@+id/lvList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>
    This xml file bind with adapter and adapter dynamically set data into this view for example in our case TextView. In sort number of copy will be generated into run time memory when you call adapter.
list_item.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">

    <TextView
        android:id="@+id/tvText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:textAppearance="?android:textAppearanceLarge" />

</LinearLayout>
    ListModel is class use for the storage it means using new operator generate new object and using this object set data into this object but question arise how can we stored this objects? For the storing this object so may technique but here i want to use array list.
ListModel.java

package com.androidsimplifycodes.example.ListView;

public class ListModel {

    private String text;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}
ListViewAdapter.java

package com.androidsimplifycodes.example.ListView;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.androidsimplifycodes.example.R;

import java.util.ArrayList;

public class ListViewAdapter extends BaseAdapter {

    private Context context;
    private ArrayList list;

    // passing the objects array list
    public ListViewAdapter(Context context, ArrayList list) {
        this.context = context;
        this.list = list;
    }

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

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

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

    @Override
    public View getView(int i, View convertView, ViewGroup viewGroup) {

        ViewHolder holder;
        // this condition only first time true because when adapter call that 
        // time your View is null so fist we bind xml file then after using ViewHolder 
        // bind views.
        if (convertView == null) {
            // bind your list_item.xml here 
            convertView = LayoutInflater.from(context).inflate(R.layout.list_item, viewGroup, false);
            holder = new ViewHolder(convertView);
            // if you not set holder into View then each and every time fist bind xml
            // then after make ViewHolder calls
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.tvText.setText(list.get(i).getText());

        return convertView;
    }

    // this class use for the memory utilization for example one time your 
    // xml view bind with java using findViewById then stored into ViewHolder
    // using setTag method. Here question arise but why required this procedure
    // because at run time each and every time not bind your xml view with adapter
    // it will be provide memory utilization and scrolling speed to the View.
    private static class ViewHolder {
        TextView tvText;

        ViewHolder(View rootView) {
            initView(rootView);
        }

        private void initView(View rootView) {
            tvText = (TextView) rootView.findViewById(R.id.tvText);
        }
    }
}
MainActivity.java

package com.androidsimplifycodes.example;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

import com.androidsimplifycodes.example.ListView.ListModel;
import com.androidsimplifycodes.example.ListView.ListViewAdapter;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    protected Context context;
    protected ListView lvList;
    protected ArrayList list;
    protected ListModel model;

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

        context = MainActivity.this;
        initView();

        list = new ArrayList<>();

        model = new ListModel();
        model.setText("ABC");
        list.add(model);

        model = new ListModel();
        model.setText("CDE");
        list.add(model);

        model = new ListModel();
        model.setText("EFG");
        list.add(model);

        model = new ListModel();
        model.setText("GHI");
        list.add(model);

        model = new ListModel();
        model.setText("IJK");
        list.add(model);

        model = new ListModel();
        model.setText("KLM");
        list.add(model);

        lvList.setAdapter(new ListViewAdapter(this, list));
    }

    private void initView() {
        lvList = (ListView) findViewById(R.id.lvList);
    }
}
Output :

Tuesday, 7 March 2017

Android ExpandableListView With Custom Layout

    This two dependency add into your build.gradle file for the CardView. colors add into color.xml file and CardView style CardViewDefault add into style file.
build.gradle (dependency)

compile 'com.android.support:design:25.0.1'
compile 'com.android.support:cardview-v7:25.0.1'
colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="color_blue">#2672FF</color>
</resources>
styles.xml

<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="CardViewDefault" parent="CardView">
        <item name="cardElevation">3dp</item>
        <item name="contentPadding">5dp</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_marginTop">5dp</item>
        <item name="android:layout_marginLeft">5dp</item>
        <item name="android:layout_marginRight">5dp</item>
        <item name="android:layout_marginBottom">5dp</item>
    </style>

</resources>
activity_main.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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context="com.androidsimplifycodes.example.MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

            <android.support.v7.widget.CardView
                style="@style/CardViewDefault"
                app:contentPadding="0dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="vertical">

                    <LinearLayout
                        android:id="@+id/llExpandableHeadingOneClick"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="@color/color_blue"
                        android:orientation="horizontal"
                        android:weightSum="1">

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_weight="0.9"
                            android:padding="10dp"
                            android:text="Expandable Heading 1"
                            android:textAppearance="?android:textAppearanceMedium"
                            android:textColor="@android:color/white" />

                        <ImageView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center"
                            android:layout_weight="0.1"
                            android:contentDescription="@null"
                            android:padding="5dp"
                            android:src="@drawable/ic_arrow_down" />

                    </LinearLayout>

                    <LinearLayout
                        android:id="@+id/llExpandableHeadingOne"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:padding="5dp">

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:text="@string/my_text"
                            android:textAppearance="?android:textAppearanceMedium"
                            android:textColor="@android:color/black" />

                    </LinearLayout>

                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:background="@android:color/white" />

                    <LinearLayout
                        android:id="@+id/llExpandableHeadingTwoClick"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="@color/color_blue"
                        android:orientation="horizontal"
                        android:weightSum="1">

                        <TextView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_weight="0.9"
                            android:padding="10dp"
                            android:text="Expandable Heading 2"
                            android:textAppearance="?android:textAppearanceMedium"
                            android:textColor="@android:color/white" />

                        <ImageView
                            android:layout_width="0dp"
                            android:layout_height="match_parent"
                            android:layout_gravity="center"
                            android:layout_weight="0.1"
                            android:contentDescription="@null"
                            android:padding="5dp"
                            android:src="@drawable/ic_arrow_down" />

                    </LinearLayout>

                    <LinearLayout
                        android:id="@+id/llExpandableHeadingTwo"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:padding="5dp">

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:text="@string/my_text"
                            android:textAppearance="?android:textAppearanceMedium"
                            android:textColor="@android:color/black" />

                    </LinearLayout>

                </LinearLayout>

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

        </LinearLayout>

    </ScrollView>

</LinearLayout>
MainActivity.java

package com.androidsimplifycodes.example;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

    protected Context context;
    protected LinearLayout llExpandableHeadingOneClick;
    protected LinearLayout llExpandableHeadingOne;
    protected LinearLayout llExpandableHeadingTwoClick;
    protected LinearLayout llExpandableHeadingTwo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        super.setContentView(R.layout.activity_main);

        context = MainActivity.this;
        initView();

        Util.collapseView(llExpandableHeadingOne);
        Util.collapseView(llExpandableHeadingTwo);

        llExpandableHeadingOneClick.setTag("Expand");
        llExpandableHeadingTwoClick.setTag("Expand");

        llExpandableHeadingOneClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag().toString().equals("Expand")) {
                    Util.expandView(llExpandableHeadingOne);
                    llExpandableHeadingOneClick.setTag("Collapse");
                } else {
                    Util.collapseView(llExpandableHeadingOne);
                    llExpandableHeadingOneClick.setTag("Expand");
                }
            }
        });

        llExpandableHeadingTwoClick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag().toString().equals("Expand")) {
                    Util.expandView(llExpandableHeadingTwo);
                    llExpandableHeadingTwoClick.setTag("Collapse");
                } else {
                    Util.collapseView(llExpandableHeadingTwo);
                    llExpandableHeadingTwoClick.setTag("Expand");
                }
            }
        });
    }

    private void initView() {
        llExpandableHeadingOneClick = (LinearLayout) findViewById(R.id.llExpandableHeadingOneClick);
        llExpandableHeadingOne = (LinearLayout) findViewById(R.id.llExpandableHeadingOne);
        llExpandableHeadingTwoClick = (LinearLayout) findViewById(R.id.llExpandableHeadingTwoClick);
        llExpandableHeadingTwo = (LinearLayout) findViewById(R.id.llExpandableHeadingTwo);
    }
}
    These two function uses for the layout expand and collapse for, expand and Collapse create animation class instance and using interpolated Time multiplied with target height getting new integer value and this value assign for the view expand and collapse.
Util.java

package com.androidsimplifycodes.example;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Transformation;

/**
 * Created by Kishan Donga on 2/22/2017.
 */

public class Util {

    public static void expandView(final View v) {
        v.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        final int targetHeight = v.getMeasuredHeight();

        v.getLayoutParams().height = 1;
        v.setVisibility(View.VISIBLE);
        Animation a = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                v.getLayoutParams().height = interpolatedTime == 1
                        ? ViewGroup.LayoutParams.WRAP_CONTENT
                        : (int) (targetHeight * interpolatedTime);
                v.requestLayout();
            }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };

        a.setDuration((int) (targetHeight / v.getContext().getResources().getDisplayMetrics().density));
        v.startAnimation(a);
    }

    public static void collapseView(final View v) {
        final int initialHeight = v.getMeasuredHeight();

        Animation a = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                if (interpolatedTime == 1) {
                    v.setVisibility(View.GONE);
                } else {
                    v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
                    v.requestLayout();
                }
            }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };

        a.setDuration((int) (initialHeight / v.getContext().getResources().getDisplayMetrics().density));
        v.startAnimation(a);
    }
}
Output :



Monday, 6 March 2017

Android SharedPreferences Example

 MODE_PRIVATE: the default mode, file accessed withing calling application.
 MODE_WORLD_READABLE: Mode name itself represent this file is not protected so it will be create security holes in applications for the sensitive data.
 MODE_WORLD_WRITEABLE: Mode name itself represent this file is not protected so it will be create security holes in applications for the sensitive data.
 MODE_MULTI_PROCESS: This method will check for modification of preferences even if the Shared Preference instance has already been loaded
 MODE_APPEND: This will append the new preferences data with the already existing preferences data.
 MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag. When it is set, it would enable write ahead logging by default

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:gravity="center"
    android:orientation="vertical"
    tools:context="com.androidsimplifycodes.example.MainActivity">

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

        <EditText
            android:id="@+id/edText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="text"/>

        <Button
            android:id="@+id/btnSave"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Save" />

    </LinearLayout>

    <TextView
        android:id="@+id/tvStoredData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:textAppearanceLarge"
        android:textColor="@color/colorAccent" />

</LinearLayout>
MainActivity.java

package com.androidsimplifycodes.example;

import android.content.Context;
import android.content.SharedPreferences;
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 {

    protected Context context;
    protected SharedPreferences sharedPreferences;
    protected SharedPreferences.Editor editor;
    protected EditText edText;
    protected TextView tvStoredData;
    protected Button btnSave;

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

        context = MainActivity.this;
        initView();

        // sharedPreferences used for the storing the data and _Preferences is file name
        // of the sharedPreferences
        sharedPreferences = getSharedPreferences("_Preferences", Context.MODE_PRIVATE);

        // get stored data from the SharedPreferences for the TAG _DATA
        tvStoredData.setText(sharedPreferences.getString("_DATA", "Default String"));

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                editor = sharedPreferences.edit();
                editor.putString("_DATA", edText.getText().toString());
                // commit the changes
                boolean result = editor.commit();
                // if data committed then return true otherwise return false
                if (result) {
                    Toast.makeText(context, "Data Stored into SharedPreferences", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Problem Arrive for the storing Data", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void initView() {
        edText = (EditText) findViewById(R.id.edText);
        tvStoredData = (TextView) findViewById(R.id.tvStoredData);
        btnSave = (Button) findViewById(R.id.btnSave);
    }
}
Output :
Output Same as Default SharedPreferences Example

Thursday, 2 March 2017

How To Draw Triangle In Android

DrawView.java

package com.androidsimplifycodes.example;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.View;

public class DrawView extends View {

    protected Paint paint;

    public DrawView(Context context) {
        super(context);
        initView();
    }

    private void initView() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.BLUE);
        paint.setStrokeWidth(6f);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawTriangle(getWidth() / 2, getHeight() / 2, 350, canvas, paint);
    }

    public void drawTriangle(int x, int y, int width, Canvas canvas, Paint paint) {
        int halfWidth = width / 2;

        Path path = new Path();
        path.moveTo(x, y - halfWidth);
        path.lineTo(x - halfWidth, y + halfWidth);
        path.lineTo(x + halfWidth, y + halfWidth);
        path.lineTo(x, y - halfWidth);
        path.close();

        canvas.drawPath(path, paint);
    }
}
MainActivity.java

package com.androidsimplifycodes.example;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(new DrawView(this));
    }
}
Output :

Android Default SharedPreferences Example

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:gravity="center"
    android:orientation="vertical"
    tools:context="com.androidsimplifycodes.example.MainActivity">

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

        <EditText
            android:id="@+id/edText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <Button
            android:id="@+id/btnSave"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Save" />

    </LinearLayout>

    <TextView
        android:id="@+id/tvStoredData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:textAppearanceLarge"
        android:textColor="@color/colorAccent" />

</LinearLayout>
MainActivity.java

package com.androidsimplifycodes.example;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
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 {

    protected Context context;
    protected SharedPreferences sharedPreferences;
    protected SharedPreferences.Editor editor;
    protected EditText edText;
    protected TextView tvStoredData;
    protected Button btnSave;

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

        context = MainActivity.this;
        initView();

        // sharedPreferences used for the storing the data
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

        // get stored data from the SharedPreferences for the TAG _DATA
        tvStoredData.setText(sharedPreferences.getString("_DATA", "Default String"));

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                editor = sharedPreferences.edit();
                editor.putString("_DATA", edText.getText().toString());
                // commit the changes
                boolean result = editor.commit();
                // if data committed then return true otherwise return false
                if (result) {
                    Toast.makeText(context, "Data Stored into SharedPreferences", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Problem Arrive for the storing Data", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void initView() {
        edText = (EditText) findViewById(R.id.edText);
        tvStoredData = (TextView) findViewById(R.id.tvStoredData);
        btnSave = (Button) findViewById(R.id.btnSave);
    }
}
Output :
Here, sharedPreferences _DATA key not have any value so default string return.


String stored into sharedPreferences if successfully then return result true else false. Note : Only commit() function return result so we can use commit() function instead of apply().


Now _DATA key have some value so data will be return by sharedPreferences.


Wednesday, 1 March 2017

Android CheckBox In Option Menu

     Here, one linear layout inside set three child linear layout whenever user make it check or uncheck check box form the option menu then accordingly child linear layout visibility will be changed.
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.androidsimplifycodes.example.MainActivity">

    <LinearLayout
        android:id="@+id/llPhone"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center"
        android:visibility="gone">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Phone"
            android:textAppearance="?android:textAppearanceLarge"
            android:textColor="@color/colorAccent" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/llMail"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center"
        android:visibility="gone">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Mail"
            android:textAppearance="?android:textAppearanceLarge"
            android:textColor="@color/colorAccent" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/llCalender"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="center">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Calender"
            android:textAppearance="?android:textAppearanceLarge"
            android:textColor="@color/colorAccent" />

    </LinearLayout>

</LinearLayout>
     In menu.xml file have one xml attribute like android:checkable="true | false" if true then check box will be display into your option menu.
menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_phone"
        android:checkable="true"
        android:title="Phone"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_mail"
        android:checkable="true"
        android:title="Mail"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_calender"
        android:checkable="true"
        android:title="Calender"
        app:showAsAction="never" />
</menu>
MainActivity.java

package com.androidsimplifycodes.example;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

    protected LinearLayout llPhone;
    protected LinearLayout llMail;
    protected LinearLayout llCalender;
    protected SharedPreferences sharedPreferences;
    protected SharedPreferences.Editor editor;

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

        // sharedPreferences used for the storing the state of the check box.
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        editor = sharedPreferences.edit();
        // by default phone item if you want to make checked then make it true
        editor.putBoolean("phone", false);
        // by default mail item if you want to make checked then make it true
        editor.putBoolean("mail", false);
        // by default calender item if you want to make checked then make it true
        editor.putBoolean("calender", true);
        // commit the changes
        editor.commit();
    }

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

        // when menu create then using stored state of the item
        // make checkable or uncheckable item.
        if (sharedPreferences.getBoolean("phone", false)) {
            // findItem id function return the id of the menu
            menu.findItem(R.id.action_phone).setChecked(true);
        } else if (sharedPreferences.getBoolean("mail", false)) {
            menu.findItem(R.id.action_mail).setChecked(true);
        } else if (sharedPreferences.getBoolean("calender", false)) {
            menu.findItem(R.id.action_calender).setChecked(true);
        }

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // previously committed editor object never use
        // so we can create new editor reference
        editor = sharedPreferences.edit();
        switch (item.getItemId()) {
            case R.id.action_phone:
                if (item.isChecked()) {
                    llPhone.setVisibility(View.GONE);
                    // make it false because user unchecked item.
                    item.setChecked(false);
                    // checked item now unchecked
                    // so make it false into sharedPreferences
                    editor.putBoolean("phone", false);
                } else {
                    item.setChecked(true);
                    llPhone.setVisibility(View.VISIBLE);
                    editor.putBoolean("phone", true);
                }
                break;
            case R.id.action_mail:
                if (item.isChecked()) {
                    item.setChecked(false);
                    llMail.setVisibility(View.GONE);
                    editor.putBoolean("mail", false);
                } else {
                    item.setChecked(true);
                    llMail.setVisibility(View.VISIBLE);
                    editor.putBoolean("mail", true);
                }
                break;
            case R.id.action_calender:
                if (item.isChecked()) {
                    item.setChecked(false);
                    editor.putBoolean("calender", false);
                    llCalender.setVisibility(View.GONE);
                } else {
                    item.setChecked(true);
                    editor.putBoolean("calender", true);
                    llCalender.setVisibility(View.VISIBLE);
                }
                break;
        }

        // required to commit the changes
        editor.commit();
        return super.onOptionsItemSelected(item);
    }

    private void initView() {
        llPhone = (LinearLayout) findViewById(R.id.llPhone);
        llMail = (LinearLayout) findViewById(R.id.llMail);
        llCalender = (LinearLayout) findViewById(R.id.llCalender);
    }
}
Output :



Android Option Menu Example

    activity_main.xml have simple one linear or relative layout by default. For the icons right click on drawable folder and select New->Vector Asset then after added required icons. android:showAsAction=["ifRoom" | "never" | "withText" | "always" | "collapseActionView"] this one is most important for the displaying your menu with icon into menu bar or action bar. For more information refer developer console.
menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_phone"
        android:icon="@drawable/ic_call"
        android:title="Phone"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/action_mail"
        android:icon="@drawable/ic_post"
        android:title="Mail"
        app:showAsAction="never" />
    <item
        android:id="@+id/action_calender"
        android:icon="@drawable/ic_calendar"
        android:title="Calender"
        app:showAsAction="never" />
</menu>
MainActivity.java

package com.androidsimplifycodes.example;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_phone:
                Toast.makeText(this, "Phone", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.action_mail:
                Toast.makeText(this, "Mail", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.action_calender:
                Toast.makeText(this, "Calender", Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}
Output :