Thursday, 30 March 2017

How to  the Data locally in Android Studio.

[
{"ID":1,"name":"A"},
{"ID":2,"name":"B"},
{"ID":3,"name":"C"},
{"ID":4,"name":"D"},
{"ID":5,"name":"E"},
{"ID":6,"name":"F"},
{"ID":7,"name":"G"}
]


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

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.


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


              TimeAdapter timeAdapter;
              final ArrayList<TimeItem> timeArrayList = new ArrayList<>();

              DataBaseHandler handler = new DataBaseHandler(this);
              NetworkUtils utils = new NetworkUtils(MainActivity.this);

                if (handler.getMenuCount() == 0 && utils.isConnectingToInternet()) {
                    //Execute the AsyncTask
                    customDialog();
              } else {
                    ListView popListView = (ListView) findViewById(R.id.popList);
                    final ArrayList<TimeItem> menuList = handler.getAllMenu();
                    timeAdapter = new TimeAdapter(MainActivity.this, menuList);
                    popListView.setAdapter(timeAdapter);
                }

            }
        });

 private void customDialog() {
        String GET_URL = "http://clientdemo.mayaitsolution.com/upload/getallmenus";
        StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray jsonArray = new JSONArray(response);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                String mID=jsonObject.getString("ID");
                                String menu_id=jsonObject.getString("ID");
                                String mDay = jsonObject.getString("name");
                                TimeItem timeItem = new TimeItem();
                                timeItem.setDay(mDay);

                                //set the data in database
                                handler.addMenu(timeItem);


                                //deleiveryEditText.setText(mDelivery);
                                timeAdapter = new TimeAdapter(MainActivity.this, timeArrayList);
                                // set the adapter object to the Recyclerview
                                timeAdapter.notifyDataSetChanged();
                                popListView.setAdapter(timeAdapter);


                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

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

    }

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


  <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ListView
                android:id="@+id/popList"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
            </ListView>
        </LinearLayout>


Create Xml file in project.     
Open => app => res => layout - time_row_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="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="start|center"
        android:orientation="horizontal"
        android:padding="12dp">

        <TextView
            android:id="@+id/txtTime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="22dp"
            android:text="Day"
            android:textColor="#000"
            android:textSize="16dp"
            android:textStyle="bold" />
    </LinearLayout>

</LinearLayout>



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


public class TimeAdapter extends BaseAdapter {
    ArrayList<TimeItem> items = new ArrayList<TimeItem>();
    Activity con;

    public TimeAdapter(Activity con, ArrayList<TimeItem> items) {
        this.con = con;
        this.items = items;
    }

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

    @Override
    public Object getItem(int pos) {
        return items.get(pos);
    }

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

    @Override
    public View getView(final int pos, View view, ViewGroup viewGroup) {
        LayoutInflater inflator = con.getLayoutInflater();
        View listItem = inflator.inflate(R.layout.time_row_item, null, true);

        //TextView
        TextView dayTextView = (TextView) listItem.findViewById(R.id.txtTime);

        //Typeface childFont = Typeface.createFromAsset(listItem.getContext().getAssets(),"fonts/Titillium-Regular.otf");
        //dayTextView.setTypeface(childFont);

        //Get and set the data here
        dayTextView.setText(items.get(pos).getDay());
        return listItem;
    }
}


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

public class TimeItem {
    String day;

    public String getDay() {
        return day;
    }

    public void setDay(String day) {
        this.day = day;
    }
}


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


public class NetworkUtils {

    private Context context;

    public NetworkUtils(Context context) {
        this.context = context;
    }

    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }

        }
        return false;
    }

}


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


interface Listener {
    //Main image
    public void addItem(TimeItem city);
    public ArrayList<TimeItem> getAllItem();
    public int getItemCount();

    //Main Menu List
    public void addMenu(TimeItem city);
    public ArrayList<TimeItem> getAllMenu();
    public int getMenuCount();




    // Category
    public void SaveJsonSubCat(String data, JSONArray jsonObject);
    public boolean isItemAvailable(String url);
    JSONArray GetSubCat(String data);


    // Gallery Image
    public void SaveImage(String data, JSONArray jsonObject);
    public boolean isItemImage(String url);
    JSONArray GetImage(String data);

}




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


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.easy.cube.customitem.TimeItem;

import org.json.JSONArray;

import java.util.ArrayList;

/**
 * Created by Shobhna on 16-Mar-16.
 */

public class DataBaseHandler  extends SQLiteOpenHelper implements Listener {
    private static final int DB_VERSION = 1;
    private static final String DB_NAME = "Database.db";
    //Main category Activity
    public static final String TABLE_NAME = "item_table";

    public static final String TABLE_MENU = "item_list";
    public static final String TABLE_ALL_IMAGE = "all_image";


    //SubCatgory Activity
    public static final String TABLE_FOOD_ForJson = "cate_menu";
    public static final String TABLE_IMAGE_ForJson = "cate_image";

    private static final String KEY_ID = "_id";
    private static final String KEY_MENU = "_name";
    private static final String KEY_MENU_ID = "_menu_id";
    private static final String KEY_ALL_IMAGE = "url_image";
    private static final String KEY_IMAGE = "_image";


    ///************************START*********************************//
    //All Catogory Table
    String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_IMAGE + " TEXT)";
    String CREATE_TABLE_MENU = "CREATE TABLE " + TABLE_MENU + " (" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_MENU + " TEXT,"+KEY_MENU_ID +" TEXT)";
    String CREATE_TABLE_ALLIMAGE = "CREATE TABLE " + TABLE_ALL_IMAGE + " (" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_ALL_IMAGE + " TEXT)";



    //SubCatogry Table
    String CREATE_FOODForJson = "CREATE TABLE " + TABLE_FOOD_ForJson + " (" + "url" + " TEXT, " + " array " + " TEXT)";

    String CREATE_IMAGEForJson = "CREATE TABLE " + TABLE_IMAGE_ForJson + " (" + "url_image" + " TEXT, " + " array_image" + " TEXT)";



    //Main Category
    String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
    String DROP_TABLE_MENU = "DROP TABLE IF EXISTS " + TABLE_MENU;
    String DROP_TABLE_ALLIMAGE = "DROP TABLE IF EXISTS " + TABLE_ALL_IMAGE;

    String DROP_TABLE_FOOD_ForJson = "DROP TABLE IF EXISTS " + TABLE_FOOD_ForJson;

    String DROP_TABLE_IMAGE_ForJson = "DROP TABLE IF EXISTS " + TABLE_IMAGE_ForJson;








    public DataBaseHandler(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //Main Catgory
        db.execSQL(CREATE_TABLE);
        db.execSQL(CREATE_TABLE_MENU);
        db.execSQL(CREATE_TABLE_ALLIMAGE);
        db.execSQL(CREATE_FOODForJson);
        db.execSQL(CREATE_IMAGEForJson);





    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //Main Catgory
        db.execSQL(DROP_TABLE);
        db.execSQL(DROP_TABLE_MENU);
        db.execSQL(DROP_TABLE_ALLIMAGE);


        //Catogry
        db.execSQL(DROP_TABLE_FOOD_ForJson);
        db.execSQL(DROP_TABLE_IMAGE_ForJson);

        onCreate(db);
    }


    //Get All Image
    @Override
    public void addItem(TimeItem item) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put(KEY_IMAGE, item.getImage_url());
            db.insert(TABLE_NAME, null, values);
            db.close();
        } catch (Exception e) {
            Log.e("problem", e + "");
        }
    }

    @Override
    public ArrayList<TimeItem> getAllItem() {
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<TimeItem> itemList = null;
        try {
            itemList = new ArrayList<TimeItem>();
            String QUERY = "SELECT * FROM " + TABLE_NAME;
            Cursor cursor = db.rawQuery(QUERY, null);
            if (cursor.moveToFirst()) {
                do {
                    TimeItem item = new TimeItem();
                    item.setId(cursor.getString(0));
                    item.setImage_url(cursor.getString(1));
                    itemList.add(item);
                } while (cursor.moveToNext());
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return itemList;
    }

    @Override
    public int getItemCount() {
        int num = 0;
        SQLiteDatabase db = this.getReadableDatabase();
        try {
            String QUERY = "SELECT * FROM " + TABLE_NAME;
            Cursor cursor = db.rawQuery(QUERY, null);
            num = cursor.getCount();
            db.close();
            return num;
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return 0;
    }

    ///////////////////////////////////
    //////////////////////////////////
    //Get All Menu
    @Override
    public void addMenu(TimeItem item) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put(KEY_MENU, item.getDay());
            values.put(KEY_MENU_ID, item.getMenu_id());
            db.insert(TABLE_MENU, null, values);
            db.close();
        } catch (Exception e) {
            Log.e("problem", e + "");
        }
    }


    @Override
    public ArrayList<TimeItem> getAllMenu() {
        SQLiteDatabase db = this.getReadableDatabase();
        ArrayList<TimeItem> itemList = null;
        try {
            itemList = new ArrayList<TimeItem>();
            String QUERY = "SELECT * FROM " + TABLE_MENU;
            Cursor cursor = db.rawQuery(QUERY, null);
            if (cursor.moveToFirst()) {
                do {
                    TimeItem item = new TimeItem();
                    item.setId(cursor.getString(0));
                    item.setDay(cursor.getString(1));
                    item.setMenu_id(cursor.getString(2));
                    itemList.add(item);
                } while (cursor.moveToNext());
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return itemList;
    }

    @Override
    public int getMenuCount() {
        int num = 0;
        SQLiteDatabase db = this.getReadableDatabase();
        try {
            String QUERY = "SELECT * FROM " + TABLE_MENU;
            Cursor cursor = db.rawQuery(QUERY, null);
            num = cursor.getCount();
            db.close();
            return num;
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return 0;
    }



    //////////////////
    //////////////
    ////////////end

    //All SubCatory Table
    //Food catogory
    ///////////////////////////////////////////////////////
    //////////////////////
    @Override
    public void SaveJsonSubCat(String data, JSONArray jsonObject) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put("url", data);
            values.put("array", jsonObject.toString());
            db.insert(TABLE_FOOD_ForJson, null, values);
            db.close();
        } catch (Exception e) {
            Log.e("problem", e + "");
        }
    }

    @Override
    public JSONArray GetSubCat(String data) {
        SQLiteDatabase db = this.getReadableDatabase();
        try {
            //  String QUERY = "SELECT * FROM " + TABLE_FOOD_ForJson;
            Cursor cursor = db.rawQuery("SELECT * FROM "+TABLE_FOOD_ForJson+" WHERE url = '"+data+"'", null);
            if (cursor.getCount()> 0){
                while (cursor.moveToNext()){
                    if (cursor.getString(cursor.getColumnIndex("url")).equals(data)){
                        JSONArray obj = new JSONArray(cursor.getString(cursor.getColumnIndex("array")));
                        db.close();
                        return obj;
                    }
                }
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return null;
    }

    @Override
    public boolean isItemAvailable(String url) {

        SQLiteDatabase db = this.getReadableDatabase();
        try {
            // String QUERY = "SELECT * FROM " + TABLE_FOOD_ForJson;
            Cursor cursor = db.rawQuery("SELECT * FROM "+TABLE_FOOD_ForJson,null);//+" WHERE url = '"+url+"'", null);
            if (cursor.getCount()> 0){
                while (cursor.moveToNext()){
                    if (cursor.getString(cursor.getColumnIndex("url")).equals(url)){
                        db.close();
                        return true;
                    }
                }
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return false;
    }

//**************************************************************************End*****************************************//
    //////Gallary Image////////////////
    /////save images///////


    @Override
    public void SaveImage(String data, JSONArray jsonObject) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put("url_image", data);
            values.put("array_image", jsonObject.toString());
            db.insert(TABLE_IMAGE_ForJson, null, values);
            db.close();
        } catch (Exception e) {
            Log.e("problem", e + "");
        }
    }

    @Override
    public JSONArray GetImage(String data) {
        SQLiteDatabase db = this.getReadableDatabase();
        try {
            //  String QUERY = "SELECT * FROM " + TABLE_FOOD_ForJson;
            Cursor cursor = db.rawQuery("SELECT * FROM "+TABLE_IMAGE_ForJson+" WHERE url_image = '"+data+"'", null);
            if (cursor.getCount()> 0){
                while (cursor.moveToNext()){
                    if (cursor.getString(cursor.getColumnIndex("url_image")).equals(data)){
                        JSONArray obj = new JSONArray(cursor.getString(cursor.getColumnIndex("array_image")));
                        db.close();
                        return obj;
                    }
                }
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return null;
    }

    @Override
    public boolean isItemImage(String url) {

        SQLiteDatabase db = this.getReadableDatabase();
        try {
            // String QUERY = "SELECT * FROM " + TABLE_FOOD_ForJson;
            Cursor cursor = db.rawQuery("SELECT * FROM "+TABLE_IMAGE_ForJson,null);//+" WHERE url = '"+url+"'", null);
            if (cursor.getCount()> 0){
                while (cursor.moveToNext()){
                    if (cursor.getString(cursor.getColumnIndex("url_image")).equals(url)){
                        db.close();
                        return true;
                    }
                }
            }
            db.close();
        } catch (Exception e) {
            Log.e("error", e + "");
        }
        return false;
    }

}




Add Internet permission in your manifest

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






How to filter the data on list in Android.

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.

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


SearchView searchView=(SearchView)view.findViewById(R.id.searchView);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                (your adapter name).getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                (your adapter name) getFilter().filter(newText);
                return true;
            }
        });


//Click on listView
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CustomItem mReference = (CustomItem) parent.getAdapter().getItem(position);
                if (String.valueOf(mReference) == null) {
                    Toast.makeText(getActivity(), "NO REFERENCE", Toast.LENGTH_SHORT).show();
                } else {
                    Intent in = new Intent(getActivity(), DetailActivity.class);
                    in.putExtra("reference", mReference.getmReference());
                    startActivity(in);
                }
            }
        });



Create the Java file in project.

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


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

public class CustomAdapter extends BaseAdapter implements Filterable {
    private static ArrayList<CustomItem> searchArrayList;

    private LayoutInflater mInflater;
    private ArrayList<CustomItem> orignalItems = new ArrayList<>();
    private ItemFilter mFilter = new ItemFilter();

    public CustomAdapter (Context context, ArrayList<CustomItem> results) {
        this.searchArrayList = results;
        this.orignalItems =results;
        mInflater = LayoutInflater.from(context);
    }

    public int getCount() {
        return searchArrayList.size();
    }

    public Object getItem(int position) {
        return searchArrayList.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.hotel_item, null);
            holder = new ViewHolder();
            holder.txtName = (TextView) convertView.findViewById(R.id.name);
           
           convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.txtName.setText(searchArrayList.get(position).getName());
        return convertView;
    }

    static class ViewHolder {
        TextView txtName;
      
    }

    /**
     * implement base BaseAdapter method here.....
     */

    @Override
    public Filter getFilter() {
        return mFilter;
    }

    private class ItemFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            String filterString = constraint.toString().toLowerCase();

            FilterResults results = new FilterResults();

            final List<CustomItem> list = orignalItems;

            int count = list.size();
            final ArrayList<CustomItem> nlist = new ArrayList<CustomItem>(count);

            String filterableString ;

            for (int i = 0; i < count; i++) {
                filterableString = list.get(i).name;
                if (filterableString.toLowerCase().contains(filterString)) {
                    CustomItem mYourCustomData = list.get(i);
                    nlist.add(mYourCustomData);
                    // nlist.add(filterableString);
                }
            }

            results.values = nlist;
            results.count = nlist.size();

            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            searchArrayList = (ArrayList<CustomItem>) results.values;
            notifyDataSetChanged();
        }

    }
}
 


How to post the data in object on server.

Example:

{
    "action": "login",   
    "email": "abc@gmail.com",
    "password": "12345"
}



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.android.support.constraint:constraint-layout:1.0.1'
compile 'com.loopj.android:android-async-http:1.4.9'



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


<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="12dp"
    tools:context=".MainActivity">

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

    <Button
        android:id="@+id/sendData"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send data" />
</LinearLayout>


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



import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.entity.StringEntity;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;


public class MainActivity extends AppCompatActivity { 
    //Button
    Button loginButton;
    //TextView
    TextView responseTextView;
    // Response
    String responseServer;

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

        //Getting the Widget Id Here
        init();
        //using the click leistner here
        listener();

    }

    private void init() {
        //TextView
        responseTextView = (TextView) findViewById(R.id.txtText);
        //Button
        loginButton = (Button) findViewById(R.id.sendData);
    }

    private void listener() {
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AsyncT asyncT = new AsyncT();
                asyncT.execute();
            }
        });
    }

    /* Inner class to get response */
    class AsyncT extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("Enter your url here");

            try {

                JSONObject jsonobj = new JSONObject();
                jsonobj.put("action", "login");// This field accouding to server requirment...
                jsonobj.put("email_mobile", "abc@gmail.com"); //put the email EditText field text here...
                jsonobj.put("password", "1234");//put the passwors EditText field text here...
                StringEntity stringEntity = new StringEntity(jsonobj.toString());

                httppost.setEntity(stringEntity);
                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);
                InputStream inputStream = response.getEntity().getContent();
                InputStreamToStringExample str = new InputStreamToStringExample();
                responseServer = str.getStringFromInputStream(inputStream);
                Log.e("response", "response:::" + responseServer);
                //Here getting the response data....

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

            //set the server response here
            responseTextView.setText(responseServer);
        }
    }

    public static class InputStreamToStringExample {

        public static void main(String[] args) throws IOException {

            // intilize an InputStream
            InputStream is = new ByteArrayInputStream("file content....".getBytes());
            String result = getStringFromInputStream(is);
        }

        // convert InputStream to String
        private static String getStringFromInputStream(InputStream is) {

            BufferedReader br = null;
            StringBuilder sb = new StringBuilder();

            String line;
            try {

                br = new BufferedReader(new InputStreamReader(is));
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return sb.toString();
        }

    }
}


Add Internet permission in your manifest.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Android cropping image from camera or gallery.

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;
    private int mAddedItems = 0;
    private ProgressDialog mProgressDialog;

    private boolean isUpdated = false;

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

}

Android Working with Marshmallow (M) Runtime Permissions.

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


import android.os.Build;

/**
 * Created by Laptop on 24-10-2016.
 */

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



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;

/**
 * Created by pc on 10/26/2016.
 */

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.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />