Thursday 9 November 2017

RecyclerView

RecyclerView

The RecyclerView widget is a more advanced and flexible version of ListView . This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views.

Will see simple example how to display country name and population using RecyclerView.

1. For recyclerview we need to add support library inside the
build.gradla(module:app),and then Syc project. 
 
compile 'com.android.support:recyclerview-v7:24.1.1'
 
2.Add RecyclerView in the activity_main.xml 
 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context="com.falgee.recycler.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"/>
</RelativeLayout>

 
3.Create java class with 2 variables country and population.
 
public class Country {
    protected String name;
    protected double population;

    public Country(String name, double population) {
        this.name = name;
        this.population = population;
    }
} 

4.Create Adapter class for set the value to each item.

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

    private ArrayList<Country> countryList;

    /**     * View holder class     * */    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView countryText;
        public TextView popText;

        public MyViewHolder(View view) {
            super(view);
            countryText = (TextView) view.findViewById(R.id.countryName);
            popText = (TextView) view.findViewById(R.id.pop);
        }
    }

    public CountryAdapter(ArrayList<Country> countryList) {
        this.countryList = countryList;
    }

    @Override    public void onBindViewHolder(MyViewHolder holder, int position) {
        Country c = countryList.get(position);
        holder.countryText.setText(c.name);
        holder.popText.setText(String.valueOf(c.population));
    }

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

    @Override    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.row,parent, false);
        return new MyViewHolder(v);
    }
}
 
5.We need to create item layout with 2 TextView for Display name and population.
 
row.xml 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/countryName"
        android:textStyle="bold"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/pop"/>
</LinearLayout> 

6.Go to MainActivity and we have to initialize RecyclerView.
And set the value for country and population. And set value to recycleview.

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

import java.util.ArrayList;

public class MainActivity extends Activity {
    ArrayList<Country> countryList;


    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView rv = (RecyclerView) findViewById(R.id.recycler_view);
        Country c=new Country("India","1,210,193,422");
        Country c1=new Country("China","1,354,040,000");
        Country c2=new Country("United States","315,761,000");
        Country c3=new Country("Indonesia","237,641,326");
        countryList=new ArrayList<Country>();
        countryList.add(c);
        countryList.add(c1);
        countryList.add(c2);
        countryList.add(c3);
        CountryAdapter ca = new CountryAdapter(countryList);
        rv.setAdapter(ca);
        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        rv.setLayoutManager(llm);
    }
}
7.Run and see the result in your Screen.
 
 
  



 

Wednesday 8 November 2017

Content Provider

                           Content Provider

 

Content provider is used to manage and Access to a archive of data.content provider is part of an android application.mostly it's used by  other applications.
which access the provider using a provider client object.providers and provider clients offer a consistency ,common interface to data and also it will handle inter process communication and secure the data.

The following topic will describes the basics :

1.How content provider will work

2. How to retrieve data from a content provider.

3.how to insert,update,delete in a content provider. 

 Accessing a provider:

An application accesses the data from content provider with using content resolver client object. The content resolver methods will provide the basic functions like insert.

The content resolver object in the client applications process,and content provider object in the application that owns the provider automatically it will handle inter communication process.content provider also act as an abstraction layer between its repository of data and the external appearance of data as tables.

To access the content provider to your application you want to  request permissions in the manifest file.

 <uses-permission android:name="android.permission.READ_USER_DICTIONARY"> 

 To Access contact using content provider to your application you want to request permission in the Manifest file.

<uses-permission android:name="android.permission.READ_CONTACTS">
 
Example code:
 
Are you using Marshmallow you should write the code for RuntimePremission
 
MainActivity:
 


import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private ContentResolver cv;

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

    }

    public void readContact(View view) {
        if(ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.READ_CONTACTS},
                    88);
        }else{//already have access
            contactRead();
        }

    }
    public void contactRead(){
        cv=getContentResolver();

        Uri uri= ContactsContract.Contacts.CONTENT_URI;
        Cursor c=cv.query(uri,null,null,null,
                ContactsContract.Contacts.DISPLAY_NAME);

        c.moveToFirst();
        do{
            Toast.makeText(MainActivity.this,c.getString(c.
                            getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)),
                    Toast.LENGTH_LONG).show();
        }while (c.moveToNext());

    }
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode,
                permissions, grantResults);
        if(requestCode == 88){
            if(grantResults.length > 0 &&
                    grantResults[0] == PackageManager.PERMISSION_GRANTED){
                contactRead();
            }else{//permission denied
                Toast.makeText(MainActivity.this, "sorry Permission denied",
                        Toast.LENGTH_LONG).show();
            }
        }
    }

}
 
 
activity_main:
 
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.falgee.contactprovidernewversion.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:onClick="readContact"
        tools:layout_editor_absoluteX="137dp"
        tools:layout_editor_absoluteY="205dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginTop="205dp"
        android:layout_marginStart="137dp" />
</android.support.constraint.ConstraintLayout>
 
ManiFest:
 
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.falgee.contactprovidernewversion">
    <uses-permission android:name="android.permission.READ_CONTACTS">

    </uses-permission>

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

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

</manifest>
 
 
 
 
  

 

 

 

 



Sunday 5 November 2017

Easy steps to make Animation in Android using Android Studio

Animations In Android

 There are four types of animations in android:
1. Translate Animation - to move the object from one place to another place.
2. Scale Animation - to resize the object or zoom the object.
3. Rotate Animation- to rotate the object clockwise or anti-clockwise.
4. Fade Animation - to make visible and invisible the object.

And for each animation we can add the effects, in android framework we call it as Interpolators, those are:
An interpolator whose rate
of change starts andends slowly 
but accelerates through the middle.
An interpolator whose rate
of change starts out slowly 
and then accelerates.
An interpolator whose change
 starts backward then flings forward.
An interpolator whose change
starts backward, flings forward and 
overshoots the target value, then finally
 goes back to the final value.
An interpolator whose change bounces
at the end.
An interpolator whose animation repeats
 for a specified number of cycles.
An interpolator whose rate of change
starts out quickly and and then 
decelerates.
An interpolator whose rate of change
 is constant.
An interpolator whose change flings
forward and overshoots the last value 
then comes back.
An interface that allows you to
implement your own interpolator.
Here we are going to see simple experiment  with all four animations and few interpolators. Follow the below steps:

 1. Create a new android studio project. And go to web browser download a ball image.
 2. Copy that ball image and paste it inside the drawable folder in the project.

 3. Go to activity_main.xml and add an ImageView and set this ball image to the ImageView.
4. Also add seven buttons in the layout.
5. first four buttons are to make animation and last three buttons are to add effects.
6. Add onClick for each and every button and create the equivalent method in MainActivity.

activity_main.xml:


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
 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"   
 tools:context="com.example.animation.MainActivity">

    <ImageView       
     android:id="@+id/ball_img"       
     android:layout_width="68dp"       
     android:layout_height="69dp"        
     android:layout_marginStart="16dp"       
     android:layout_marginTop="16dp"       
     android:src="@drawable/ball"       
     app:layout_constraintStart_toStartOf="parent"       
     app:layout_constraintTop_toTopOf="parent" />

    <Button       
     android:id="@+id/button"       
     android:layout_width="wrap_content"       
     android:layout_height="wrap_content"       
     android:layout_marginEnd="7dp"       
     android:layout_marginStart="16dp"       
     android:text="Translate"       
     android:onClick="translate"       
     app:layout_constraintBaseline_toBaselineOf="@+id/button2"       
     app:layout_constraintEnd_toStartOf="@+id/button2"       
     app:layout_constraintHorizontal_chainStyle="spread_inside"       
     app:layout_constraintStart_toStartOf="parent" />

    <Button       
     android:id="@+id/button2"       
     android:layout_width="wrap_content"       
     android:layout_height="wrap_content"       
     android:text="Scale"       
     android:onClick="scale"       
     app:layout_constraintBaseline_toBaselineOf="@+id/button3"       
     app:layout_constraintEnd_toStartOf="@+id/button3"       
     app:layout_constraintStart_toEndOf="@+id/button" />
    <Button       
     android:id="@+id/button3"       
     android:layout_width="wrap_content"       
     android:layout_height="wrap_content"       
     android:layout_marginBottom="25dp"       
     android:layout_marginEnd="1dp"       
     android:text="Rotate"       
     android:onClick="rotate"       
     app:layout_constraintBottom_toTopOf="@+id/button7"       
     app:layout_constraintEnd_toStartOf="@+id/button4"       
     app:layout_constraintStart_toEndOf="@+id/button2" />

    <Button       
     android:id="@+id/button4"       
     android:layout_width="wrap_content"       
     android:layout_height="wrap_content"       
     android:layout_marginEnd="1dp"       
     android:text="Fade"       
     android:onClick="fade"       
     app:layout_constraintBaseline_toBaselineOf="@+id/button3"       
     app:layout_constraintEnd_toEndOf="parent"       
     app:layout_constraintStart_toEndOf="@+id/button3" />

    <Button       
     android:id="@+id/button5"       
     android:layout_width="wrap_content"       
     android:layout_height="wrap_content"       
     android:layout_marginBottom="16dp"       
     android:layout_marginStart="32dp"       
     android:text="Bounce"       
     android:onClick="bounce"       
     app:layout_constraintBottom_toBottomOf="parent"       
     app:layout_constraintStart_toStartOf="parent" />

    <Button       
     android:id="@+id/button6"       
     android:layout_width="wrap_content"       
     android:layout_height="wrap_content"       
     android:layout_marginBottom="16dp"       
     android:layout_marginStart="21dp"       
     android:text="OverShoot"       
     android:onClick="overShoot"       
     app:layout_constraintBottom_toBottomOf="parent"       
     app:layout_constraintStart_toEndOf="@+id/button5" />

    <Button       
     android:id="@+id/button7"       
     android:layout_width="wrap_content"       
     android:layout_height="wrap_content"       
     android:layout_marginStart="12dp"       
     android:text="Accelarate"       
     android:onClick="accelarate"       
     app:layout_constraintBaseline_toBaselineOf="@+id/button6"       
     app:layout_constraintStart_toEndOf="@+id/button6" />
</android.support.constraint.ConstraintLayout>



7. Create new folder for animation. Right click on res folder -> go to New -> Android resource directory.

8. A new window will be open in that choose Resource type as anim and Directory name as anim.




9. A new anim folder will be created under res folder.


 

10. And right click on anim folder and create 4 Animation resource file.




11. Give the name as translate and click OK.



12. Same way create other 3 files, and name those as scale, rotate and fade.


13. Copy the below text paste inside each and every xml file.

   translate.xml

  <?xml version="1.0" encoding="utf-8"?>
 <set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate      
     android:fromXDelta="0%p"      
     android:toXDelta="75%p"      
     android:duration="1000" />
    <translate      
     android:startOffset="1000"      
     android:fromXDelta="0%p"      
     android:toXDelta="-75%p"      
     android:duration="1000"/>
 </set>






   scale.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">    
<scale            
android:fromXScale="0.5"           
 android:toXScale="3.0"            
android:pivotX="0%"           
 android:pivotY="0%"           
 android:fromYScale="0.5"            
android:toYScale="3.0"            
android:duration="1000" />    
<scale            
android:startOffset="1000"            
android:fromXScale="3.0"            
android:toXScale="0.5"            
android:pivotX="0%"           
 android:pivotY="0%"            
android:fromYScale="3.0"           
 android:toYScale="0.5"            
android:duration="1000"/> </set>
   rotate.xml
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <rotate android:fromDegrees="0" android:toDegrees="360" android:pivotX="50%" android:pivotY="50%" android:duration="1000"/> <rotate android:fromDegrees="360" android:toDegrees="0" android:pivotX="50%" android:pivotY="50%" android:duration="1000" android:startOffset="1000"/> </set>
   fade.xml
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="1000" /> <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:startOffset="1000" android:duration="1000" /> </set>
14. Go to MainActivity.java and load the animation for the image.
MainActivity.java

package com.example.animation;

import android.app.Activity;
import android.media.Image;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;

public class MainActivity extends Activity {

    private Animation anim;
    private ImageView mBallImage;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        anim = AnimationUtils.loadAnimation(MainActivity.this, R.anim.translate);
        mBallImage = (ImageView) findViewById(R.id.ball_img);
    }

    public void translate(View view) {
        anim = AnimationUtils.loadAnimation(MainActivity.this, R.anim.translate);
        mBallImage.startAnimation(anim);
    }

    public void scale(View view) {
        anim = AnimationUtils.loadAnimation(MainActivity.this, R.anim.scale);
        mBallImage.startAnimation(anim);
    }

    public void rotate(View view) {
        anim = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate);
        mBallImage.startAnimation(anim);
    }

    public void fade(View view) {
        anim = AnimationUtils.loadAnimation(MainActivity.this, R.anim.fade);
        mBallImage.startAnimation(anim);
    }

    public void bounce(View view) {
       anim.setInterpolator(new BounceInterpolator());
       mBallImage.startAnimation(anim);
    }

    public void overShoot(View view) {
        anim.setInterpolator(new OvershootInterpolator());
        mBallImage.startAnimation(anim);
    }

    public void accelarate(View view) {
        anim.setInterpolator(new AccelerateInterpolator());
        mBallImage.startAnimation(anim);
    }
}
15. Done. Run the code and check all these animations.