* Activity
=======
1)LoginActivity.java
====================
=======
1)LoginActivity.java
====================
package com.multiselectList.activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import com.bumptech.glide.Glide; import com.multiselectList.Utility.Constants; import com.multiselectList.Utility.CustomDialog; import com.multiselectList.Utility.PrefHelper; import com.multiselectList.Utility.Utils; import java.util.ArrayList; import java.util.Calendar; /** * Created by Manisha on 11/6/2017. */ public class LoginActivity extends AppCompatActivity { private EditText edtFirstName, edtLastName, edtEmail, edtPassword, edtConfirmPassword, edtPhoneNumber; private TextView txtBirthDate, txtBirthDateLable; private String mFirstName, mLastName, mEmail, mPassword, mConfirmPwd, mBirthDate, mPhoneNumber; private int mGender; private RadioGroup radioGroupGender; private View view; private Uri outputFileUri; private ImageView imgProfile, imgActionBarMenu; final int REQ_CODE_PERMISSION_CAMERA = 40; final int REQ_CODE_PERMISSION_GALLERY = 41; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); } public void initData() { edtFirstName = (EditText) view.findViewById(R.id.frag_register_edt_first_name); edtLastName = (EditText) view.findViewById(R.id.frag_register_edt_last_name); edtEmail = (EditText) view.findViewById(R.id.frag_register_edt_email); edtPassword = (EditText) view.findViewById(R.id.frag_register_edt_password); edtConfirmPassword = (EditText) view.findViewById(R.id.frag_register_edt_confirm_password); txtBirthDate = (TextView) view.findViewById(R.id.frag_register_txt_birth_date); edtPhoneNumber = (EditText) view.findViewById(R.id.frag_register_edt_phone_number); radioGroupGender = (RadioGroup) view.findViewById(R.id.frag_register_radio_group_gender); TextView txtActionbarTitle = (TextView) view.findViewById(R.id.txt_actionbar_title); imgProfile = (ImageView) view.findViewById(R.id.frag_register_img_profile); txtBirthDateLable = (TextView) view.findViewById(R.id.frag_register_txt_lbl_birthdate); txtBirthDateLable.setVisibility(View.INVISIBLE); Utils.getInstance().setupOutSideTouchHideKeyboard(view.findViewById(R.id.frag_register_parent_view)); txtActionbarTitle.setText(getResources().getString(R.string.sign_up)); imgActionBarMenu = (ImageView) view.findViewById(R.id.img_actionbar_menu); imgActionBarMenu.setVisibility(View.INVISIBLE); homeActivity.setSlidingMenuEnable(false); } /** * Handle Activity click events */ public void clickEvent(View v) { switch (v.getId()) { case R.id.frag_register_btn_signup: if (FieldValidation()) { mBirthDate = txtBirthDate.getText().toString().trim(); int selectedId = radioGroupGender.getCheckedRadioButtonId(); RadioButton radioButton = (RadioButton) view.findViewById(selectedId); if (radioButton.getText().toString().equalsIgnoreCase(getResources().getString(R.string.male))) { mGender = 0; } else if (radioButton.getText().toString().equalsIgnoreCase(getResources().getString(R.string.female))) { mGender = 1; } if (homeActivity.dbHelper.isEmailExist(edtEmail.getText().toString().trim())) { CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.email_already_exists)); } else { homeActivity.dbHelper.insertUser(mFirstName, mLastName, mEmail, mPassword, mBirthDate, mPhoneNumber, outputFileUri.toString(), mGender); PrefHelper.setBoolean(getResources().getString(R.string.is_login),true); homeActivity.removeAllFragment(); homeActivity.pushFragments(new DashBoardFragment(), true, false, true); } } break; case R.id.frag_register_txt_birth_date: Utils.getInstance().hideKeyboard(view, getActivity()); showDatePickerDialog(); break; case R.id.frag_register_img_profile: dialogChoosePicture(); break; } } /* Function for show datepicker dialog */ public void showDatePickerDialog() { Calendar calendar = Calendar.getInstance(); DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar newDate = Calendar.getInstance(); newDate.set(year, monthOfYear, dayOfMonth); String date = String.valueOf(dayOfMonth) + "/" + String.valueOf(monthOfYear + 1) + "/" + String.valueOf(year); txtBirthDate.setText(date); txtBirthDateLable.setVisibility(View.VISIBLE); } }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); datePickerDialog.getDatePicker().setMaxDate(calendar.getTimeInMillis()); datePickerDialog.show(); } /* custom dialog for choose picture*/ public void dialogChoosePicture() { final Dialog dialog = new Dialog(this, android.R.style.Theme_Dialog); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.setContentView(R.layout.custom_dialog_media_chooser); TextView btnGallery = (TextView) dialog.findViewById(R.id.custom_dialog_media_chooser_txt_library); btnGallery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); openGallery(); } }); TextView btnCamera = (TextView) dialog.findViewById(R.id.custom_dialog_media_chooser_txt_camera); btnCamera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); openCameraForCaptureImage(); } }); TextView btnCancel = (TextView) dialog.findViewById(R.id.custom_dialog_media_chooser_txt_cancel); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Constants.REQ_CODE_CAPTURE_IMAGE && resultCode == RESULT_OK) { Intent intent = new Intent(getActivity(), ImageCropActivity.class); intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 100); intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 100); intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); intent.putExtra(ImageCropActivity.EXTRA_IMAGE_URI, outputFileUri); startActivityForResult(intent, Constants.REQ_CODE_CROP_IMAGE); } else if (requestCode == Constants.REQ_CODE_GALLERY_IMAGE && resultCode == RESULT_OK && null != data) { if (data != null && data.getData() != null) { Uri selectedImageUri = data.getData(); String mImageURI = Utils.getInstance().getRealPathFromURI(getActivity(), selectedImageUri); //Copy Original File to app media folder String copiedFilepath = FileUtils.getInstance().copyFile(mImageURI, FileUtils.getInstance().getFilePath(getActivity(), FileUtils.MEDIA_TYPE.PICTURE)); Intent intent = new Intent(getActivity(), ImageCropActivity.class); intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 100); intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 100); outputFileUri = Uri.fromFile(new File(copiedFilepath)); intent.putExtra(ImageCropActivity.EXTRA_IMAGE_URI, outputFileUri); startActivityForResult(intent, Constants.REQ_CODE_CROP_IMAGE); } } else if (requestCode == Constants.REQ_CODE_CROP_IMAGE && resultCode == Activity.RESULT_OK && data != null) { Bundle bundle = data.getExtras(); if (bundle != null) { outputFileUri = bundle.getParcelable(ImageCropActivity.EXTRA_IMAGE_URI); setProfileImage(outputFileUri); } } } // @Override// public void onActivityResult(int requestCode, int resultCode, Intent data) {// if (requestCode == Constants.REQ_CODE_CAPTURE_IMAGE && resultCode == Activity.RESULT_OK) {//// Intent intent = new Intent(getActivity(), ImageCropActivity.class);// intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 100);// intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 100);// intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);// intent.putExtra(ImageCropActivity.EXTRA_IMAGE_URI, outputFileUri);//// startActivityForResult(intent, Constants.REQ_CODE_CROP_IMAGE);//// } else if (requestCode == Constants.REQ_CODE_GALLERY_IMAGE && resultCode == Activity.RESULT_OK && null != data) {//// if (data != null && data.getData() != null) {// Uri selectedImageUri = data.getData();// String mImageURI = Utils.getInstance().getRealPathFromURI(getActivity(), selectedImageUri);// //Copy Original File to app media folder// String copiedFilepath = FileUtils.getInstance().copyFile(mImageURI, FileUtils.getInstance().getFilePath(getActivity(), FileUtils.MEDIA_TYPE.PICTURE));// Intent intent = new Intent(getActivity(), ImageCropActivity.class);// intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 100);// intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 100);//// outputFileUri = Uri.fromFile(new File(copiedFilepath));// intent.putExtra(ImageCropActivity.EXTRA_IMAGE_URI, outputFileUri);// startActivityForResult(intent, Constants.REQ_CODE_CROP_IMAGE);// }//// } else if (requestCode == Constants.REQ_CODE_CROP_IMAGE && resultCode == Activity.RESULT_OK && data != null) {// Bundle bundle = data.getExtras();// if (bundle != null) {// outputFileUri = bundle.getParcelable(ImageCropActivity.EXTRA_IMAGE_URI);// setProfileImage(outputFileUri);// }// }// } private void setProfileImage(Uri uri) { if (uri != null) { Glide.with(this).load(uri) .placeholder(R.mipmap.ic_default_profile) .error(R.mipmap.ic_default_profile) .into(imgProfile); } else { imgProfile.setImageResource(R.mipmap.ic_default_profile); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { ArrayList<String> listNotGrantedPermissions; switch (requestCode) { case REQ_CODE_PERMISSION_CAMERA: listNotGrantedPermissions = PermissionUtil.getInstance().verifyPermissions(permissions, grantResults); if (listNotGrantedPermissions != null && listNotGrantedPermissions.size() > 0) { checkCameraPermissions(listNotGrantedPermissions, requestCode, false); } else { openCameraForCaptureImage(); } break; case REQ_CODE_PERMISSION_GALLERY: listNotGrantedPermissions = PermissionUtil.getInstance().verifyPermissions(permissions, grantResults); if (listNotGrantedPermissions != null && listNotGrantedPermissions.size() > 0) { checkCameraPermissions(listNotGrantedPermissions, requestCode, false); } else { openGallery(); } break; } } /*function for check open gallery*/ private void openGallery() { ArrayList<String> listPermissionsNeed = PermissionUtil.getInstance().getGalleryPermission(); if (checkCameraPermissions(listPermissionsNeed, REQ_CODE_PERMISSION_GALLERY, true)) { Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, Constants.REQ_CODE_GALLERY_IMAGE); } } /*function for check open camera*/ private void openCameraForCaptureImage() { ArrayList<String> listPermissionsNeed = PermissionUtil.getInstance().getCameraPermissionsList(); if (checkCameraPermissions(listPermissionsNeed, REQ_CODE_PERMISSION_CAMERA, true)) { try { Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { outputFileUri = FileProvider.getUriForFile(getActivity(), getActivity().getApplicationContext().getPackageName() + ".provider", new File(FileUtils.getInstance().getFilePath(getActivity(),FileUtils.MEDIA_TYPE.PICTURE))); }else { outputFileUri = FileUtils.getInstance().getFileUri(getActivity(), FileUtils.MEDIA_TYPE.PICTURE); } captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); startActivityForResult(captureIntent, Constants.REQ_CODE_CAPTURE_IMAGE); } catch (ActivityNotFoundException e) { e.getMessage(); } } } /*function for check camera permission*/ private boolean checkCameraPermissions(ArrayList<String> listPermissions, int reqCode, boolean isFirstTime) { if (listPermissions == null || listPermissions.size() <= 0) return true; ArrayList<String> listPermissionsNeeded = new ArrayList<String>(); if (isFirstTime) { for (int i = 0; i < listPermissions.size(); i++) { if (ActivityCompat.checkSelfPermission(getActivity(), listPermissions.get(i)) != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(listPermissions.get(i)); } } } if (!listPermissionsNeeded.isEmpty()) { requestPermissions(listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), reqCode); return false; } return true; } /*Validate fields*/ public boolean FieldValidation() { boolean flag = true; mFirstName = edtFirstName.getText().toString().trim(); mLastName = edtLastName.getText().toString().trim(); mEmail = edtEmail.getText().toString().trim(); mPassword = edtPassword.getText().toString().trim(); mConfirmPwd = edtConfirmPassword.getText().toString().trim(); mBirthDate = txtBirthDate.getText().toString().trim(); mPhoneNumber = edtPhoneNumber.getText().toString().trim(); if (outputFileUri == null) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_select_image)); } else if (!Utils.getInstance().validateString(mFirstName)) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_first_name)); } else if (!Utils.getInstance().validateString(mLastName)) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_last_name)); } else if (!Utils.getInstance().validateString(mEmail)) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_email)); } else if (!Utils.getInstance().isEmailValid(mEmail)) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_valid_email)); } else if (!Utils.getInstance().validateString(mPassword)) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_password)); } else if (mPassword.length() < 8) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.password_is_too_short)); } else if (!Utils.getInstance().validateString(mConfirmPwd)) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_confirm_password)); } else if (!TextUtils.equals(mPassword, mConfirmPwd)) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.password_does_not_match)); } else if (mPhoneNumber.length() < 10) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_valid_phone_number)); } else if (!Utils.getInstance().validateString(mBirthDate) || mBirthDate.equalsIgnoreCase(getResources().getString(R.string.birth_Date))) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_birth_date)); } return flag; } /** * Handle Activity click events */ @Override public void onBackPressed() { homeActivity.popFragment(); } }
2)MainActivity.java
===================
package com.multiselectList.activity; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.ActionMode; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.multiselectList.MyApplication; import com.multiselectList.Utility.AlertDialogHelper; import com.multiselectList.Utility.RecyclerItemClickListener; import com.multiselectList.adapter.MultiSelectAdapter; import com.multiselectList.api.ApiResponseListener; import com.multiselectList.api.RestClient; import com.multiselectList.model.SampleModel; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Response; public class MainActivity extends AppCompatActivity implements AlertDialogHelper.AlertDialogListener, ApiResponseListener { ActionMode mActionMode; Menu context_menu; FloatingActionButton fab; RecyclerView recyclerView; MultiSelectAdapter multiSelectAdapter; boolean isMultiSelect = false; ArrayList<SampleModel> user_list = new ArrayList<>(); ArrayList<SampleModel> multiselect_list = new ArrayList<>(); AlertDialogHelper alertDialogHelper; public RestClient restClient; public MyApplication appInstance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); appInstance = (MyApplication) getApplication(); restClient = appInstance.getRestClient(); alertDialogHelper = new AlertDialogHelper(this); recyclerView = (RecyclerView) findViewById(R.id.recycler_view); data_load(); multiSelectAdapter = new MultiSelectAdapter(this, user_list, multiselect_list); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); recyclerView.setLayoutManager(mLayoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setAdapter(multiSelectAdapter); recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { if (isMultiSelect) multi_select(position); else Toast.makeText(getApplicationContext(), "Details Page", Toast.LENGTH_SHORT).show(); } @Override public void onItemLongClick(View view, int position) { if (!isMultiSelect) { multiselect_list = new ArrayList<SampleModel>(); isMultiSelect = true; if (mActionMode == null) { mActionMode = startActionMode(mActionModeCallback); } } multi_select(position); } })); fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Click action alertDialogHelper.showAlertDialog("", "Do you want to add new contact", "LATER", "ADD", 2, false); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_common_activity, menu); return true; } @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(); switch (id) { case android.R.id.home: onBackPressed(); return true; case R.id.action_settings: Toast.makeText(getApplicationContext(), "Settings Click", Toast.LENGTH_SHORT).show(); return true; case R.id.action_exit: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } public void data_load() { String name[] = {"Gokul", "Rajesh", "Ranjith", "Madhu", "Ameer", "Sonaal"}; String posting[] = {"Manager", "HR", "Android Developer", "iOS Developer", "Team Leader", "Designer"}; for (int i = 0; i < name.length; i++) { SampleModel mSample = new SampleModel(name[i], posting[i]); user_list.add(mSample); } } public void multi_select(int position) { if (mActionMode != null) { if (multiselect_list.contains(user_list.get(position))) multiselect_list.remove(user_list.get(position)); else multiselect_list.add(user_list.get(position)); if (multiselect_list.size() > 0) mActionMode.setTitle("" + multiselect_list.size()); else mActionMode.setTitle(""); refreshAdapter(); } } public void refreshAdapter() { multiSelectAdapter.selected_usersList = multiselect_list; multiSelectAdapter.usersList = user_list; multiSelectAdapter.notifyDataSetChanged(); } private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() { @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { // Inflate a menu resource providing context menu items MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.menu_multi_select, menu); context_menu = menu; return true; } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; // Return false if nothing is done } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.action_delete: alertDialogHelper.showAlertDialog("", "Delete Contact", "DELETE", "CANCEL", 1, false); return true; default: return false; } } @Override public void onDestroyActionMode(ActionMode mode) { mActionMode = null; isMultiSelect = false; multiselect_list = new ArrayList<SampleModel>(); refreshAdapter(); } }; // AlertDialog Callback Functions @Override public void onPositiveClick(int from) { if (from == 1) { if (multiselect_list.size() > 0) { for (int i = 0; i < multiselect_list.size(); i++) user_list.remove(multiselect_list.get(i)); multiSelectAdapter.notifyDataSetChanged(); if (mActionMode != null) { mActionMode.finish(); } Toast.makeText(getApplicationContext(), "Delete Click", Toast.LENGTH_SHORT).show(); } } else if (from == 2) { if (mActionMode != null) { mActionMode.finish(); } SampleModel mSample = new SampleModel("Name" + user_list.size(), "Designation" + user_list.size()); user_list.add(mSample); multiSelectAdapter.notifyDataSetChanged(); } } public void getData() { Call<SampleModel> objectCall = RestClient.getApiClient().getSpotFollowersList(/*homeActivity.loginModel.getUserId() + "",*/ spotId + "", String.valueOf(pageNo), search); restClient.makeApiRequest(this, objectCall, this, this.getResources().getInteger(R.integer.reqCodeGetFollowersList), showDialog); } @Override public void onNegativeClick(int from) { } @Override public void onNeutralClick(int from) { } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if (reqCode == getResources().getInteger(R.integer.reqCodeGetFollowersList) || reqCode == getResources().getInteger(R.integer.reqCodeUserFollowersList)) { SampleModel followersListModel = (SampleModel) response.body(); // totalCount = followersListModel.getTotalCount(); if (listFollowers == null) listFollowers = new ArrayList<FollowersListModel.Followuser>(); if (followersListModel.getFollowuser() != null) { listFollowers.addAll(followersListModel.getFollowuser()); } // bindUserList(listFollowers); } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode, int position) { } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { } }3)RegistrationActivity.java=============================package com.multiselectList.activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import com.bumptech.glide.Glide; import com.multiselectList.Utility.CustomDialog; import com.multiselectList.Utility.PrefHelper; import com.multiselectList.Utility.Utils; import java.util.ArrayList; import java.util.Calendar; /** * Created by Manisha on 11/6/2017. */ public class RegistrationActivity extends AppCompatActivity { private EditText edtFirstName, edtLastName, edtEmail, edtPassword, edtConfirmPassword, edtPhoneNumber; private TextView txtBirthDate, txtBirthDateLable; private String mFirstName, mLastName, mEmail, mPassword, mConfirmPwd, mBirthDate, mPhoneNumber; private int mGender; private RadioGroup radioGroupGender; private View view; private Uri outputFileUri; private ImageView imgProfile, imgActionBarMenu; final int REQ_CODE_PERMISSION_CAMERA = 40; final int REQ_CODE_PERMISSION_GALLERY = 41; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); } public void initData() { edtFirstName = (EditText) view.findViewById(R.id.frag_register_edt_first_name); edtLastName = (EditText) view.findViewById(R.id.frag_register_edt_last_name); edtEmail = (EditText) view.findViewById(R.id.frag_register_edt_email); edtPassword = (EditText) view.findViewById(R.id.frag_register_edt_password); edtConfirmPassword = (EditText) view.findViewById(R.id.frag_register_edt_confirm_password); txtBirthDate = (TextView) view.findViewById(R.id.frag_register_txt_birth_date); edtPhoneNumber = (EditText) view.findViewById(R.id.frag_register_edt_phone_number); radioGroupGender = (RadioGroup) view.findViewById(R.id.frag_register_radio_group_gender); TextView txtActionbarTitle = (TextView) view.findViewById(R.id.txt_actionbar_title); imgProfile = (ImageView) view.findViewById(R.id.frag_register_img_profile); txtBirthDateLable = (TextView) view.findViewById(R.id.frag_register_txt_lbl_birthdate); txtBirthDateLable.setVisibility(View.INVISIBLE); Utils.getInstance().setupOutSideTouchHideKeyboard(view.findViewById(R.id.frag_register_parent_view)); txtActionbarTitle.setText(getResources().getString(R.string.sign_up)); imgActionBarMenu = (ImageView) view.findViewById(R.id.img_actionbar_menu); imgActionBarMenu.setVisibility(View.INVISIBLE); // homeActivity.setSlidingMenuEnable(false); } /** * Handle Activity click events */ public void clickEvent(View v) { switch (v.getId()) { case R.id.frag_register_btn_signup: if (FieldValidation()) { mBirthDate = txtBirthDate.getText().toString().trim(); int selectedId = radioGroupGender.getCheckedRadioButtonId(); RadioButton radioButton = (RadioButton) view.findViewById(selectedId); if (radioButton.getText().toString().equalsIgnoreCase(getResources().getString(R.string.male))) { mGender = 0; } else if (radioButton.getText().toString().equalsIgnoreCase(getResources().getString(R.string.female))) { mGender = 1; } //// if (homeActivity.dbHelper.isEmailExist(edtEmail.getText().toString().trim())) {// CustomDialog.getInstance().showMessageDialog(this,// getResources().getString(R.string.email_already_exists));// } else {// homeActivity.dbHelper.insertUser(mFirstName, mLastName, mEmail, mPassword, mBirthDate, mPhoneNumber, outputFileUri.toString(), mGender);// PrefHelper.setBoolean(getResources().getString(R.string.is_login),true);// homeActivity.removeAllFragment();// homeActivity.pushFragments(new DashBoardFragment(), true, false, true);// } } break; case R.id.frag_register_txt_birth_date: Utils.getInstance().hideKeyboard(view, this); showDatePickerDialog(); break; case R.id.frag_register_img_profile: dialogChoosePicture(); break; } } /* Function for show datepicker dialog */ public void showDatePickerDialog() { Calendar calendar = Calendar.getInstance(); DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Calendar newDate = Calendar.getInstance(); newDate.set(year, monthOfYear, dayOfMonth); String date = String.valueOf(dayOfMonth) + "/" + String.valueOf(monthOfYear + 1) + "/" + String.valueOf(year); txtBirthDate.setText(date); txtBirthDateLable.setVisibility(View.VISIBLE); } }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)); datePickerDialog.getDatePicker().setMaxDate(calendar.getTimeInMillis()); datePickerDialog.show(); } /* custom dialog for choose picture*/ public void dialogChoosePicture() { final Dialog dialog = new Dialog(this, android.R.style.Theme_Dialog); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.setContentView(R.layout.custom_dialog_media_chooser); TextView btnGallery = (TextView) dialog.findViewById(R.id.custom_dialog_media_chooser_txt_library); btnGallery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); openGallery(); } }); TextView btnCamera = (TextView) dialog.findViewById(R.id.custom_dialog_media_chooser_txt_camera); btnCamera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); openCameraForCaptureImage(); } }); TextView btnCancel = (TextView) dialog.findViewById(R.id.custom_dialog_media_chooser_txt_cancel); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == Constants.REQ_CODE_CAPTURE_IMAGE && resultCode == RESULT_OK) { Intent intent = new Intent(this, ImageCropActivity.class); intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 100); intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 100); intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); intent.putExtra(ImageCropActivity.EXTRA_IMAGE_URI, outputFileUri); startActivityForResult(intent, Constants.REQ_CODE_CROP_IMAGE); } else if (requestCode == Constants.REQ_CODE_GALLERY_IMAGE && resultCode == RESULT_OK && null != data) { if (data != null && data.getData() != null) { Uri selectedImageUri = data.getData(); String mImageURI = Utils.getInstance().getRealPathFromURI(this, selectedImageUri); //Copy Original File to app media folder String copiedFilepath = FileUtils.getInstance().copyFile(mImageURI, FileUtils.getInstance().getFilePath(this, FileUtils.MEDIA_TYPE.PICTURE)); Intent intent = new Intent(this, ImageCropActivity.class); intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 100); intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 100); outputFileUri = Uri.fromFile(new File(copiedFilepath)); intent.putExtra(ImageCropActivity.EXTRA_IMAGE_URI, outputFileUri); startActivityForResult(intent, Constants.REQ_CODE_CROP_IMAGE); } } else if (requestCode == Constants.REQ_CODE_CROP_IMAGE && resultCode == Activity.RESULT_OK && data != null) { Bundle bundle = data.getExtras(); if (bundle != null) { outputFileUri = bundle.getParcelable(ImageCropActivity.EXTRA_IMAGE_URI); setProfileImage(outputFileUri); } } } // @Override// public void onActivityResult(int requestCode, int resultCode, Intent data) {// if (requestCode == Constants.REQ_CODE_CAPTURE_IMAGE && resultCode == Activity.RESULT_OK) {//// Intent intent = new Intent(this, ImageCropActivity.class);// intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 100);// intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 100);// intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);// intent.putExtra(ImageCropActivity.EXTRA_IMAGE_URI, outputFileUri);//// startActivityForResult(intent, Constants.REQ_CODE_CROP_IMAGE);//// } else if (requestCode == Constants.REQ_CODE_GALLERY_IMAGE && resultCode == Activity.RESULT_OK && null != data) {//// if (data != null && data.getData() != null) {// Uri selectedImageUri = data.getData();// String mImageURI = Utils.getInstance().getRealPathFromURI(this, selectedImageUri);// //Copy Original File to app media folder// String copiedFilepath = FileUtils.getInstance().copyFile(mImageURI, FileUtils.getInstance().getFilePath(this, FileUtils.MEDIA_TYPE.PICTURE));// Intent intent = new Intent(this, ImageCropActivity.class);// intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 100);// intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 100);//// outputFileUri = Uri.fromFile(new File(copiedFilepath));// intent.putExtra(ImageCropActivity.EXTRA_IMAGE_URI, outputFileUri);// startActivityForResult(intent, Constants.REQ_CODE_CROP_IMAGE);// }//// } else if (requestCode == Constants.REQ_CODE_CROP_IMAGE && resultCode == Activity.RESULT_OK && data != null) {// Bundle bundle = data.getExtras();// if (bundle != null) {// outputFileUri = bundle.getParcelable(ImageCropActivity.EXTRA_IMAGE_URI);// setProfileImage(outputFileUri);// }// }// } private void setProfileImage(Uri uri) { if (uri != null) { Glide.with(this).load(uri) .placeholder(R.mipmap.ic_default_profile) .error(R.mipmap.ic_default_profile) .into(imgProfile); } else { imgProfile.setImageResource(R.mipmap.ic_default_profile); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { ArrayList<String> listNotGrantedPermissions; switch (requestCode) { case REQ_CODE_PERMISSION_CAMERA: listNotGrantedPermissions = PermissionUtil.getInstance().verifyPermissions(permissions, grantResults); if (listNotGrantedPermissions != null && listNotGrantedPermissions.size() > 0) { checkCameraPermissions(listNotGrantedPermissions, requestCode, false); } else { openCameraForCaptureImage(); } break; case REQ_CODE_PERMISSION_GALLERY: listNotGrantedPermissions = PermissionUtil.getInstance().verifyPermissions(permissions, grantResults); if (listNotGrantedPermissions != null && listNotGrantedPermissions.size() > 0) { checkCameraPermissions(listNotGrantedPermissions, requestCode, false); } else { openGallery(); } break; } } /*function for check open gallery*/ private void openGallery() { ArrayList<String> listPermissionsNeed = PermissionUtil.getInstance().getGalleryPermission(); if (checkCameraPermissions(listPermissionsNeed, REQ_CODE_PERMISSION_GALLERY, true)) { Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, Constants.REQ_CODE_GALLERY_IMAGE); } } /*function for check open camera*/ private void openCameraForCaptureImage() { ArrayList<String> listPermissionsNeed = PermissionUtil.getInstance().getCameraPermissionsList(); if (checkCameraPermissions(listPermissionsNeed, REQ_CODE_PERMISSION_CAMERA, true)) { try { Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { outputFileUri = FileProvider.getUriForFile(this, this.getApplicationContext().getPackageName() + ".provider", new File(FileUtils.getInstance().getFilePath(this, FileUtils.MEDIA_TYPE.PICTURE))); } else { outputFileUri = FileUtils.getInstance().getFileUri(this, FileUtils.MEDIA_TYPE.PICTURE); } captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); startActivityForResult(captureIntent, Constants.REQ_CODE_CAPTURE_IMAGE); } catch (ActivityNotFoundException e) { e.getMessage(); } } } /*function for check camera permission*/ private boolean checkCameraPermissions(ArrayList<String> listPermissions, int reqCode, boolean isFirstTime) { if (listPermissions == null || listPermissions.size() <= 0) return true; ArrayList<String> listPermissionsNeeded = new ArrayList<String>(); if (isFirstTime) { for (int i = 0; i < listPermissions.size(); i++) { if (ActivityCompat.checkSelfPermission(this, listPermissions.get(i)) != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(listPermissions.get(i)); } } } if (!listPermissionsNeeded.isEmpty()) { requestPermissions(listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), reqCode); return false; } return true; } /*Validate fields*/ public boolean FieldValidation() { boolean flag = true; mFirstName = edtFirstName.getText().toString().trim(); mLastName = edtLastName.getText().toString().trim(); mEmail = edtEmail.getText().toString().trim(); mPassword = edtPassword.getText().toString().trim(); mConfirmPwd = edtConfirmPassword.getText().toString().trim(); mBirthDate = txtBirthDate.getText().toString().trim(); mPhoneNumber = edtPhoneNumber.getText().toString().trim(); if (outputFileUri == null) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_select_image)); } else if (!Utils.getInstance().validateString(mFirstName)) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_first_name)); } else if (!Utils.getInstance().validateString(mLastName)) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_last_name)); } else if (!Utils.getInstance().validateString(mEmail)) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_email)); } else if (!Utils.getInstance().isEmailValid(mEmail)) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_valid_email)); } else if (!Utils.getInstance().validateString(mPassword)) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_password)); } else if (mPassword.length() < 8) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.password_is_too_short)); } else if (!Utils.getInstance().validateString(mConfirmPwd)) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_confirm_password)); } else if (!TextUtils.equals(mPassword, mConfirmPwd)) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.password_does_not_match)); } else if (mPhoneNumber.length() < 10) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_valid_phone_number)); } else if (!Utils.getInstance().validateString(mBirthDate) || mBirthDate.equalsIgnoreCase(getResources().getString(R.string.birth_Date))) { flag = false; CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.please_enter_birth_date)); } return flag; } /** * Handle Activity click events */ @Override public void onBackPressed() { homeActivity.popFragment(); } }* adapter1)MultiselectAdapter.java==========================package com.multiselectList.adapter; import android.content.Context; import android.support.v4.content.ContextCompat; 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 java.util.ArrayList; import com.multiselectList.model.SampleModel; /** * Created by Jaison on 08/10/16. */ public class MultiSelectAdapter extends RecyclerView.Adapter<MultiSelectAdapter.MyViewHolder> { public ArrayList<SampleModel> usersList=new ArrayList<>(); public ArrayList<SampleModel> selected_usersList=new ArrayList<>(); Context mContext; public class MyViewHolder extends RecyclerView.ViewHolder { public TextView posting, name; public LinearLayout ll_listitem; public MyViewHolder(View view) { super(view); posting = (TextView) view.findViewById(R.id.tv_posting); name = (TextView) view.findViewById(R.id.tv_user_name); ll_listitem=(LinearLayout)view.findViewById(R.id.ll_listitem); } } public MultiSelectAdapter(Context context,ArrayList<SampleModel> userList,ArrayList<SampleModel> selectedList) { this.mContext=context; this.usersList = userList; this.selected_usersList = selectedList; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.item_userlist, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { SampleModel movie = usersList.get(position); holder.name.setText(movie.getName()); holder.posting.setText(movie.getPosting()); if(selected_usersList.contains(usersList.get(position))) holder.ll_listitem.setBackgroundColor(ContextCompat.getColor(mContext, R.color.list_item_selected_state)); else holder.ll_listitem.setBackgroundColor(ContextCompat.getColor(mContext, R.color.list_item_normal_state)); } @Override public int getItemCount() { return usersList.size(); } } *api1)APIError.java=================package com.multiselectList.api; public class APIError { private int statusCode; private String message; private String title; public APIError() { } public int status() { return statusCode; } public String message() { return message; } public String getTitle() { return title; } }2)ApiResponseListener.java==========================package com.multiselectList.api; import retrofit2.Call; import retrofit2.Response; public interface ApiResponseListener { /**Call on success API response with request code*/ void onApiResponse(Call<Object> call, Response<Object> response, int reqCode); /**Call on success API response with request code and passed position*/ void onApiResponse(Call<Object> call, Response<Object> response, int reqCode, int position); /**Call on error of API with request code */ void onApiError(Call<Object> call, Object object, int reqCode); }3)ErrorUtils.java=================package com.multiselectList.api; import java.lang.annotation.Annotation; import okhttp3.ResponseBody; import retrofit2.Converter; import retrofit2.Response; public class ErrorUtils { public static APIError parseError(Response<?> response) { Converter<ResponseBody, APIError> converter = RestClient.retrofit().responseBodyConverter(APIError.class, new Annotation[0]); APIError error=null; try { error = converter.convert(response.errorBody()); } catch (Exception e) { e.printStackTrace(); //return new APIError(); } return error; } }4)MyAppAPI.java===============package com.multiselectList.api; import com.multiselectList.model.SampleModel; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Query; public interface MyAppAPI { // @GET("api.json?rss_url=http%3A%2F%2Ftimesofindia.indiatimes.com%2Frssfeeds%2F2886704.cms")// Call<LatestUpdateCategoryModel> getLifestyleData();//// @GET("nearbysearch/json")// Call<NearByLocationModel> getNearByLocation(@Query("location") String location, @Query("rankby") String rankby, @Query("types") String types, @Query("key") String key); @FormUrlEncoded @POST("spot-followers/spot-followers-list") Call<SampleModel> getSpotFollowersList(/*@Field("userId") String userId,*/@Field("spotId") String spotId, @Field("page") String page, @Field("search") String search); }5)RestClient.java=================package com.multiselectList.api; import android.app.Activity; import android.content.Context; import android.support.v4.app.Fragment; import com.multiselectList.BuildConfig; import com.multiselectList.R; import com.multiselectList.Utility.CustomDialog; import com.multiselectList.Utility.Utils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.util.concurrent.TimeUnit; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class RestClient { private static String TAG=RestClient.class.getName(); private static MyAppAPI API_CLIENT; static Retrofit retrofit; Context context; private static int TIME_OUT_DURATION=60; // Seconds public RestClient(Context context,String authKey) { this.context = context; setupRestClient(context,authKey); } public static MyAppAPI getApiClient() { return API_CLIENT; } public void setupRestClient(final Context context,final String authKey) { OkHttpClient.Builder builderOkHttp = new OkHttpClient.Builder(); builderOkHttp.connectTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS); builderOkHttp.readTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS); HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builderOkHttp.networkInterceptors().add(httpLoggingInterceptor); // builderOkHttp.hostnameVerifier(getHostNameVerifier()); if(authKey!=null && authKey.trim().length()>0) { builderOkHttp.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("authorization", "Bearer " + authKey) .addHeader("Content-Type", "application/json") .build(); return chain.proceed(request); } }); } else { builderOkHttp.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Content-Type", "application/json") .build(); return chain.proceed(request); } }); } OkHttpClient client = builderOkHttp.build(); Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .create(); retrofit = new Retrofit.Builder() .baseUrl(context.getString(R.string.baseURL)) .addConverterFactory(GsonConverterFactory.create(gson)) .client(client) .build(); API_CLIENT = retrofit.create(MyAppAPI.class); } /*public void setupRestClient(final Context context) { OkHttpClient.Builder builderOkHttp = new OkHttpClient.Builder(); builderOkHttp.connectTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS); builderOkHttp.readTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS); HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builderOkHttp.networkInterceptors().add(httpLoggingInterceptor);// builderOkHttp.hostnameVerifier(getHostNameVerifier()); builderOkHttp.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException {// PrintLog.e("REST CLIENT", "MY TOKEN :: " + AppPrefs.getInstance(context).getToken());// PrintLog.e("REST CLIENT", "UUID:: " + String.valueOf(deviceUuidFactory.getDeviceUuid())); Request request = chain.request().newBuilder()// .addHeader("Token", AppPrefs.getInstance(context).getToken())// .addHeader("sourceSystemId", AppPrefs.getInstance(context).getSourceSystemId())// .addHeader("buId", AppPrefs.getInstance(context).getBuId()) .addHeader("Content-Type", "application/json")// .addHeader("macId", String.valueOf(deviceUuidFactory.getDeviceUuid())) .build(); return chain.proceed(request); } }); OkHttpClient client = builderOkHttp.build(); Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .create(); retrofit = new Retrofit.Builder() .baseUrl(context.getString(R.string.baseURL)) .addConverterFactory(GsonConverterFactory.create(gson)) .client(client) .build(); API_CLIENT = retrofit.create(EppicoAPI.class); }*/ public static Retrofit retrofit() { return retrofit; } @SuppressWarnings("unchecked") public void makeApiRequest(final Activity activity, Object call, final ApiResponseListener apiResponseListener, final int reqCode,boolean showProgressDialog) { try { if(Utils.getInstance().checkInternetConnection(activity)) { if(showProgressDialog) CustomDialog.getInstance().show(activity,false); final Call<Object> objectCall = (Call<Object>) call; objectCall.enqueue(new Callback<Object>() { @Override public void onResponse(Call<Object> call, retrofit2.Response<Object> response) { CustomDialog.getInstance().hide(); /** Returns true if code() is in the range [200..300). */ if(response.isSuccessful()) { MyLog.v(TAG, "onResponse - Success : " + response.body()); if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiResponse(call, response, reqCode); /* if(apiResponseListener instanceof Fragment) { Fragment fragment = (Fragment) apiResponseListener; if(fragment.isAdded()){ apiResponseListener.onApiResponse(call, response, reqCode); } }*/ } else { if(response.message()!=null && shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, response.message(), reqCode); /*Note: This error log is only for developer. Where developer identify exact API error*/ if (BuildConfig.DEBUG) { APIError error = ErrorUtils.parseError(response); if(error!=null) MyLog.e(TAG, "error message: "+error.message()); } } } @Override public void onFailure(Call<Object> call, Throwable t) { //there is more than just a failing request (like: no internet connection) MyLog.e(TAG, "onFailure - Fail : " + t.getMessage()); CustomDialog.getInstance().hide(); if (t instanceof ConnectException || t instanceof SocketTimeoutException){ //Displaying no network connection error if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, activity.getString(R.string.msgInternetConnectionNotAvailable), reqCode); } else { if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, activity.getString(R.string.msgProblemWithRequest), reqCode); } } }); } else { ToastHelper.getInstance().showToast(activity,activity.getString(R.string.msgInternetConnectionNotAvailable)); } }catch (Exception e) { CustomDialog.getInstance().hide(); e.printStackTrace(); ToastHelper.getInstance().showToast(activity,activity.getString(R.string.msgProblemWithRequest)); } } @SuppressWarnings("unchecked") public void makeApiRequest(final Activity activity,Object call, final ApiResponseListener apiResponseListener, final int reqCode,final int position,boolean showProgressDialog) { try { if(Utils.getInstance().checkInternetConnection(activity)) { if(showProgressDialog) CustomDialog.getInstance().show(activity,false); final Call<Object> objectCall = (Call<Object>) call; objectCall.enqueue(new Callback<Object>() { @Override public void onResponse(Call<Object> call, retrofit2.Response<Object> response) { CustomDialog.getInstance().hide(); /** Returns true if code() is in the range [200..300).*/ if(response.isSuccessful()) { MyLog.v(TAG, "onResponse - Success : " + response.body()); if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiResponse(call,response,reqCode,position); /* if(apiResponseListener instanceof Fragment ) { Fragment fragment = (Fragment) apiResponseListener; if(fragment.isAdded()){ apiResponseListener.onApiResponse(call, response, reqCode); } }*/ } else { if(response.message()!=null && shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, response.message(), reqCode); /*Note: This error log is only for developer. Where developer identify exact API error*/ if (BuildConfig.DEBUG) { APIError error = ErrorUtils.parseError(response); if(error!=null) MyLog.e(TAG, "error message: "+error.message()); } } } @Override public void onFailure(Call<Object> call, Throwable t) { //there is more than just a failing request (like: no internet connection) MyLog.e(TAG, "onFailure - Fail : " + t.getMessage()); CustomDialog.getInstance().hide(); if (t instanceof ConnectException){ //Displaying no network connection error if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, activity.getString(R.string.msgInternetConnectionNotAvailable), reqCode); } else { if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, activity.getString(R.string.msgProblemWithRequest), reqCode); } } }); } else { ToastHelper.getInstance().showToast(activity,activity.getString(R.string.msgInternetConnectionNotAvailable)); } }catch (Exception e) { CustomDialog.getInstance().hide(); e.printStackTrace(); ToastHelper.getInstance().showToast(activity,activity.getString(R.string.msgProblemWithRequest)); } } private boolean shouldCallCallback(ApiResponseListener apiResponseListener) { if(apiResponseListener instanceof Fragment) { Fragment fragment= (Fragment) apiResponseListener; if(fragment.isAdded()) return true; } else if(apiResponseListener instanceof Activity) { Activity activity= (Activity) apiResponseListener; if(!activity.isFinishing()) return true; } return false; } }package com.multiselectList.api;import android.app.Activity; import android.content.Context; import android.support.v4.app.Fragment; import com.multiselectList.BuildConfig; import com.multiselectList.R; import com.multiselectList.Utility.CustomDialog; import com.multiselectList.Utility.Utils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.util.concurrent.TimeUnit; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class RestClient { private static String TAG=RestClient.class.getName(); private static MyAppAPI API_CLIENT; static Retrofit retrofit; Context context; private static int TIME_OUT_DURATION=60; // Seconds public RestClient(Context context,String authKey) { this.context = context; setupRestClient(context,authKey); } public static MyAppAPI getApiClient() { return API_CLIENT; } public void setupRestClient(final Context context,final String authKey) { OkHttpClient.Builder builderOkHttp = new OkHttpClient.Builder(); builderOkHttp.connectTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS); builderOkHttp.readTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS); HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builderOkHttp.networkInterceptors().add(httpLoggingInterceptor); // builderOkHttp.hostnameVerifier(getHostNameVerifier()); if(authKey!=null && authKey.trim().length()>0) { builderOkHttp.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("authorization", "Bearer " + authKey) .addHeader("Content-Type", "application/json") .build(); return chain.proceed(request); } }); } else { builderOkHttp.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Content-Type", "application/json") .build(); return chain.proceed(request); } }); } OkHttpClient client = builderOkHttp.build(); Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .create(); retrofit = new Retrofit.Builder() .baseUrl(context.getString(R.string.baseURL)) .addConverterFactory(GsonConverterFactory.create(gson)) .client(client) .build(); API_CLIENT = retrofit.create(MyAppAPI.class); } /*public void setupRestClient(final Context context) { OkHttpClient.Builder builderOkHttp = new OkHttpClient.Builder(); builderOkHttp.connectTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS); builderOkHttp.readTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS); HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builderOkHttp.networkInterceptors().add(httpLoggingInterceptor);// builderOkHttp.hostnameVerifier(getHostNameVerifier()); builderOkHttp.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException {// PrintLog.e("REST CLIENT", "MY TOKEN :: " + AppPrefs.getInstance(context).getToken());// PrintLog.e("REST CLIENT", "UUID:: " + String.valueOf(deviceUuidFactory.getDeviceUuid())); Request request = chain.request().newBuilder()// .addHeader("Token", AppPrefs.getInstance(context).getToken())// .addHeader("sourceSystemId", AppPrefs.getInstance(context).getSourceSystemId())// .addHeader("buId", AppPrefs.getInstance(context).getBuId()) .addHeader("Content-Type", "application/json")// .addHeader("macId", String.valueOf(deviceUuidFactory.getDeviceUuid())) .build(); return chain.proceed(request); } }); OkHttpClient client = builderOkHttp.build(); Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .create(); retrofit = new Retrofit.Builder() .baseUrl(context.getString(R.string.baseURL)) .addConverterFactory(GsonConverterFactory.create(gson)) .client(client) .build(); API_CLIENT = retrofit.create(EppicoAPI.class); }*/ public static Retrofit retrofit() { return retrofit; } @SuppressWarnings("unchecked") public void makeApiRequest(final Activity activity, Object call, final ApiResponseListener apiResponseListener, final int reqCode,boolean showProgressDialog) { try { if(Utils.getInstance().checkInternetConnection(activity)) { if(showProgressDialog) CustomDialog.getInstance().show(activity,false); final Call<Object> objectCall = (Call<Object>) call; objectCall.enqueue(new Callback<Object>() { @Override public void onResponse(Call<Object> call, retrofit2.Response<Object> response) { CustomDialog.getInstance().hide(); /** Returns true if code() is in the range [200..300). */ if(response.isSuccessful()) { MyLog.v(TAG, "onResponse - Success : " + response.body()); if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiResponse(call, response, reqCode); /* if(apiResponseListener instanceof Fragment) { Fragment fragment = (Fragment) apiResponseListener; if(fragment.isAdded()){ apiResponseListener.onApiResponse(call, response, reqCode); } }*/ } else { if(response.message()!=null && shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, response.message(), reqCode); /*Note: This error log is only for developer. Where developer identify exact API error*/ if (BuildConfig.DEBUG) { APIError error = ErrorUtils.parseError(response); if(error!=null) MyLog.e(TAG, "error message: "+error.message()); } } } @Override public void onFailure(Call<Object> call, Throwable t) { //there is more than just a failing request (like: no internet connection) MyLog.e(TAG, "onFailure - Fail : " + t.getMessage()); CustomDialog.getInstance().hide(); if (t instanceof ConnectException || t instanceof SocketTimeoutException){ //Displaying no network connection error if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, activity.getString(R.string.msgInternetConnectionNotAvailable), reqCode); } else { if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, activity.getString(R.string.msgProblemWithRequest), reqCode); } } }); } else { ToastHelper.getInstance().showToast(activity,activity.getString(R.string.msgInternetConnectionNotAvailable)); } }catch (Exception e) { CustomDialog.getInstance().hide(); e.printStackTrace(); ToastHelper.getInstance().showToast(activity,activity.getString(R.string.msgProblemWithRequest)); } } @SuppressWarnings("unchecked") public void makeApiRequest(final Activity activity,Object call, final ApiResponseListener apiResponseListener, final int reqCode,final int position,boolean showProgressDialog) { try { if(Utils.getInstance().checkInternetConnection(activity)) { if(showProgressDialog) CustomDialog.getInstance().show(activity,false); final Call<Object> objectCall = (Call<Object>) call; objectCall.enqueue(new Callback<Object>() { @Override public void onResponse(Call<Object> call, retrofit2.Response<Object> response) { CustomDialog.getInstance().hide(); /** Returns true if code() is in the range [200..300).*/ if(response.isSuccessful()) { MyLog.v(TAG, "onResponse - Success : " + response.body()); if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiResponse(call,response,reqCode,position); /* if(apiResponseListener instanceof Fragment ) { Fragment fragment = (Fragment) apiResponseListener; if(fragment.isAdded()){ apiResponseListener.onApiResponse(call, response, reqCode); } }*/ } else { if(response.message()!=null && shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, response.message(), reqCode); /*Note: This error log is only for developer. Where developer identify exact API error*/ if (BuildConfig.DEBUG) { APIError error = ErrorUtils.parseError(response); if(error!=null) MyLog.e(TAG, "error message: "+error.message()); } } } @Override public void onFailure(Call<Object> call, Throwable t) { //there is more than just a failing request (like: no internet connection) MyLog.e(TAG, "onFailure - Fail : " + t.getMessage()); CustomDialog.getInstance().hide(); if (t instanceof ConnectException){ //Displaying no network connection error if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, activity.getString(R.string.msgInternetConnectionNotAvailable), reqCode); } else { if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, activity.getString(R.string.msgProblemWithRequest), reqCode); } } }); } else { ToastHelper.getInstance().showToast(activity,activity.getString(R.string.msgInternetConnectionNotAvailable)); } }catch (Exception e) { CustomDialog.getInstance().hide(); e.printStackTrace(); ToastHelper.getInstance().showToast(activity,activity.getString(R.string.msgProblemWithRequest)); } } private boolean shouldCallCallback(ApiResponseListener apiResponseListener) { if(apiResponseListener instanceof Fragment) { Fragment fragment= (Fragment) apiResponseListener; if(fragment.isAdded()) return true; } else if(apiResponseListener instanceof Activity) { Activity activity= (Activity) apiResponseListener; if(!activity.isFinishing()) return true; } return false; } }*model1)SampleModel .java
===================
package com.multiselectList.model;
public class SampleModel { private String name; private String posting; public SampleModel(String name, String posting) { this.name = name; this.posting = posting; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPosting() { return posting; } public void setPosting(String posting) { this.posting = posting; } }*Utility1)AlertDialogHelper.java=============================package com.multiselectList.Utility;
import android.app.Activity; import android.content.Context; import android.content.DialogInterface; import android.os.Looper; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.view.View; import android.widget.Button; /** * Created by Jaison on 04/10/16. */ public class AlertDialogHelper { Context context; AlertDialog alertDialog=null; AlertDialogListener callBack; Activity current_activity; public AlertDialogHelper(Context context) { this.context = context; this.current_activity = (Activity) context; callBack = (AlertDialogListener) context; } /** * Displays the AlertDialog with 3 Action buttons * * you can set cancelable property * * @param title * @param message * @param positive * @param negative * @param neutral * @param from * @param isCancelable */ public void showAlertDialog(String title,String message,String positive,String negative,String neutral,final int from,boolean isCancelable) { final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(current_activity); if(!TextUtils.isEmpty(title)) alertDialogBuilder.setTitle(title); if(!TextUtils.isEmpty(message)) alertDialogBuilder.setMessage(message); if(!TextUtils.isEmpty(positive)) { alertDialogBuilder.setPositiveButton(positive, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { callBack.onPositiveClick(from); alertDialog.dismiss(); } }); } if(!TextUtils.isEmpty(neutral)) { alertDialogBuilder.setNeutralButton(neutral, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { callBack.onNeutralClick(from); alertDialog.dismiss(); } }); } if(!TextUtils.isEmpty(negative)) { alertDialogBuilder.setNegativeButton(negative, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { callBack.onNegativeClick(from); alertDialog.dismiss(); } }); } else { try { new Thread() { @Override public void run() { Looper.prepare(); alertDialog = alertDialogBuilder.create(); alertDialog.show(); Button negative_button = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE); negative_button.setVisibility(View.GONE); Looper.loop(); } }.start(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } alertDialogBuilder.setCancelable(isCancelable); alertDialog = alertDialogBuilder.create(); alertDialog.show(); } /** * Displays the AlertDialog with positive action button only * * you can set cancelable property * * @param title * @param message * @param positive * @param from * @param isCancelable */ public void showAlertDialog(String title,String message,String positive,final int from,boolean isCancelable) { showAlertDialog(title,message,positive,"","",from,isCancelable); } /** * Displays the AlertDialog with positive action button only * * cancelable property is false (Default) * * @param title * @param message * @param positive * @param from */ public void showAlertDialog(String title,String message,String positive,final int from) { showAlertDialog(title,message,positive,"","",from,false); } /** * * Displays the AlertDialog with positive & negative buttons * * you can set cancelable property * * @param title * @param message * @param positive * @param negative * @param from * @param isCancelable */ public void showAlertDialog(String title,String message,String positive,String negative,final int from,boolean isCancelable) { showAlertDialog(title,message,positive,negative,"",from,isCancelable); } /** * * Displays the AlertDialog with positive & negative buttons * * cancelable property is false (Default) * * @param title * @param message * @param positive * @param negative * @param from */ public void showAlertDialog(String title,String message,String positive,String negative,final int from) { showAlertDialog(title,message,positive,negative,"",from,false); } /** * Displays the AlertDialog with 3 Action buttons * * cancelable property is false (Default) * * @param title * @param message * @param positive * @param negative * @param neutral * @param from */ public void showAlertDialog(String title,String message,String positive,String negative,String neutral,final int from) { showAlertDialog(title,message,positive,negative,neutral,from,false); } public interface AlertDialogListener { public void onPositiveClick(int from); public void onNegativeClick(int from); public void onNeutralClick(int from); } } 2)Constants.java====================package com.multiselectList.Utility; /** * Created by manisha on 27/2/17. */ public class Constants { public static final int REQ_CODE_CAPTURE_IMAGE=50,REQ_CODE_GALLERY_IMAGE=51,REQ_CODE_CROP_IMAGE=53; }3)CustomDialog.java=====================package com.multiselectList.Utility; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.support.annotation.NonNull; import com.multiselectList.MyApplication.R; public class CustomDialog { private static CustomDialog customDialog; ProgressDialog progressDialog; public static CustomDialog getInstance() { if (customDialog == null) { customDialog = new CustomDialog(); } return customDialog; } /** * Show progress dialog without message, Before show new dialog it is hide previous showing dialog * @param context Context of activity. * @param cancelable true: Hide out side touch or back press, false: Can not hide out side touch * */ public void show(@NonNull Context context, boolean cancelable) { try { //Before show new dialog hide previous showing dialog hide(); progressDialog = new ProgressDialog(context); progressDialog.setCancelable(cancelable); progressDialog.setMessage(context.getString(R.string.msgLoading)); progressDialog.show(); } catch (Exception e) { e.printStackTrace(); } } /** * Show progress dialog without message, Before show new dialog it is hide previous showing dialog * @param context Context of activity. * @param message Message of dialog. * @param cancelable true: Hide out side touch or back press, false: Can not hide out side touch * */ public void show(@NonNull Context context,@NonNull String message,boolean cancelable) { try { //Before show new dialog hide previous showing dialog hide(); //Set default dialog message "Loading" message=(message!=null && message.trim().length()>0)?message:context.getString(R.string.msgLoading); progressDialog = new ProgressDialog(context); progressDialog.setMessage(message); progressDialog.setCancelable(cancelable); progressDialog.show(); } catch (Exception e) { e.printStackTrace(); } } public void hide() { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } } public boolean isDialogShowing() { if (progressDialog != null) return progressDialog.isShowing(); else return false; } //Show alert dialog public void showMessageDialog(Context context, String title, String message) { if (message != null && message.trim().length() > 0) { AlertDialog.Builder builder = new AlertDialog.Builder(context); //builder.setTitle(title); builder.setCancelable(true); builder.setMessage(message); builder.setPositiveButton(context.getString(R.string.btnOk), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); // create alert dialog AlertDialog alertDialog = builder.create(); // show it alertDialog.show(); } } //Show alert dialog public void showMessageDialog(Context context,String message) { if (message != null && message.trim().length() > 0) { AlertDialog.Builder builder = new AlertDialog.Builder(context); //builder.setTitle(title); builder.setCancelable(true); builder.setMessage(message); builder.setPositiveButton(context.getString(R.string.btnOk), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); // create alert dialog AlertDialog alertDialog = builder.create(); // show it alertDialog.show(); } } }4)PermissionUtil.java=====================/** Copyright 2015 The Android Open Source Project** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/ package com.multiselectList.Utility; import android.Manifest; import android.app.Activity; import android.content.pm.PackageManager; import java.util.ArrayList; /** * Utility class that wraps access to the runtime permissions API in M and provides basic helper * methods. */public class PermissionUtil { static PermissionUtil permissionUtil; public static PermissionUtil getInstance() { if(permissionUtil==null) permissionUtil=new PermissionUtil(); return permissionUtil; } /** * Check that all given permissions have been granted by verifying that each entry in the * given array is of the value {@link PackageManager#PERMISSION_GRANTED}. * * @see Activity#onRequestPermissionsResult(int, String[], int[]) */ public static boolean verifyPermissions(int[] grantResults) { // At least one result must be checked. if(grantResults.length < 1){ return false; } // Verify that each required permission has been granted, otherwise return false. for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } public ArrayList<String> verifyPermissions(String permissions[],int[] grantResults) { // At least one result must be checked. if(permissions!=null && grantResults!=null && permissions.length>0 && grantResults.length>0) { ArrayList<String> listPermissionsNotGranted=new ArrayList<String>(); // Verify that each required permission has been granted, otherwise return false. for (int i=0;i<grantResults.length;i++) { if (grantResults[i] != PackageManager.PERMISSION_GRANTED) { listPermissionsNotGranted.add(permissions[i]); } } return listPermissionsNotGranted; } return null; } public ArrayList<String> getCameraPermissionsList() { ArrayList<String> listPermissionsNeed=new ArrayList<String>(); listPermissionsNeed.add(Manifest.permission.CAMERA); listPermissionsNeed.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); return listPermissionsNeed; } public ArrayList<String> getGalleryPermission() { ArrayList<String> listPermissionsNeed=new ArrayList<String>(); listPermissionsNeed.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); return listPermissionsNeed; } }5)PrefHelper.java=================package com.multiselectList.Utility; import android.content.SharedPreferences.Editor; import android.util.Log; import com.multiselectList.MyApplication; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Map; /** * This class is help to store/get data into preference * */public class PrefHelper { public static void setString(String key, String value) { final Editor editor = MyApplication.myPref.edit(); editor.putString(key, value); apply(editor); } public static String getString(String key,String defaultValue) { return MyApplication.myPref.getString(key, defaultValue); } public static void setInt(String key,int value) { final Editor editor = MyApplication.myPref.edit(); editor.putInt(key, value); apply(editor); } public static int getInt(String key,int defaultValue) { return MyApplication.myPref.getInt(key, defaultValue); } public static boolean getBoolean(String key,boolean defaultValue) { return MyApplication.myPref.getBoolean(key, defaultValue); } public static void setBoolean(String key,boolean value) { final Editor editor = MyApplication.myPref.edit(); editor.putBoolean(key, value); apply(editor); } public static long getLong(String key,long defaultValue) { return MyApplication.myPref.getLong(key, defaultValue); } public static void setLong(String key,long value) { final Editor editor = MyApplication.myPref.edit(); editor.putLong(key, value); apply(editor); } public static double getDouble(String key,double defaultValue) { return Double.longBitsToDouble(MyApplication.myPref.getLong(key, Double.doubleToLongBits(defaultValue))); } public static void setDouble(String key,double value) { final Editor editor = MyApplication.myPref.edit(); editor.putLong(key, Double.doubleToRawLongBits(value)); apply(editor); } public static void deletePreference(String key) { final Editor editor = MyApplication.myPref.edit(); editor.remove(key); apply(editor); } public static void deletePreferences(String[] keys) { if(keys!=null && keys.length>0) { // Editor editor = null; for(int i=0;i<keys.length;i++) { final Editor editor= MyApplication.myPref.edit(); editor.remove(keys[i]); apply(editor); } } } public static void deleteAllPreferences() { final Editor editor = MyApplication.myPref.edit(); editor.clear(); apply(editor); } /*Delete all preference of app except passed argument*/ public static void deletePreferencesExcept(ArrayList<String> keysNotDelete) { //SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(MyApplication.appInstance); Map<String,?> keys = MyApplication.myPref.getAll(); for(Map.Entry<String,?> entry : keys.entrySet()){ Log.d("map values", entry.getKey() + ": " + entry.getValue().toString()); if(!keysNotDelete.contains(entry.getKey())) { final Editor editor= MyApplication.myPref.edit(); editor.remove(entry.getKey()); apply(editor); } } } // Faster pref saving for high performance private static final Method sApplyMethod = findApplyMethod(); private static Method findApplyMethod() { try { final Class<Editor> cls = Editor.class; return cls.getMethod("apply"); } catch (final NoSuchMethodException unused) { // fall through } return null; } public static void apply(final Editor editor) { if (sApplyMethod != null) { try { sApplyMethod.invoke(editor); return; } catch (final InvocationTargetException unused) { // fall through } catch (final IllegalAccessException unused) { // fall through } } editor.commit(); } }6)RecyclerItemClickListener.java===============================package com.multiselectList.Utility; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; /** * Created by Jaison on 21/10/15. */public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener { public static interface OnItemClickListener { public void onItemClick(View view, int position); public void onItemLongClick(View view, int position); } private OnItemClickListener mListener; private GestureDetector mGestureDetector; public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) { mListener = listener; mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return true; } @Override public void onLongPress(MotionEvent e) { View childView = recyclerView.findChildViewUnder(e.getX(), e.getY()); if(childView != null && mListener != null) { mListener.onItemLongClick(childView, recyclerView.getChildPosition(childView)); } } }); } @Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) { View childView = view.findChildViewUnder(e.getX(), e.getY()); if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) { mListener.onItemClick(childView, view.getChildPosition(childView)); } return false; } @Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent){} @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } }7)Utils.java=============package com.multiselectList.Utility; import android.annotation.SuppressLint; import android.content.Context; import android.net.ConnectivityManager; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Manisha on 11/8/2017. */public class Utils { private static Utils utils; public static Utils getInstance() { if (utils == null) utils = new Utils(); return utils; } public boolean isEmailValid(String email) { String expression = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; CharSequence inputStr = email; boolean flag = false; Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); if (matcher.matches()) { flag = true; } return flag; } public boolean checkInternetConnection(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // test for connection if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) { return true; } else { Log.v("", "Internet Connection Not Available"); //Toast.makeText(context, context.getResources().getString(R.string.network_connectivity_not_available), Toast.LENGTH_SHORT).show(); return false; } } @SuppressLint("NewApi") public boolean validateString(String object) { boolean flag = false; if (object != null && !object.equalsIgnoreCase("null") && !object.equalsIgnoreCase("(null)") && !object.isEmpty() && !object.equalsIgnoreCase("(null)")) { flag = true; } return flag; } public void hideKeyboard(View v, Context context) { InputMethodManager mgr = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); mgr.hideSoftInputFromWindow(v.getWindowToken(), 0); } public void showKeyboard(View v, Context context) { /* * InputMethodManager mgr = * (InputMethodManager)context.getSystemService( * Context.INPUT_METHOD_SERVICE); mgr.showSoftInput(v, 0); */ InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.toggleSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0); } /** * Function is used to hide keyboard while user click outside of keyboard on screen. * @param view contains parent view id to get all child views. */ @SuppressLint("ClickableViewAccessibility") public void setupOutSideTouchHideKeyboard(final View view) { if(view==null) return; // Set up touch listener for non-text box views to hide keyboard. if (!(view instanceof EditText)) { view.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { hideKeyboard(view,view.getContext()); return false; } }); } // If a layout container, iterate over children and seed recursion. if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { View innerView = ((ViewGroup) view).getChildAt(i); setupOutSideTouchHideKeyboard(innerView); } } } }MyApplication.java
===================
package com.multiselectList; import android.app.Application; import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.Typeface; import android.preference.PreferenceManager; import com.multiselectList.api.RestClient; import java.util.Locale; /** * Created by manisha on 12/12/16. */ public class MyApplication extends Application{ public static SharedPreferences myPref; public static boolean DISABLE_FRAGMENT_ANIMATION=false; RestClient restClient; // DbHelper dbHelper;// public Typeface fontRobotoRegular,fontRobotoLight; @Override public void onCreate() { super.onCreate(); //Set language Locale locale = new Locale("en"); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); // Initialize preference at application level myPref = PreferenceManager.getDefaultSharedPreferences(this); // Initialize RestClient API class restClient = new RestClient(this); // Initialize DbHelper class and open database// dbHelper = new DbHelper(this);// dbHelper.openDatabase(); } public RestClient getRestClient() { return restClient; } // public DbHelper getDbInstance(){// return dbHelper;// } // /**// * Return typeface// */// public Typeface getTypeFace(String typeFaceName) {// return Typeface.createFromAsset(getAssets(), typeFaceName);// } // @Override// public void onTerminate() {// super.onTerminate();// dbHelper.closeDataBase();// }}
No comments:
Post a Comment