Tuesday 16 May 2017

Android Google Maps Nearby Example

Sample Code

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        com.google.android.gms.location.LocationListener {

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    double latitude;
    double longitude;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    LocationRequest mLocationRequest;
    Spinner mSprPlaceType;
    String[] mPlaceType = null;
    String[] mPlaceTypeName = null;
    Button btnGetNearBy;
    private GoogleMap mMap;
    private int PROXIMITY_RADIUS = 10000;

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

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            checkLocationPermission();
        }

        btnGetNearBy = (Button) findViewById(R.id.btnGet);

        // Array of place types
        mPlaceType = getResources().getStringArray(R.array.place_type);

        // Array of place type names
        mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);

        // Creating an array adapter with an array of Place types
        // to populate the spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);

        // Getting reference to the Spinner
        mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);

        // Setting adapter on Spinner to set place types
        mSprPlaceType.setAdapter(adapter);

        //Check if Google Play Services Available or not
        if (!CheckGooglePlayServices()) {
            Log.d("onCreate", "Google Play Services not available.");
            finish();
        } else {
            Log.d("onCreate", "Google Play Services available.");
        }
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    private boolean CheckGooglePlayServices() {
        GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();
        int result = googleAPI.isGooglePlayServicesAvailable(this);
        if (result != ConnectionResult.SUCCESS) {
            if (googleAPI.isUserResolvableError(result)) {
                googleAPI.getErrorDialog(this, result,
                        0).show();
            }
            return false;
        }
        return true;
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            }
        } else {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }

        btnGetNearBy.setOnClickListener(new View.OnClickListener() {
            // String Restaurant = "restaurant";
            @Override
            public void onClick(View v) {

                int selectedPosition = mSprPlaceType.getSelectedItemPosition();
                String type = mPlaceType[selectedPosition];
                // String type = "atm|bank|bus_station|church|doctor|hospital|mosque|movie_theater|hindu_temple|restaurant";
                mMap.clear();
                String url = getUrl(latitude, longitude, type);
                Object[] DataTransfer = new Object[2];
                DataTransfer[0] = mMap;
                DataTransfer[1] = url;
                Log.d("onClick", url);
                GetNearbyPlacesData getNearbyPlacesData = new GetNearbyPlacesData();
                getNearbyPlacesData.execute(DataTransfer);
                Toast.makeText(MapsActivity.this, "Nearby " + type, Toast.LENGTH_LONG).show();
            }
        });
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    private String getUrl(double latitude, double longitude, String nearbyPlace) {

        //latitude=21.228125
        //longitude=72.833771
        StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
        googlePlacesUrl.append("location=" + latitude + "," + longitude);
        googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS);
        googlePlacesUrl.append("&type=" + nearbyPlace);
        googlePlacesUrl.append("&sensor=true");
        googlePlacesUrl.append("&page_token=60");
        googlePlacesUrl.append("&key=" + "Xxxxxxxxxxxxxxxxxxxxxxxxxxx-xXXxX");
        Log.d("getUrl", googlePlacesUrl.toString());
        return (googlePlacesUrl.toString());
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d("onLocationChanged", "entered");

        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //current location marker
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mMap.addMarker(markerOptions);

        //move map camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
        Toast.makeText(MapsActivity.this, "Your Current Location", Toast.LENGTH_LONG).show();

        Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f", latitude, longitude));
    
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            Log.d("onLocationChanged", "Removing Location Updates");
        }
        Log.d("onLocationChanged", "Exit");

    }


    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    public boolean checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
               if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {
                 ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);
            }
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mMap.setMyLocationEnabled(true);
                    }

                } else {

                    // Permission denied, Disable the functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

        }
    }

}


Data Parser
 
public class DataParser {
    public List<HashMap<String, String>> parse(String jsonData) {
        JSONArray jsonArray = null;
        JSONObject jsonObject;

        try {
            Log.d("Places", "parse");
            jsonObject = new JSONObject((String) jsonData);
            jsonArray = jsonObject.getJSONArray("results");
        } catch (JSONException e) {
            Log.d("Places", "parse error");
            e.printStackTrace();
        }
        return getPlaces(jsonArray);
    }

    private List<HashMap<String, String>> getPlaces(JSONArray jsonArray) {
        int placesCount = jsonArray.length();
        List<HashMap<String, String>> placesList = new ArrayList<>();
        HashMap<String, String> placeMap = null;
        Log.d("Places", "getPlaces");

        for (int i = 0; i < placesCount; i++) {
            try {
                placeMap = getPlace((JSONObject) jsonArray.get(i));
                placesList.add(placeMap);
                Log.d("Places", "Adding places");

            } catch (JSONException e) {
                Log.d("Places", "Error in Adding places");
                e.printStackTrace();
            }
        }
        return placesList;
    }

    private HashMap<String, String> getPlace(JSONObject googlePlaceJson) {
        HashMap<String, String> googlePlaceMap = new HashMap<String, String>();
        String placeName = "-NA-";
        String vicinity = "-NA-";
        String latitude = "";
        String longitude = "";
        String reference = "";

        Log.d("getPlace", "Entered");

        try {
            if (!googlePlaceJson.isNull("name")) {
                placeName = googlePlaceJson.getString("name");
            }
            if (!googlePlaceJson.isNull("vicinity")) {
                vicinity = googlePlaceJson.getString("vicinity");
            }
            latitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lat");
            longitude = googlePlaceJson.getJSONObject("geometry").getJSONObject("location").getString("lng");
            reference = googlePlaceJson.getString("reference");
            googlePlaceMap.put("place_name", placeName);
            googlePlaceMap.put("vicinity", vicinity);
            googlePlaceMap.put("lat", latitude);
            googlePlaceMap.put("lng", longitude);
            googlePlaceMap.put("reference", reference);
            Log.d("getPlace", "Putting Places");
        } catch (JSONException e) {
            Log.d("getPlace", "Error");
            e.printStackTrace();
        }
        return googlePlaceMap;
    }
}

Download URI

public class DownloadUrl {

    public String readUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            data = sb.toString();
            Log.d("downloadUrl", data.toString());
            br.close();

        } catch (Exception e) {
            Log.d("Exception", e.toString());
        } finally {
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }
}

GetNearbyPlacesData

public class GetNearbyPlacesData extends AsyncTask<Object, String, String> {

    String googlePlacesData;
    GoogleMap mMap;
    String url;

    @Override
    protected String doInBackground(Object... params) {
        try {
            Log.d("GetNearbyPlacesData", "doInBackground entered");
            mMap = (GoogleMap) params[0];
            url = (String) params[1];
            DownloadUrl downloadUrl = new DownloadUrl();
            googlePlacesData = downloadUrl.readUrl(url);
            Log.d("GooglePlacesReadTask", "doInBackground Exit");
        } catch (Exception e) {
            Log.d("GooglePlacesReadTask", e.toString());
        }
        return googlePlacesData;
    }

    @Override
    protected void onPostExecute(String result) {
        Log.d("GooglePlacesReadTask", "onPostExecute Entered");
        List<HashMap<String, String>> nearbyPlacesList = null;
        DataParser dataParser = new DataParser();
        nearbyPlacesList =  dataParser.parse(result);
        ShowNearbyPlaces(nearbyPlacesList);
        Log.d("GooglePlacesReadTask", "onPostExecute Exit");
    }

    private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {
        for (int i = 0; i < nearbyPlacesList.size(); i++) {
            Log.d("onPostExecute","Entered into showing locations");
            MarkerOptions markerOptions = new MarkerOptions();
            HashMap<String, String> googlePlace = nearbyPlacesList.get(i);
            double lat = Double.parseDouble(googlePlace.get("lat"));
            double lng = Double.parseDouble(googlePlace.get("lng"));
            String placeName = googlePlace.get("place_name");
            String vicinity = googlePlace.get("vicinity");
            LatLng latLng = new LatLng(lat, lng);
            markerOptions.position(latLng);
            markerOptions.title(placeName + " : " + vicinity);
            mMap.addMarker(markerOptions);
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
            //move map camera
            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
        }
    }
}

Monday 15 May 2017

Image Cropping in L+M+N Example

Cropping_SampleCode

public class MainActivity extends AppCompatActivity {
    @Bind(R.id.imgSelCrop)
    ImageView ivSelectImage;
    @Bind(R.id.btnSelectimg)
    Button btnSelectImage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        btnSelectImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CropImage.activity(null)
                        .setGuidelines(CropImageView.Guidelines.ON)
                        .start(MainActivity.this);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        // handle result of CropImageActivity         
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                ivSelectImage.setImageURI(result.getUri());
                Log.e("uri-", "-" + result.getUri());
                Toast.makeText(this, "Cropping done, Thumbnail: " + result.getSampleSize(), Toast.LENGTH_LONG).show();
            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
            }
        }
    }
}
 
compile 'com.theartofdev.edmodo:android-image-cropper:2.4.+' 

Cropping in Marshmellow Example

MarshmallowCrop Sample

public class Imgmarsh extends Activity {

    public static final int RequestPermissionCode = 1;
    @Bind(R.id.imgSelImage)
    ImageView ivSelectImage;
    @Bind(R.id.btn_Camera)
    Button btnCamera;
    @Bind(R.id.btn_Gallery)
    Button btnGallary;
    File file;
    Uri uri;
    Intent intent_Camera, intent_Gallary, intent_Cropping;

    @Override     
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imagemarsh);
        ButterKnife.bind(this);
        Check_EnableRuntimePermission();

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

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

    }
    public void GetFromCamera() {
        intent_Camera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        file = new File(Environment.getExternalStorageDirectory(),
                "file" + String.valueOf(System.currentTimeMillis()) + ".jpg");
        uri = Uri.fromFile(file);
        intent_Camera.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);
        intent_Camera.putExtra("return-data", true);
        startActivityForResult(intent_Camera, 0);
    }

    public void GetFromGallary() {
        intent_Gallary = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent_Gallary, "Get Image From Gallery"), 2);
    }

    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0 && resultCode == RESULT_OK) {
            CropSelectedImage();
        } else if (requestCode == 2) {
            if (data != null) {
                uri = data.getData();
                //Cropping image 
                 CropSelectedImage();
            }
        } else if (requestCode == 1) {
            if (data != null) {
                Bundle bundle = data.getExtras();
                Bitmap bitmap = bundle.getParcelable("data");
                ivSelectImage.setImageBitmap(bitmap);
            }
        }
    }

    public void CropSelectedImage() {
        // Cropping image started here         
        try {
            intent_Cropping = new Intent("com.android.camera.action.CROP");
            intent_Cropping.setDataAndType(uri, "image/*");
            intent_Cropping.putExtra("crop", "true");
            intent_Cropping.putExtra("outputX", 180);
            intent_Cropping.putExtra("outputY", 180);
            intent_Cropping.putExtra("aspectX", 3);
            intent_Cropping.putExtra("aspectY", 4);
            intent_Cropping.putExtra("scaleUpIfNeeded", true);
            intent_Cropping.putExtra("return-data", true);
            startActivityForResult(intent_Cropping, 1);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void Check_EnableRuntimePermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(Imgmarsh.this,
                Manifest.permission.CAMERA)) {
            Toast.makeText(Imgmarsh.this, "Permission for access camera"
Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(Imgmarsh.this, new String[]{
                    Manifest.permission.CAMERA}, RequestPermissionCode);
        }
    }

    @Override 
    public void onRequestPermissionsResult(int reqCode, String per[], int[] PrmsnResult) {
        switch (reqCode) {
            case RequestPermissionCode:
                if (PrmsnResult.length > 0 && PrmsnResult[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(Imgmarsh.this, "Successfully camera permission granted"
Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(Imgmarsh.this, "Camera permission canceled"
Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}
 
//compile 'com.jakewharton:butterknife:7.0.1' 

Sunday 14 May 2017

RecyclerView adapter example

MyAdapter.java

public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.ViewHolder> {
    Context mContext;
    Activity mActivity;
    ArrayList<CustomerModel> list;

    public CustomerAdapter(Context context, ArrayList<CustomerModel> list) {
        this.list = list;
        this.mContext = context;
        this.mActivity = (Activity) context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.row_customerlist, parent,
                false);
        ViewHolder holder = new ViewHolder(v);
        return holder;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int i) {
        final CustomerModel item = list.get(i);
        holder.txt_customer_name.setText(item.getCust_name());
        holder.txt_customer_mobileno.setText(item.getCust_mobileno());

        Font.RobotoRegular.apply(mContext, holder.txt_customer_name);
        Font.RobotoLight.apply(mContext, holder.txt_customer_mobileno);


        try {
            Picasso.with(mContext)
                    .load(item.getCust_profilepic())
                    //.transform(new RoundedTransformation(100, -25)).fit()
                    .placeholder(R.drawable.ic_loading).fit()
                    //.transform(new RoundedTransformation(20, 0)).fit()
                    .error(R.drawable.ic_loading).into(holder.ivProfile);
        } catch (Exception e) {
            e.printStackTrace();
        }
     
      if (mContext instanceof PlanActivity) {
            holder.btnServiceSell.setVisibility(View.VISIBLE);
        } else {
            holder.btnServiceSell.setVisibility(View.GONE);
        }

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(mContext, ListActivity.class);
                i.putExtra(Connection.Tag_customer_id, item.getCust_id());
                Log.e("ciddd-", item.getCust_id());
                mContext.startActivity(i);

            }
        });

    }

    @Override
    public int getItemCount() {
        return (null != list ? list.size() : 0);
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView txt_customer_name, txt_customer_mobileno;
        CircularImageView ivProfile;

        public ViewHolder(View v) {
            super(v);
            txt_customer_name = (TextView) v.findViewById(R.id.tvusername);
            txt_customer_mobileno = (TextView) v.findViewById(R.id.tvusermobileno);
            ivProfile = (CircularImageView) v.findViewById(R.id.imguserpic);
        }

        @Override
        public void onClick(View v) {
            Log.e("------------", "------- ");
        }
    }
}

Saturday 13 May 2017

Call Async http RESTful Api Example(LoopJ)

SampleCode.java

public class ListActivity extends AppCompatActivity {
    Toolbar toolbar;
    Functions function;
    SharedPreferences Pref;
    ArrayList<myModel> CArrayList = new ArrayList<myModel>();
    RecyclerView recyclerViewCar;
    StringEntity entity = null;
    AsyncHttpClient client;
    JSONObject objSend;
    Intent i;
    String customer_id;
    RelativeLayout ivBack;
    TextView txtTitle;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.car_list);
        function = new Functions(ListActivity.this);
        Pref = getSharedPreferences(getResources().getString(R.string.app_name), MODE_PRIVATE);
        // Drawer.displayDrawer(CustomerDetailsActivity.this);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(getResources().getString(R.string.act));
        ivBack = (RelativeLayout) findViewById(R.id.imgback);
        txtTitle = (TextView) findViewById(R.id.txttitle);
        txtTitle.setText(getResources().getString(R.string.car));
        //toolbar.setNavigationIcon(R.mipmap.drawer);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(false);
        recyclerViewCar = (RecyclerView) findViewById(R.id.rc_car);
        recyclerViewCar.setHasFixedSize(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerViewCar.setLayoutManager(layoutManager);
        i = getIntent();
        if (i.getExtras() != null) {
            customer_id = i.getStringExtra(Constr.Tag_customer_id);
        }
        if (function.isOnline(toolbar, R.string.internet_not_available)) {
            getSelldata(customer_id);
        }
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
    }


    public void getdata(final String customerid) {
        function.show();
        JSONObject get_JSONObject = function.request_json();
        try {
            objSend = new JSONObject(get_JSONObject.toString());
            objSend.put("txtuserid", customerid);
            objSend.put("user_type", "SPA");
            objSend.put("txt_id", function.getUserId());
            Log.e("paramSellistCustomerid", objSend.toString().trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        try {
            entity = new StringEntity(objSend.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        client = new AsyncHttpClient();
        client.setTimeout(30 * 1000);
        client.setMaxConnections(6);
client.post(getApplicationContext(), Constr.GETLIST, entity, "application/json", new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
if (responseString != null) {
Toast.makeText(getApplicationContext(), "Fail to load data", Toast.LENGTH_LONG).show();
}
 function.dismiss();
}
 @Override
 public void onSuccess(int statusCode, Header[] headers, String responseString) {
 if (statusCode == 200 && responseString != null) {
     Log.e("onSuccess", responseString);
     try {
     JSONObject json = new JSONObject(responseString);
     int success = json.getInt(Constr.TAG_SUCCESS);
     if (success == 1) {
      JSONArray arrList = json.getJSONArray("allnewdata");
      for (int i = 0; i < arrList.length(); i++) {
      JSONObject c = arrList.getJSONObject(i);
       myModel obj = new myModel();
        obj.set_no(c.getString(Constr.Tag_no).trim());
         obj.set_pic(c.getString(Constr.Tag_act_pic).trim());
              if (c != null) {
                  JSONArray all_jsondata = c.getJSONArray(Constr.Tag_jsonarrayname);
                   if (all_jsondata != null) {
                 for (int j = 0; j < all_jsondata.length(); j++) {
                JSONObject objData = all_jsondata.getJSONObject(j);
               obj.setCl_id(objData.getString(Constr.Tag_cl_id).trim());
               obj.setCl_id(objData.getString(Constr.Tag_cl_details_pid).trim());
               obj.setCl_name(objData.getString(Constr.Tag_cl_pname).trim());
               obj.setCl_desc(objData.getString(Constr.Tag_cl_pdesc).trim());
               obj.setClperson_id(objData.getString(Constr.Tag_cl_sid).trim());
               obj.setCl_customer_id(objData.getString(Constr.Tag_cl_custid).trim());
               obj.setCl_customer_name(objData.getString(Constr.Tag_cl_custname).trim());
               obj.setCl_customer_email(objData.getString(Constr.Tag_cl_custemail).trim());
               //get JSONArray in response

               obj.setSellplanpkgdata(objData.getJSONArray(Constr.Tag_jsonArrayData));
               /*if (objData != null) {
                   JSONArray all_Sdata = objData.getJSONArray(Constr.Tag_jsonArrayData);
                   if (all_sellobjSjData != null) {
                       for (int k = 0; k < all_Sdata.length(); k++) {
                        JSONObject objSjData = all_sellobjSjData.getJSONObject(k);
                        obj.setCssellsdetails_id(objSjData.getString(Constr.Tag_cldetails_id).trim());
                           obj.setCl_id(objSjData.getString(Constr.Tag_cl_id).trim());
                           obj.setClsdetails_prod_qty(objSjData.getString(Constr.Tag_cs_ssdetails_total_qty).trim());
                           obj.setClsdetails_pused_qty(objSjData.getString(Constr.Tag_cs_sdetails_used_qty).trim());
                       }
                   }
               }*/
               CArrayList.add(obj);
           }
         }
        }
       }
      }
                        if (CArrayList.size() > 0) {
                            CAdapter adapter = new CarAdapter(ListActivity.this, CArrayList);
                            recyclerViewCar.setAdapter(adapter);
                        }
                        function.dismiss();
      } catch (JSONException e) {
          e.printStackTrace();
      }
     }
    }
   });
  }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                if (Drawer.mDrawerLayout.isDrawerOpen(Drawer.flDrawerRl)) {
                    Drawer.mDrawerLayout.closeDrawers();
                } else {
                    Drawer.mDrawerLayout.openDrawer(Drawer.flDrawerRl);
                }
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
build.gradle
apply plugin: 'com.android.application'
android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.andy"
        minSdkVersion 11
        targetSdkVersion 20
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
    testCompile 'junit:junit:4.12'
    compile 'com.loopj.android:android-async-http:1.4.9'
    compile 'com.android.support:support-v4:25.2.0'
    compile 'com.android.support:recyclerview-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile files('libs/httpmime-4.0.3.jar')
    compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
    compile files('libs/apache-mime4j-0.6.jar')
    compile 'com.nineoldandroids:library:2.4.0+'
    compile 'com.android.support:cardview-v7:25+'
    //compile 'com.theartofdev.edmodo:android-image-cropper:2.4.+'
    //compile 'com.android.support:cardview-v7:26.0.0-alpha1'
}