Friday, 5 May 2017

How to Implement Google Place API  in Android Studio.

Creating New Project.
Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

First we need to add Library to our project.

compile 'com.google.android.gms:play-services:8.4.0'

Create Xml file in project.
Open => app => res => layout - activity_main.xml.

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/icons"
        android:elevation="2dp"
        android:orientation="vertical"
        android:padding="8dp">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_from"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <EditText
                android:id="@+id/edtFrom"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:editable="false"
                android:focusable="false"
                android:focusableInTouchMode="false"
                android:hint="From" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/input_layout_to"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp">

            <EditText
                android:id="@+id/edtTo"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:editable="false"
                android:focusable="false"
                android:focusableInTouchMode="false"
                android:hint="To" />
        </android.support.design.widget.TextInputLayout>
    </LinearLayout>

    <Button
        android:id="@+id/find"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Find Now"
        android:textColor="@color/icons" />
</LinearLayout>



Create the Java file in project.
Open app => main => src =
FragmentFind.java
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.conn.findroute.R;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.ui.PlaceAutocomplete;


public class FragmentFind extends Fragment {

    Button mFind;
    EditText mFrom, mTo;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bus, container, false);

        init(view);
        eventListener();

        return view;
    }

    /*
    * Initialize UI elements
    * */
    void init(View v) {


        mFind = (Button) v.findViewById(R.id.find);
        mFrom = (EditText) v.findViewById(R.id.edtFrom);
        mTo = (EditText) v.findViewById(R.id.edtTo);
    }

    /*
    * Click event handler
    * */
    private void eventListener() {


        mFind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Snackbar.make(v, "Coming Soon", Snackbar.LENGTH_LONG).show();
                Intent in = new Intent(getActivity(), RouteListActivity.class);
                startActivity(in);
            }
        });

        mFrom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent =
                            new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
                                    .build(getActivity());
                    startActivityForResult(intent, 1);
                } catch (GooglePlayServicesRepairableException e) {
                    // TODO: Handle the error.
                } catch (GooglePlayServicesNotAvailableException e) {
                    // TODO: Handle the error.
                }
            }
        });

        mTo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent =
                            new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
                                    .build(getActivity());
                    startActivityForResult(intent, 2);
                } catch (GooglePlayServicesRepairableException e) {
                    // TODO: Handle the error.
                } catch (GooglePlayServicesNotAvailableException e) {
                    // TODO: Handle the error.
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == getActivity().RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(getActivity(), data);
                Log.i("FIND", "Place: " + place.getName());
                mFrom.setText(place.getName());
            } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
                Status status = PlaceAutocomplete.getStatus(getActivity(), data);
                // TODO: Handle the error.
                Log.i("MAP", status.getStatusMessage());

            } else if (resultCode == getActivity().RESULT_CANCELED) {
                // The user canceled the operation.
            }
        }
        if (requestCode == 2) {
            if (resultCode == getActivity().RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(getActivity(), data);
                Log.i("FIND", "Place: " + place.getName());
                mTo.setText(place.getName());
            } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
                Status status = PlaceAutocomplete.getStatus(getActivity(), data);
                // TODO: Handle the error.
                Log.i("MAP", status.getStatusMessage());

            } else if (resultCode == getActivity().RESULT_CANCELED) {
                // The user canceled the operation.
            }
        }
    }
}


Add Internet permission in your manifest.

<uses-permission android:name="android.permission.INTERNET" />
 <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="key"/>

        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <uses-feature
            android:glEsVersion="0x00020000"
            android:required="true"/>

Wednesday, 3 May 2017

 JSON Parsing in array with Retrofit in Android Studio.

[
    {
        "Id":"101",
        "Name":"Arun",
        "Marks":"112"
    },
  
    {
        "Id":"102",
        "Name":"Kamal",
        "Marks":"116"
    },
   
]


Creating New Project.
Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.


First we need to add Library to our project.

compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
compile 'com.google.code.gson:gson:1.7.2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.okhttp:okhttp:2.4.0'




Create Xml file in project.
Open => app => res => layout - activity_main.xml.


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <TextView
        android:id="@+id/txtIdOne"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="150dp" />

    <TextView
        android:id="@+id/txtIdTwo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="300dp" />

    <TextView
        android:id="@+id/txtNameOne"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="120dp" />

    <TextView
        android:id="@+id/txtNameTwo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="270dp" />

    <TextView
        android:id="@+id/txtMarkOne"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="240dp" />

    <TextView
        android:id="@+id/txtMarkTwo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="90dp" />

</RelativeLayout>



Create the Java file in project.
Open app => main => src = MainActivity.java



import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import java.util.List;

import retrofit.Call;
import retrofit.Callback;
import retrofit.GsonConverterFactory;
import retrofit.Response;
import retrofit.Retrofit;

public class MainActivity extends AppCompatActivity {

    String url = "http://www.androidtutorialpoint.com/";
    TextView idOneTextView, nameOneTextView, markOneTextView;
    TextView idTwoTextView, nameTwoTextView, markTwoTextView;

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


        idOneTextView = (TextView) findViewById(R.id.txtIdOne);
        nameOneTextView = (TextView) findViewById(R.id.txtNameOne);
        markOneTextView = (TextView) findViewById(R.id.txtMarkOne);

        idTwoTextView = (TextView) findViewById(R.id.txtIdTwo);
        nameTwoTextView = (TextView) findViewById(R.id.txtNameTwo);
        markTwoTextView = (TextView) findViewById(R.id.txtMarkTwo);

        //Getting the Data here....
        getRetrofitArray();


    }

    void getRetrofitArray() {

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RetrofitArrayAPI service = retrofit.create(RetrofitArrayAPI.class);

        Call<List<Student>> call = service.getStudentDetails();

        call.enqueue(new Callback<List<Student>>() {
            @Override
            public void onResponse(Response<List<Student>> response, Retrofit retrofit) {

                try {

                    List<Student> StudentData = response.body();

                    for (int i = 0; i < StudentData.size(); i++) {

                        if (i == 0) {
                            idOneTextView.setText("Id  :  " + StudentData.get(i).getStudentId());
                            nameOneTextView.setText("Name  :  " + StudentData.get(i).getStudentName());
                            markOneTextView.setText("Marks  : " + StudentData.get(i).getStudentMarks());
                        } else if (i == 1) {
                            idTwoTextView.setText("Id  :  " + StudentData.get(i).getStudentId());
                            nameTwoTextView.setText("Name  :  " + StudentData.get(i).getStudentName());
                            markTwoTextView.setText("Marks  : " + StudentData.get(i).getStudentMarks());
                        }
                    }


                } catch (Exception e) {
                    Log.d("onResponse", "There is an error");
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Throwable t) {
                Log.d("onFailure", t.toString());
            }
        });
    }


}


Create the Java file in project.
Open app => main => src = RetrofitArrayAPI.java


import java.util.List;
import retrofit.Call;
import retrofit.http.GET;

/**
 * Created by Saify on 5/3/2017.
 **/

public interface RetrofitArrayAPI {

    /*
     * Retrofit get annotation with our URL
     * And our method that will return us details of student.
    */
    @GET("api/RetrofitAndroidArrayResponse")
    Call<List<Student>> getStudentDetails();

}


Create the Java file in project.
Open app => main => src = Student.java


/**
 * Created by Saify on 5/3/2017.
 **/

public class Student {
    //Variables that are in our json
    private int StudentId;
    private String StudentName;
    private String StudentMarks;

    //Getters and setters
    public int getStudentId() {
        return StudentId;
    }

    public void setStudentId(int bookId) {
        this.StudentId = StudentId;
    }

    public String getStudentName() {
        return StudentName;
    }

    public void setStudentName(String name) {
        this.StudentName = StudentName;
    }

    public String getStudentMarks() {
        return StudentMarks;
    }

    public void setStudentMarks(String price) {
        this.StudentMarks = StudentMarks;
    }
}


Add Internet permission in your manifest.
<uses-permission android:name="android.permission.INTERNET" />
JSON Parsing with Retrofit in Android Studio.

Json Format:- http://api.androidhive.info/contacts/
{
    "contacts": [
        {
                "id": "c200",
                "name": "Ravi Tamada",
                "email": "ravi@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        }
        ]
}


Creating New Project.
Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

First we need to add Library to our project.
  compile 'com.google.code.gson:gson:2.6.2'
  compile 'com.squareup.retrofit2:retrofit:2.1.0'
  compile 'com.squareup.retrofit2:converter-gson:2.1.0'
  compile 'com.android.support:recyclerview-v7:25.1.0'
  compile 'com.jakewharton:butterknife:8.4.0'
  compile 'com.squareup.okhttp3:logging-interceptor:3.4.2'
  compile 'com.google.dagger:dagger:2.4'
  compile 'com.squareup.okhttp3:okhttp:3.5.0'


Create Xml file in project. 
Open => app => res => layout - 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="co.apidemos.activity.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recyclerView"
        android:scrollbars="vertical"
        ></android.support.v7.widget.RecyclerView>
    <TextView
        android:id="@+id/emptyTextView"
        android:layout_width="wrap_content"
        android:text="@string/empty_string"
        android:layout_centerInParent="true"
        android:textSize="30sp"
        android:visibility="gone"
        android:layout_height="wrap_content" />
</RelativeLayout>



Create Xml file in project. 
Open => app => res => layout - list_item.xml.


package co.apidemos.adapter;

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/userLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#fff"
    android:orientation="vertical">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="12dp">

    <TextView
        android:id="@+id/txtName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/activity_vertical_margin"
        android:text="" />

    <TextView
        android:id="@+id/txtAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/activity_vertical_margin"
        android:text="" />

    <TextView
        android:id="@+id/txtEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="@dimen/activity_vertical_margin"
        android:text=" " />

    <TextView
    android:id="@+id/txtGender"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="@dimen/activity_vertical_margin"
    android:text="" />



</LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="6dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textPhone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Mobile: "
            />

        <TextView
            android:id="@+id/txtPhone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/activity_vertical_margin"
            />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="6dp">

        <TextView
            android:id="@+id/textHome"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Home: "/>

        <TextView
            android:id="@+id/txtHome"
            style="@style/textviewBadge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="6dp">

        <TextView
            android:id="@+id/textOffice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="office: "/>

        <TextView
            android:id="@+id/txtOffice"
            style="@style/textviewBadge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginTop="8dp"
        android:background="#ccc"></View>
</LinearLayout>



Create the Java file in project.
Open app => main => src = MainActivity.java



import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import co.apidemos.BaseActivity;
import co.apidemos.R;
import co.apidemos.adapter.CustomAdapter;
import co.apidemos.model.flow.ObjectData;
import co.apidemos.model.flow.UserData;
import co.apidemos.rest.APIClient;
import co.apidemos.rest.EndPoints;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Saify on 5/3/2017.
 **/

public class MainActivity extends BaseActivity {

    @BindView(R.id.emptyTextView)
    TextView emptyTextView;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    List<UserData> myDataSource = new ArrayList<>();
    RecyclerView.Adapter myAdater;

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


        setTitle(getApplicationContext().getResources().getString(R.string.stackoverflow));
        creatingLayouts();
        ButterKnife.bind(this);

        loadUsers();
    }

    private void loadUsers() {
        EndPoints apiService = APIClient.getStackOverFLowClient().create(EndPoints.class);
        Call<ObjectData> call = apiService.getUsers("");
        showProgressDialog();
        call.enqueue(new Callback<ObjectData>() {
            @Override
            public void onResponse(Call<ObjectData> call, Response<ObjectData> response) {

                List<UserData> users = response.body().getUsers();

                myDataSource.clear();
                myDataSource.addAll(response.body().getUsers());
                myAdater.notifyDataSetChanged();
                hideProgressDialog();
            }

            @Override
            public void onFailure(Call<ObjectData> call, Throwable t) {
                t.printStackTrace();
                emptyTextView.setText(t.toString());

            }
        });
    }

    private void creatingLayouts() {
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        myAdater = new CustomAdapter(getApplicationContext(), myDataSource, R.layout.list_item);
        recyclerView.setAdapter(myAdater);
    }

}



Create the Java file in project.

Open app => main => src = CustomerAdapter.java


import android.content.Context;
import android.graphics.Typeface;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import co.apidemos.R;
import co.apidemos.model.flow.UserData;

/**
 * Created by Saify on 5/3/2017.
 **/


public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.UserViewHolder> {
    private List<UserData> users;
    private Context mcontext;
    private int rowLayout;


    // constructor
    public CustomAdapter(Context mcontext, List<UserData> users, int rowLayout) {
        this.setMcontext(mcontext);
        this.setUsers(users);
        this.setRowLayout(rowLayout);
    }

    public Context getMcontext() {
        return mcontext;
    }

    public void setMcontext(Context mcontext) {
        this.mcontext = mcontext;
    }

    public List<UserData> getUsers() {
        return users;
    }

    public void setUsers(List<UserData> users) {
        this.users = users;
    }

    public int getRowLayout() {
        return rowLayout;
    }

    public void setRowLayout(int rowLayout) {
        this.rowLayout = rowLayout;
    }

    @Override
    public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(rowLayout, parent, false);
        return new UserViewHolder(view);
    }

    @Override
    public void onBindViewHolder(UserViewHolder holder, final int position) {
        holder.userName.setText("NAME: "+users.get(position).getUserName());
        holder.userName.setTypeface(Typeface.DEFAULT_BOLD);
        holder.userAddess.setText("ADDRESS: " + users.get(position).getAddress());
        holder.userEmail.setText("EMAIL:  " + users.get(position).getEmail());
        holder.userGender.setText("Gender: "+users.get(position).getGender());


        Iterator<Map.Entry<String, String>> iterator=users.get(position).getPhone().entrySet().iterator();

        Map.Entry<String, String> pair=iterator.next();
        holder.phone.setText(pair.getKey()+ " : ");
        holder.phoneTextView.setText(pair.getValue());

        pair=iterator.next();
        holder.home.setText(pair.getKey()+ " : ");
        holder.homeTextView.setText(pair.getValue());

        pair=iterator.next();
        holder.office.setText(pair.getKey()+ " : ");
        holder.officeTextView.setText(pair.getValue());



        holder.usersLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(mcontext, " " + users.get(position).getUserName(), Toast.LENGTH_SHORT).show();
            }
        });

    }

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


    public static class UserViewHolder extends RecyclerView.ViewHolder {

        LinearLayout usersLinearLayout;
        TextView userName;
        TextView userAddess;
        TextView userEmail;
        TextView userGender;
        TextView phoneTextView;
        TextView phone;
        TextView homeTextView;
        TextView home;
        TextView officeTextView;
        TextView office;


        public UserViewHolder(View itemView) {
            super(itemView);

            usersLinearLayout = (LinearLayout) itemView.findViewById(R.id.userLayout);
            userName = (TextView) itemView.findViewById(R.id.txtName);
            userAddess = (TextView) itemView.findViewById(R.id.txtAddress);
            userEmail = (TextView) itemView.findViewById(R.id.txtEmail);
            userGender = (TextView) itemView.findViewById(R.id.txtGender);
            phoneTextView = (TextView) itemView.findViewById(R.id.txtPhone);
            phone = (TextView) itemView.findViewById(R.id.textPhone);
            homeTextView = (TextView) itemView.findViewById(R.id.txtHome);
            home = (TextView) itemView.findViewById(R.id.textHome);
            officeTextView = (TextView) itemView.findViewById(R.id.txtOffice);
            office = (TextView) itemView.findViewById(R.id.textOffice);

        }
    }
}



//*****In this java file declaring the array list with array name********//


Create the Java file in project.
Open app => main => src = ObjectData.java

import com.google.gson.annotations.SerializedName;
import java.util.List;

/**
 * Created by Saify on 5/3/2017.
 **/

public class ObjectData {
    @SerializedName("contacts")
    private List<UserData> users;

    public  void setUsers(List<UserData> users){this.users=users;}
    public List<UserData> getUsers(){ return users;}
}



//*****set the parameter******//


Create the Java file in project.
Open app => main => src = UserData.java


import com.google.gson.annotations.SerializedName;

import java.util.HashMap;


/**
 * Created by Saify on 5/3/2017.
 **/

public class UserData {

    @SerializedName("address")
    private String address;
    @SerializedName("name")
    private String userName;

    @SerializedName("gender")
    private  String gender;

    @SerializedName("email")
    private String email;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }



    @SerializedName("phone")
    private HashMap<String, String> phone= new HashMap<>();

    public HashMap<String, String> getPhone() {
        return phone;
    }

    public void setPhone(HashMap<String, String> phone) {
        this.phone = phone;
    }

}


//********Set the base url and end point url*****//


Create the Java file in project.
Open app => main => src = APIClient.java


import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Saify on 5/3/2017.
 **/

public class APIClient {

    public static  final  String BASE_URL="http://api.androidhive.info";
    public static Retrofit retrofit=null;
   

    public static  Retrofit getStackOverFLowClient(){
        if(retrofit == null){
            retrofit=new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return  retrofit;
    }
}



Create the Java file in project.
Open app => main => src = EndPoint.java


import co.apidemos.model.flow.ObjectData;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

/**
 * Created by Saify on 5/3/2017.
 **/


public interface EndPoints {
    //get the user of stackoverflow
    @GET("/contacts/")
    Call<ObjectData> getUsers(@Query("") String sort);

}



//********Progres Dialog Class******//


Create the Java file in project.
Open app => main => src = BaseActivity.java


import android.app.ProgressDialog;
import android.support.annotation.VisibleForTesting;
import android.support.v7.app.AppCompatActivity;

/**
 * Created by Saify on 5/3/2017.
 **/


public class BaseActivity extends AppCompatActivity {

    @VisibleForTesting
    public ProgressDialog mProgressDialog;

    public void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage(getString(R.string.loading));
            mProgressDialog.setIndeterminate(true);
        }

        mProgressDialog.show();
    }

    public void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        hideProgressDialog();
    }

}



Add Internet permission in your manifest.
<uses-permission android:name="android.permission.INTERNET" />


Tuesday, 2 May 2017

Swipe to Refresh ListView(SwipeRefreshLayout) in Android Studio.

Creating New Project.
Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

First we need to add Library to our project.
compile 'com.mcxiaoke.volley:library-aar:1.0.0'

Create Xml file in project.  
Open => app => res => layout - 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:padding="16dp">


    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swiperefreshlayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="Swipe To Refresh"
            android:textSize="18dp" />

    </android.support.v4.widget.SwipeRefreshLayout>

</LinearLayout>




Create the Java file in project.

Open app => main => src = MainActivity.java

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

public class MainActivity extends AppCompatActivity {

    SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        refresh();
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefreshlayout);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refresh();
            }
        });

    }

    private void refresh() {
        //Getting then data through json volley...
        StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://api.androidhive.info/contacts/",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT).show();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //swipeRefreshLayout.setRefreshing(false);
                    }
                });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);

    }
}


Add Internet permission in your manifest.
<uses-permission android:name="android.permission.INTERNET" />


May this code help you. Thanks!!!!!!

Tuesday, 25 April 2017

How to upload the Multipart Request data on server Using Android Volley.

Creating New Project.
Open android studio and create a new project.

File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.
First we need to add Library to our project. 
compile 'dev.dworks.libs:volleyplus:+'


Create Xml file in project.   
Open => app => res => layout - 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:padding="16dp"
    tools:context="org.snowcorp.imageupload.MainActivity"
    android:orientation="vertical">


    <Button
        android:id="@+id/button_choose"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SelectImage"
        android:textColor="#000"
        android:layout_gravity="center_horizontal"
        android:layout_margin="20dp"
        android:padding="10dp"/>

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="@drawable/border"
        android:layout_gravity="center_horizontal"
        android:padding="5dp"
        android:layout_margin="20dp"/>

    <Button
        android:id="@+id/button_upload"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Post"
        android:textColor="#000"
        android:layout_gravity="center_horizontal"
        android:layout_margin="20dp"/>

</LinearLayout>




Create the Java file in project.
Open app => main => src = MainActivity.java

import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.android.volley.request.SimpleMultiPartRequest;

public class MainActivity extends AppCompatActivity {
    private ImageView imageView;
    private Button choseButton, uploadButton;
    private ProgressBar progressBar;
    public static String BASE_URL = "your url here";
    static final int PICK_IMAGE_REQUEST = 1;
    String filePath;


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

        imageView = (ImageView) findViewById(R.id.imageView);
        choseButton = (Button) findViewById(R.id.button_choose);
        uploadButton = (Button) findViewById(R.id.button_upload);

        choseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageBrowse();
            }
        });

        uploadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (filePath != null) {
                    imageUpload(filePath);
                } else {
                    Toast.makeText(getApplicationContext(), "Image not selected!", Toast.LENGTH_LONG).show();
                }

            }
        });
    }

    private void imageBrowse() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {

            if(requestCode == PICK_IMAGE_REQUEST){
                Uri picUri = data.getData();
                filePath = getPath(picUri);
                Log.d("filePath", filePath);
                imageView.setImageURI(picUri);

            }
        }
    }

    private void imageUpload(final String imagePath) {

        SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

        smr.addFile("image", imagePath);
        MyApplication.getInstance().addToRequestQueue(smr);

    }

    private String getPath(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String result = cursor.getString(column_index);
        cursor.close();
        return result;
    }

}



Create the Java file in project
.

Open app => main => src = MyApplication.java

import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class MyApplication extends Application {
    public static final String TAG = MyApplication.class.getSimpleName();
    private RequestQueue mRequestQueue;

    private static MyApplication mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}


Add Internet permission in your manifest.

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


 

How to use croper  in andorid.

Creating New Project.

Open android studio and create a new project.


File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish
.

First we need to add Library to our project. 
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.soundcloud.android:android-crop:1.0.1@aar'
compile 'com.jakewharton:butterknife:8.4.0
'


Create Xml file in project.   
Open => app => res => layout - activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/preImage"
        android:layout_width="144dp"
        android:layout_height="144dp"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:src="@mipmap/ic_launcher"
        app:civ_border_color="#ffffff"
        app:civ_border_width="2dp"></de.hdodenhof.circleimageview.CircleImageView>

</RelativeLayout>




Create the Java file in project.

Open app => main => src = MainActivity.java

import android.app.ProgressDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.soundcloud.android.crop.Crop;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import de.hdodenhof.circleimageview.CircleImageView;

import static journal.shibboleth.com.croperactivity.MarshMallowPermission.CAMERA_PERMISSION_REQUEST_CODE;
import static journal.shibboleth.com.croperactivity.MarshMallowPermission.EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE;

public class MainActivity extends AppCompatActivity {

    private static final int CAMERA_REQUEST = 108;
    private String mCurrentPhotoPath = "";
    private MarshMallowPermission marshMallowPermission;
    CircleImageView mPreImageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPreImageView = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.preImage);

        mPreImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (CheckVersions.isMarshmallow()) {
                    marshMallowPermission =
                            new MarshMallowPermission(MainActivity.this);
                    if (!marshMallowPermission.checkPermissionForCamera()) {
                        marshMallowPermission.requestPermissionForCamera();
                    } else {
                        if (!marshMallowPermission.checkPermissionForExternalStorage()) {
                            marshMallowPermission.requestPermissionForExternalStorage();
                        } else {
                            clickImage();
                        }
                    }
                } else {
                    clickImage();
                }
            }
        });



    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == android.R.id.home) {
            Intent returnIntent = new Intent();
            setResult(RESULT_CANCELED, returnIntent);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        switch (requestCode) {
            case CAMERA_PERMISSION_REQUEST_CODE:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (!marshMallowPermission.checkPermissionForExternalStorage()) {
                        marshMallowPermission.requestPermissionForExternalStorage();
                    } else {
                        clickImage();
                    }
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {
                    Toast.makeText(this, "Camera permission needed." +
                            " Please allow in App Settings for additional " +
                            "functionality.", Toast.LENGTH_LONG).show();
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
            case EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    clickImage();
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.

                } else {
                    Toast.makeText(this, "External Storage permission needed. " +
                            "Please allow in App Settings for additional" +
                            " functionality.", Toast.LENGTH_LONG).show();
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }

            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    private void clickImage() {
        final CharSequence[] items = {"Take Photo Camera", "Take Photo Gallery"};
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo Camera")) {
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (cameraIntent.resolveActivity(getPackageManager()) != null) {
                        // Create the File where the photo should go
                        File photoFile;
                        photoFile = createImageFile();
                        // Continue only if the File was successfully created
                        if (photoFile != null) {
                            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                            startActivityForResult(cameraIntent, CAMERA_REQUEST);
                        } else {
                            mCurrentPhotoPath = "";
                            startActivityForResult(cameraIntent, CAMERA_REQUEST);
                        }
                    }
                } else if (items[item].equals("Take Photo Gallery")) {
                    Crop.pickImage(MainActivity.this);
                }
            }
        });
        builder.show();
    }
    private File createImageFile() {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File image = null;
        try {
            image = File.createTempFile(
                    imageFileName,  // prefix
                    ".jpg",         // suffix
                    storageDir      // directory

            );
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Save a file: path for use with ACTION_VIEW intents
        if (image != null) {
            mCurrentPhotoPath = "file:" + image.getAbsolutePath();
            Log.i("Ihdh", "Image" + mCurrentPhotoPath);
        }
        return image;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent result) {
        if (resultCode != RESULT_CANCELED) {
            if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) {
                beginCrop(result.getData());
            } else if (requestCode == Crop.REQUEST_CROP) {
                handleCrop(resultCode, result);
            } else if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
                if (mCurrentPhotoPath == null || mCurrentPhotoPath.isEmpty()) {
                    beginCrop(result.getData());
                } else {
                    beginCrop(Uri.parse(mCurrentPhotoPath));
                }
            }
        }
    }

    private void beginCrop(Uri source) {
        try {
            File file = MainActivity.this.getCacheDir();
            deleteDir(file);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
        Crop.of(source, destination).asSquare().start(this, Crop.REQUEST_CROP);
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (String aChildren : children) {
                boolean success = deleteDir(new File(dir, aChildren));
                if (!success) {
                    return false;
                }
            }
        }

        // The directory is now empty so delete it
        return dir != null && dir.delete();
    }

    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == RESULT_OK) {
            try {
                mPreImageView.setImageDrawable(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                Log.i("CROP", "handleCrop: " + Crop.getOutput(result));
                mPreImageView.setImageURI(Crop.getOutput(result));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (resultCode == Crop.RESULT_ERROR) {
            try {
                Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private String saveToInternalStorage(Bitmap bitmapImage) {
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
        // path to /data/data/yourapp/app_data/imageDir
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        // Create imageDir
        String name = System.currentTimeMillis() + "_image.jpg";
        File mypath = new File(directory, name);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(mypath);
            // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.JPEG, 50, fos);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return directory.getAbsolutePath() + "/" + name;
    }

}

//Check the version in this class.
Create the Java file in project.

Open app => main => src = CheckVersions.java

import android.os.Build;

public class CheckVersions {
    public static boolean isMarshmallow() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }
}

//Permission....
Create the Java file in project.

Open app => main => src = MarshMallowPermission.java

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

public class MarshMallowPermission {
    public static final int EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;
    public static final int CAMERA_PERMISSION_REQUEST_CODE = 3;
    Activity activity;

    public MarshMallowPermission(Activity activity) {
        this.activity = activity;
    }


    public boolean checkPermissionForExternalStorage() {
        int result = ContextCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        return result == PackageManager.PERMISSION_GRANTED;
    }

    public boolean checkPermissionForCamera() {
        int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA);
        return result == PackageManager.PERMISSION_GRANTED;
    }


    public void requestPermissionForExternalStorage() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Toast.makeText(activity, "External Storage permission needed. " +
                    "Please allow in App Settings for additional" +
                    " functionality.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(activity, new String[]{
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
        }
    }

    public void requestPermissionForCamera() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(activity,
                Manifest.permission.CAMERA)) {
            Toast.makeText(activity, "Camera permission needed." +
                    " Please allow in App Settings for additional " +
                    "functionality.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(activity, new String[]{
                            Manifest.permission.CAMERA},
                    CAMERA_PERMISSION_REQUEST_CODE);
        }
    }

}


Add Internet permission in your manifest.


<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.CAMERA" />

<activity android:name="com.soundcloud.android.crop.CropImageActivity"/>






May this code help you. Thanks!!!!!!