package: fragment
1)BaseFragment.java
====================
========================
1)BaseFragment.java
====================
package com.eppico.fragments; import android.content.res.Resources;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.View;import android.view.animation.AlphaAnimation;import android.view.animation.Animation;import android.view.animation.AnimationUtils;import com.eppico.MyApplication;import com.eppico.R;import com.eppico.activity.HomeActivity;import com.eppico.api.ApiResponseListener;import com.eppico.interfaces.BackPressedEventListener;import com.eppico.interfaces.ClickEventListener; import java.lang.reflect.Field; import retrofit2.Call;import retrofit2.Response; /** * Created by manisha on 12/12/16. */ public class BaseFragment extends Fragment implements BackPressedEventListener,ClickEventListener,ApiResponseListener{ HomeActivity homeActivity; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); homeActivity= (HomeActivity) getActivity(); } /*@Override public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) { //MyLog.v("onCreateAnimator", "enter: " + enter + " transit: " + transit); if (MyApplication.DISABLE_FRAGMENT_ANIMATION) { if(!enter) { Animation anim = null; if(nextAnim!=0) { anim = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_out_left);// anim = AnimationUtils.loadAnimation(getActivity(), nextAnim);// if(anim!=null)// anim.setDuration(0); return anim; } } } return super.onCreateAnimation(transit, enter, nextAnim); }*/ // Arbitrary value; set it to some reasonable default private static final int DEFAULT_CHILD_ANIMATION_DURATION = 250; @Override public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) { final Fragment parent = getParentFragment(); // Apply the workaround only if this is a child fragment, and the parent // is being removed. if (!enter && parent != null && parent.isRemoving()) { /*Note:This is a workaround for the bug where child fragments disappear when the parent is removed (as all children are first removed from the parent) See https://code.google.com/p/android/issues/detail?id=55228*/ Animation doNothingAnim = new AlphaAnimation(1, 1); doNothingAnim.setDuration(getNextAnimationDuration(parent, DEFAULT_CHILD_ANIMATION_DURATION)); return doNothingAnim; } else { if (MyApplication.DISABLE_FRAGMENT_ANIMATION) { if(!enter) { Animation anim = null; if(nextAnim!=0) { //anim = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_out_left); anim = AnimationUtils.loadAnimation(getActivity(), nextAnim); //if(anim!=null) anim.setDuration(0); //return anim; } else { /*Note: If next animation is not there then it will blink layout after remove all fragments. * So to overcome this issue here load any animation and set duration 0*/ anim = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_out_left); anim.setDuration(0); } return anim; } } } return super.onCreateAnimation(transit, enter, nextAnim); } private static long getNextAnimationDuration(Fragment fragment, long defValue) { try { // Attempt to get the resource ID of the next animation that // will be applied to the given fragment. Field nextAnimField = Fragment.class.getDeclaredField("mNextAnim"); nextAnimField.setAccessible(true); int nextAnimResource = nextAnimField.getInt(fragment); if(nextAnimResource>0) { Animation nextAnim = AnimationUtils.loadAnimation(fragment.getActivity(), nextAnimResource); // ...and if it can be loaded, return that animation's duration return (nextAnim == null) ? defValue : nextAnim.getDuration(); } else return defValue; } catch (NoSuchFieldException|IllegalAccessException|Resources.NotFoundException ex) { //Log.w("getNextAnimationDuration", "Unable to load next animation from parent.", ex); ex.printStackTrace(); return defValue; } } @Override public void onBackPressed() { } @Override public void clickEvent(View v) { } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { } @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) { } }2)AddPostFragment.java
========================
package com.eppico.fragments; import android.app.Activity;import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.net.Uri;import android.os.AsyncTask;import android.os.Bundle;import android.os.Environment;import android.os.PowerManager;import android.support.annotation.Nullable;import android.support.design.widget.TextInputLayout;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.EditText;import android.widget.FrameLayout;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import com.bumptech.glide.Glide;import com.bumptech.glide.util.Util;import com.eppico.R;import com.eppico.api.RestClient;import com.eppico.models.AddPostModel;import com.eppico.utility.Constants;import com.eppico.utility.CustomDialog;import com.eppico.utility.FileUtils;import com.eppico.utility.MyLog;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils;import com.facebook.CallbackManager;import com.facebook.FacebookCallback;import com.facebook.FacebookException;import com.facebook.share.Sharer;import com.facebook.share.model.ShareLinkContent;import com.facebook.share.model.ShareOpenGraphAction;import com.facebook.share.model.ShareOpenGraphContent;import com.facebook.share.model.ShareOpenGraphObject;import com.facebook.share.model.SharePhoto;import com.facebook.share.model.SharePhotoContent;import com.facebook.share.model.ShareVideo;import com.facebook.share.model.ShareVideoContent;import com.facebook.share.widget.ShareDialog;import com.netcompss.ffmpeg4android.CommandValidationException;import com.netcompss.ffmpeg4android.GeneralUtils;import com.netcompss.loader.LoadJNI; import java.io.File; import okhttp3.MediaType;import okhttp3.MultipartBody;import okhttp3.RequestBody;import retrofit2.Call;import retrofit2.Response; /** * Created by rushil on 20/12/16. */ public class AddPostFragment extends BaseFragment { // XML Components ImageView imgPostImage,imgPlayIcon; TextView txtUploadImage; EditText edtPostDesc; FrameLayout frameLayoutImage; View mainView; String postMediaPath =""; String spotId; Constants.POST_MEDIA_TYPE postMediaType; // FFMPEG variable private LoadJNI loadJNI; CallbackManager callbackManager; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle=getArguments(); if(bundle!=null) { postMediaPath =bundle.getString(getString(R.string.extraPostMediaPath)); spotId=bundle.getString(getString(R.string.extraSpotId)); postMediaType=Constants.POST_MEDIA_TYPE.values()[bundle.getInt(getString(R.string.extraPostMediaType),Constants.POST_MEDIA_TYPE.IMAGE.ordinal())]; } callbackManager = CallbackManager.Factory.create(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mainView = inflater.inflate(R.layout.fragment_add_post, container, false); init(); return mainView; } public void init() { //getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // Set Sliding Menu disable homeActivity.setSlidingMenuEnable(false); // Hide Keyboard on outside touch Utils.getInstance().setupOutSideTouchHideKeyboard(mainView.findViewById(R.id.parentView)); // Set Title TextView actionBarTitle= (TextView) mainView.findViewById(R.id.actionBarTitle); actionBarTitle.setText(getString(R.string.screenTitleAddPost)); // Setup Actionbar ImageView actionBarMenu= (ImageView) mainView.findViewById(R.id.actionBarMenu); ImageView actionBarRightMenu= (ImageView) mainView.findViewById(R.id.actionBarRightMenu); TextView actionBarRightButton= (TextView) mainView.findViewById(R.id.actionBarRightButton); actionBarMenu.setImageResource(R.mipmap.ic_back); actionBarRightMenu.setVisibility(View.GONE); actionBarRightButton.setVisibility(View.VISIBLE); actionBarRightButton.setText(getString(R.string.actionBarDone)); TextInputLayout inputPostDesc = (TextInputLayout) mainView.findViewById(R.id.inputPostDesc); inputPostDesc.setTypeface(homeActivity.appInstance.fontRobotoLight); imgPostImage= (ImageView) mainView.findViewById(R.id.imgPostImage); imgPlayIcon= (ImageView) mainView.findViewById(R.id.imgPlayIcon); txtUploadImage= (TextView) mainView.findViewById(R.id.txtUploadImage); edtPostDesc= (EditText) mainView.findViewById(R.id.edtPostDesc); frameLayoutImage= (FrameLayout) mainView.findViewById(R.id.frameLayoutImage); //Set height of image int screenWH[]=Utils.getInstance().getScreenWidthHeight(getActivity()); LinearLayout.LayoutParams params= (LinearLayout.LayoutParams) frameLayoutImage.getLayoutParams(); params.height= (int) (screenWH[0] * 0.72); frameLayoutImage.setLayoutParams(params); setPostSelectedImage(postMediaPath); } private void setPostSelectedImage(String postImagePath) { if(postImagePath!=null && postImagePath.length()>0) { imgPostImage.setVisibility(View.VISIBLE); txtUploadImage.setVisibility(View.GONE); Glide.with(getActivity()).load(new File(postImagePath)).into(imgPostImage); if(postMediaType== Constants.POST_MEDIA_TYPE.VIDEO) imgPlayIcon.setVisibility(View.VISIBLE); else imgPlayIcon.setVisibility(View.GONE); } else { imgPostImage.setVisibility(View.GONE); txtUploadImage.setVisibility(View.VISIBLE); } } private void callAddPostApi() { try { if(postMediaPath ==null || postMediaPath.length()<0) CustomDialog.getInstance().showMessageDialog(getActivity(),getString(R.string.selectPostImage)); /*else if(edtPostDesc.getText()==null || edtPostDesc.getText().toString().trim().length()<1) CustomDialog.getInstance().showMessageDialog(getActivity(),getString(R.string.enterPostDescription));*/ else { File file = new File(postMediaPath); if(!file.exists()) { ToastHelper.getInstance().showToast(getActivity(),getString(R.string.msgFileNotFound)); return; } // create RequestBody instance from file RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); // MultipartBody.Part is used to send also the actual file name MultipartBody.Part body = MultipartBody.Part.createFormData("media", file.getName(), requestFile); // add another part within the multipart request RequestBody spotIdReq = RequestBody.create(MediaType.parse("multipart/form-data"), spotId+""); RequestBody userId = RequestBody.create(MediaType.parse("multipart/form-data"), homeActivity.loginModel.getUserId()+""); RequestBody postDesc = RequestBody.create(MediaType.parse("multipart/form-data"), Utils.getInstance().escapeJava(edtPostDesc.getText().toString().trim())); RequestBody mediaType = RequestBody.create(MediaType.parse("multipart/form-data"),postMediaType.ordinal()+""); if(postMediaType== Constants.POST_MEDIA_TYPE.IMAGE) CustomDialog.getInstance().show(getActivity(),getString(R.string.msgImageUploading),false); Call<AddPostModel> objectCall = RestClient.getApiClient().addPost(spotIdReq, /*userId, */postDesc, mediaType,body); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getResources().getInteger(R.integer.reqCodeAddPost), false); } }catch (Exception e) { e.printStackTrace(); } } @Override public void clickEvent(View v) { super.clickEvent(v); switch (v.getId()) { case R.id.actionBarMenu: // Back button onBackPressed(); break; case R.id.actionBarRightButton: if(postMediaType== Constants.POST_MEDIA_TYPE.VIDEO) { new VideoCompressTask(getActivity(),postMediaPath).execute(); } else callAddPostApi();// showFacebookPostAlert(); break; case R.id.imgPlayIcon: File file = new File(postMediaPath); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "video/*"); startActivity(intent); break; } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { try { if (reqCode == getResources().getInteger(R.integer.reqCodeAddPost)) { if (response != null) { //ToastHelper.getInstance().showToast(getActivity(),getString(R.string.postAddedSuccessfully)); //onBackPressed(); showFacebookPostAlert(); } } } catch (Exception e) { e.printStackTrace(); } } private void showFacebookPostAlert() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); //builder.setTitle(title); builder.setCancelable(false); builder.setMessage(getString(R.string.postAddedSuccessfully) + "\n" + getString(R.string.msgPostToFacebook)); builder.setPositiveButton(getString(R.string.btnYes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); sharePostToFacebook(); } }); builder.setNegativeButton(getString(R.string.btnNo), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); onBackPressed(); } }); // create alert dialog AlertDialog alertDialog = builder.create(); // show it alertDialog.show(); } private void sharePostToFacebook() { ShareDialog shareDialog = new ShareDialog(this); if (shareDialog.canShow(SharePhotoContent.class)) { Log.v("ShareDialog.canShow","true"); Uri uri=Uri.fromFile(new File(postMediaPath)); /*// Create an object ShareOpenGraphObject object = new ShareOpenGraphObject.Builder() .putString("og:type", "books.book") .putString("og:title", "A Game of Thrones") .putString("og:description", "In the frozen wastes to the north of Winterfell, sinister and supernatural forces are mustering.") .putString("books:isbn", "0-553-57340-3") .build(); SharePhoto photo = new SharePhoto.Builder() .setImageUrl(uri) .setUserGenerated(true) .build(); // Create an action ShareOpenGraphAction action = new ShareOpenGraphAction.Builder() .setActionType("books.reads") .putObject("book", object) .putPhoto("image", photo) .build(); // Create the content ShareOpenGraphContent content = new ShareOpenGraphContent.Builder() .setPreviewPropertyName("book").setAction(action) .build(); ShareDialog.show(this, content);*/ /*ShareOpenGraphObject object = new ShareOpenGraphObject.Builder() .putString("og:type", "enguru_app:badge") .putString("og:title", "Unlocked Newbie Badge") .putString("og:url","xxxx") .putString("og:image","xxx") .putString("game:points", "10") .putString("fb:app_id", "xxx") .putString("og:description", "We are rocking. Come and Play with us").build(); // Create an action ShareOpenGraphAction action = new ShareOpenGraphAction.Builder() .setActionType("enguru_app:unlocked") .putObject("badge", object).build(); // Create the content ShareOpenGraphContent content = new ShareOpenGraphContent.Builder() .setPreviewPropertyName("badge").setAction(action) .build(); ShareDialog.show(this, content);*/ shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() { @Override public void onSuccess(Sharer.Result result) { MyLog.v("AddPost","onSuccess: " ); onBackPressed(); } @Override public void onCancel() { MyLog.v("AddPost","onCancel: " ); onBackPressed(); } @Override public void onError(FacebookException error) { MyLog.v("AddPost","onError: " ); onBackPressed(); } }); if(postMediaType== Constants.POST_MEDIA_TYPE.IMAGE) { SharePhoto photo = new SharePhoto.Builder() .setImageUrl(uri) .build(); SharePhotoContent photoContent = new SharePhotoContent.Builder() .addPhoto(photo) .build(); shareDialog.show(photoContent, ShareDialog.Mode.AUTOMATIC); // shareDialog.show(photoContent); } else { ShareVideo shareVideo = new ShareVideo.Builder() .setLocalUrl(uri).build(); ShareVideoContent videoContent = new ShareVideoContent.Builder() .setVideo(shareVideo) .build(); shareDialog.show(videoContent, ShareDialog.Mode.AUTOMATIC);// shareDialog.show(videoContent); } } else Log.v("ShareDialog.canShow","false"); } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { if (object != null) ToastHelper.getInstance().showToast(getActivity(), object.toString(), Toast.LENGTH_LONG); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode, resultCode, data); } class VideoCompressTask extends AsyncTask<String,Void,String> { String videoPath; Context context; public VideoCompressTask(Context context,String videoPath) { this.videoPath=videoPath; this.context=context; } @Override protected void onPreExecute() { super.onPreExecute(); CustomDialog.getInstance().show(context,getString(R.string.msgVideoUploading),false); } @Override protected String doInBackground(String... C) { return compressVideo(videoPath); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); // CustomDialog.getInstance().hide(); postMediaPath=result; callAddPostApi(); } } //String workFolder, vkLogPath, demoVideoFolder; private String compressVideo(String videoPath) {//TRANS CODING COMMAND PowerManager powerManager = (PowerManager) getActivity().getSystemService(Activity.POWER_SERVICE); PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "VK_LOCK"); wakeLock.acquire(); String compressedVideoPath= FileUtils.getInstance().getFileUri(getActivity(), FileUtils.MEDIA_TYPE.VIDEO).getPath(); String[] complexCommand = {"ffmpeg", "-y", "-i", videoPath, "-strict", "experimental", "-s", "480x320", "-r", "22", "-vcodec", "mpeg4", "-b", "1048k", "-ab", "48000", "-ac", "2", "-ar", "22050", compressedVideoPath}; String workFolder = getActivity().getApplicationContext().getFilesDir() + "/"; String vkLogPath = workFolder + "vk.log"; String demoVideoFolder = Environment.getExternalStorageDirectory().getAbsolutePath() + "/videokit/"; loadJNI = new LoadJNI(); try { loadJNI.run(complexCommand, workFolder, getActivity()); GeneralUtils.copyFileToFolder(vkLogPath, demoVideoFolder); // Delete Original file after compress new File(videoPath).delete(); } catch (CommandValidationException e) { //VIDEO FILE NOT FOUND EXCEPTION e.printStackTrace(); } catch (Throwable e) { e.printStackTrace(); } finally { if (wakeLock.isHeld()) { wakeLock.release(); } } return compressedVideoPath; } @Override public void onBackPressed() { homeActivity.popFragment(); } }
3)CheckInUserFragment.java
==========================
package com.eppico.fragments; import android.app.Dialog;import android.content.Context;import android.content.Intent;import android.os.Bundle;import android.os.Handler;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.support.v7.widget.DividerItemDecoration;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.view.KeyEvent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.inputmethod.EditorInfo;import android.widget.Button;import android.widget.CheckBox;import android.widget.CompoundButton;import android.widget.EditText;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import com.bumptech.glide.Glide;import com.eppico.R;import com.eppico.activity.HomeActivity;import com.eppico.adapter.AppUserListAdapter;import com.eppico.adapter.CheckInUserAdapter;import com.eppico.api.ApiResponseListener;import com.eppico.api.RestClient;import com.eppico.models.AppUserModel;import com.eppico.models.CheckInUserModel;import com.eppico.models.CreateSpotModel;import com.eppico.models.FollowUserModel;import com.eppico.models.FollowersListModel;import com.eppico.models.InviteFriendModel;import com.eppico.models.InviteSpotListModel;import com.eppico.utility.Constants;import com.eppico.utility.CustomDialog;import com.eppico.utility.MyLog;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils;import com.facebook.CallbackManager;import com.facebook.FacebookCallback;import com.facebook.FacebookException;import com.facebook.share.model.GameRequestContent;import com.facebook.share.widget.GameRequestDialog; import org.json.JSONArray;import org.json.JSONObject; import java.util.ArrayList;import java.util.HashMap; import okhttp3.RequestBody;import retrofit2.Call;import retrofit2.Response; /** * Created by manisha on 13/12/16. */ public class CheckInUserFragment extends BaseFragment { // XML Components private RecyclerView recyclerViewCheckInUser; private TextView txtNoRecords, txtActionBarTitle; private View mainView; private CheckInUserAdapter mCheckInUserAdapter; int totalCount = 0; boolean isLoading = false, isSearch = false; static final int FIRST_PAGE_NO = 0; int pageNo = FIRST_PAGE_NO; int pastVisiblesItems, visibleItemCount, totalItemCount; String searchStr = "",spotId=""; EditText edtSearchUser; private ArrayList<CheckInUserModel.User> listCheckedInUser; private ImageView actionBarMenu, actionBarRightMenu; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mainView = inflater.inflate(R.layout.fragment_checkin_user, container, false); init(); setSearchEvent(); Bundle bundle = getArguments(); if(bundle!=null) { spotId = bundle.getString("CheckInSpotId"); } return mainView; } public void init() { homeActivity.setSlidingMenuEnable(false); // Hide Keyboard on outside touch Utils.getInstance().setupOutSideTouchHideKeyboard(mainView.findViewById(R.id.parentView)); // Set Title txtActionBarTitle = (TextView) mainView.findViewById(R.id.actionBarTitle); txtActionBarTitle.setText(getString(R.string.screenTitleCheckInUser)); // Setup Actionbar actionBarMenu = (ImageView) mainView.findViewById(R.id.actionBarMenu); actionBarMenu.setImageResource(R.mipmap.ic_back); actionBarRightMenu = (ImageView) mainView.findViewById(R.id.actionBarRightMenu); actionBarRightMenu.setVisibility(View.VISIBLE); TextView txtNext = (TextView) mainView.findViewById(R.id.actionBarRightButton); txtNext.setVisibility(View.GONE); edtSearchUser = (EditText) mainView.findViewById(R.id.edtSearch); edtSearchUser.setHint(getString(R.string.hintSearchCheckInUser)); txtNoRecords = (TextView) mainView.findViewById(R.id.txtNoRecords); initNSetRecyclerViewEvents(); new Handler().postDelayed(new Runnable() { @Override public void run() { resetListVariables(); getCheckInUserList(spotId, searchStr, pageNo, true); } }, 400);// mCheckInUserAdapter = new CheckInUserAdapter(getActivity(),alstCheckInUser,totalCount);// recyclerViewCheckInUser.setAdapter(mCheckInUserAdapter); } private void initNSetRecyclerViewEvents() { recyclerViewCheckInUser = (RecyclerView) mainView.findViewById(R.id.recyclerViewCheckInUser); final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); recyclerViewCheckInUser.setLayoutManager(layoutManager); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerViewCheckInUser.getContext(), layoutManager.getOrientation()); // dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this,R.drawable.divider)); recyclerViewCheckInUser.addItemDecoration(dividerItemDecoration); recyclerViewCheckInUser.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); // if (dy > 0) //check for scroll down //{ visibleItemCount = layoutManager.getChildCount(); totalItemCount = layoutManager.getItemCount(); pastVisiblesItems = layoutManager.findFirstVisibleItemPosition(); if (!isLoading && totalCount > listCheckedInUser.size()) { if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) { getCheckInUserList(spotId, searchStr, pageNo, false); } } //} } }); } public void setSearchEvent() { edtSearchUser.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { searchStr = edtSearchUser.getText().toString().trim(); if (searchStr.length() > 0) { Utils.getInstance().hideKeyboard(v, getActivity()); searchStr = edtSearchUser.getText().toString().trim(); if (searchStr.length() > 0) { isSearch = true; //pageNo=0; resetListVariables(); getCheckInUserList(spotId, searchStr, pageNo, true); } } else { //Toast.makeText(getActivity(), getActivity().getString(R.string.searchMessage), Toast.LENGTH_SHORT).show(); ToastHelper.getInstance().showToast(getActivity(), getString(R.string.enterSearchText)); edtSearchUser.requestFocus(); } } return true; } }); } /** * Reset variables before search */ private void resetListVariables() { isLoading = false; pageNo = FIRST_PAGE_NO; totalCount = 0; visibleItemCount = 0; totalItemCount = 0; pastVisiblesItems = 0; listCheckedInUser = new ArrayList<CheckInUserModel.User>(); recyclerViewCheckInUser.setAdapter(null); } private void getCheckInUserList(String spotId, String search, int pageNo, boolean showDialog) { // loginModel.getUserId(); isLoading = true; Call<CheckInUserModel> objectCall = RestClient.getApiClient().checkInUserList(spotId, String.valueOf(pageNo), search); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeCheckInUser), showDialog); } @Override public void clickEvent(View v) { super.clickEvent(v); switch (v.getId()) { case R.id.actionBarRightMenu: //Toggle Search icon if(edtSearchUser.getVisibility() ==View.VISIBLE) { searchStr=""; edtSearchUser.setText(""); edtSearchUser.clearFocus(); edtSearchUser.setVisibility(View.GONE); txtActionBarTitle.setVisibility(View.VISIBLE); actionBarRightMenu.setVisibility(View.VISIBLE); //Set Menu icon actionBarMenu.setImageResource(R.mipmap.ic_back); } else { edtSearchUser.setVisibility(View.VISIBLE); txtActionBarTitle.setVisibility(View.GONE); actionBarRightMenu.setVisibility(View.GONE); //Set back icon actionBarMenu.setImageResource(R.mipmap.ic_back); edtSearchUser.requestFocus(); Utils.getInstance().showKeyboard(edtSearchUser,getActivity()); } /*if (!edtSearch.getText().toString().trim().equalsIgnoreCase("")) { MyLog.e("", "Search:" + edtSearch.getText().toString()); searchInviteList(); Utils.getInstance().hideKeyboard(view, getActivity()); }*/ break; case R.id.actionBarMenu: // Back button onBackPressed(); break; case R.id.actionBarRightButton: break; case R.id.txtFollow: if (v.getTag() != null) { CheckInUserModel.User user = (CheckInUserModel.User) v.getTag(); if(user.getUserIsFollowing()== Constants.FOLLOW_STATUS.FOLLOW.ordinal()) showUnFollowDialog(user); else callUserFollowApi(user); } break; case R.id.imgUser: // Glide Tag Id is nessasary for settag when we use glide CheckInUserModel.User checkInUser = (CheckInUserModel.User) v.getTag(R.string.tagId); Fragment fragment = new MyProfileFragment(); Bundle mBundle = new Bundle(); mBundle.putInt(getString(R.string.extraUserId),checkInUser.getUserId()); fragment.setArguments(mBundle); homeActivity.pushFragments(fragment, true, false, true); break; } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if (reqCode == getResources().getInteger(R.integer.reqCodeCheckInUser)) { isLoading = false; pageNo++; CheckInUserModel checkInUserModel = (CheckInUserModel) response.body(); totalCount = checkInUserModel.getTotalCount(); if (listCheckedInUser == null) listCheckedInUser = new ArrayList<CheckInUserModel.User>(); if (checkInUserModel.getUser() != null) { listCheckedInUser.addAll(checkInUserModel.getUser()); } /*if(pageNo==4) listUsers=null; if(listUsers!=null && listUsers.size()>0) listAppUsers.addAll((ArrayList<AppUserModel.User>) response.body()); else isAllRecordsLoaded=true;*/ bindUserList(listCheckedInUser); } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode, int position) { if (reqCode == getResources().getInteger(R.integer.reqCodeFollowUser)) { FollowUserModel followUserModel= (FollowUserModel) response.body(); CheckInUserModel.User user=listCheckedInUser.get(position); user.setUserIsFollowing(followUserModel.getUserIsFollowing()); listCheckedInUser.set(position,user); bindUserList(listCheckedInUser); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { ToastHelper.getInstance().showToast(getActivity(),object.toString(), Toast.LENGTH_LONG); } private void bindUserList(ArrayList<CheckInUserModel.User> alstCheckInUser) { if (alstCheckInUser != null && alstCheckInUser.size() > 0) { /*if(searchStr!=null && searchStr.length()>0 && pageNoSearch==1) recyclerViewInviteSpot.setAdapter(null);*/ recyclerViewCheckInUser.setVisibility(View.VISIBLE); txtNoRecords.setVisibility(View.GONE); CheckInUserAdapter adapter = (CheckInUserAdapter) recyclerViewCheckInUser.getAdapter(); if (adapter != null && adapter.getItemCount() > 0) { adapter.setListItems(alstCheckInUser); /*if(isAllRecordsLoaded) adapter.notifyItemRemoved(listAppUsers.size());*/ } else { adapter = new CheckInUserAdapter(getActivity(),homeActivity.loginModel.getUserId(), alstCheckInUser, totalCount); recyclerViewCheckInUser.setAdapter(adapter); } } else { recyclerViewCheckInUser.setVisibility(View.GONE); txtNoRecords.setVisibility(View.VISIBLE); } } /**Show UnFollow User confirmation dialog with spot image and spot name*/ private void showUnFollowDialog(final CheckInUserModel.User user) { try { final Dialog dialog = new Dialog(getActivity(), R.style.DialogTheme); dialog.setCancelable(true); LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.dialog_unfollow, null); ImageView imgUser = (ImageView) view.findViewById(R.id.imgUser); TextView txtUserName = (TextView) view.findViewById(R.id.txtUserName); Button btnCancel = (Button) view.findViewById(R.id.btnCancel); Button btnUnfollow = (Button) view.findViewById(R.id.btnUnfollow); // Set font type btnCancel.setTypeface(homeActivity.appInstance.fontRobotoRegular); btnUnfollow.setTypeface(homeActivity.appInstance.fontRobotoRegular); txtUserName.setText(getString(R.string.btnUnfollow) + " " + user.getFirstName() + " " + user.getLastName() + "?"); Glide.with(getActivity()) .load(user.getUserProfile()) .placeholder(R.mipmap.ic_default_user_list) .error(R.mipmap.ic_default_user_list) .into(imgUser); dialog.setContentView(view); /** Set Dialog width match parent */ dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); btnUnfollow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); callUserFollowApi(user); } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); if (dialog.isShowing()) dialog.dismiss(); dialog.show(); } catch (Exception e) { e.printStackTrace(); } } private void callUserFollowApi(CheckInUserModel.User user) { Constants.FOLLOW_STATUS followStatus; // TODO Later Change This condition if(user.getUserIsFollowing()==Constants.FOLLOW_STATUS.FOLLOW.ordinal()) followStatus= Constants.FOLLOW_STATUS.UNFOLLOW; else followStatus= Constants.FOLLOW_STATUS.FOLLOW; Call<FollowUserModel> objectCall = RestClient.getApiClient().followUser(/*homeActivity.loginModel.getUserId() + "",*/ user.getUserId() + "", followStatus.ordinal()+""); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeFollowUser),user.getPosition(), true); } @Override public void onBackPressed() { if (isSearch) { isSearch = false; edtSearchUser.setText(""); resetListVariables(); actionBarRightMenu.performClick(); getCheckInUserList(spotId, searchStr, pageNo, true); } else if (edtSearchUser.getVisibility() == View.VISIBLE) actionBarRightMenu.performClick(); else homeActivity.popFragment(); } }4)CMSPageFragment.java=======================package com.eppico.fragments; import android.annotation.SuppressLint;import android.graphics.Color;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.webkit.WebView;import android.webkit.WebViewClient;import android.widget.ImageView;import android.widget.TextView; import com.eppico.R;import com.eppico.api.RestClient;import com.eppico.models.SearchSpotModel;import com.eppico.utility.Constants;import com.eppico.utility.ToastHelper; import java.util.ArrayList; import retrofit2.Call;import retrofit2.Response; public class CMSPageFragment extends BaseFragment { View mainView; WebView webViewCMSPage; Constants.CMS_PAGE cmsPage= Constants.CMS_PAGE.PRIVACY_POLICY; // Set default privacy policy @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle=getArguments(); if(bundle!=null && bundle.containsKey(getString(R.string.extraCMSPageId))) { cmsPage= Constants.CMS_PAGE.values()[bundle.getInt(getString(R.string.extraCMSPageId))]; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mainView=inflater.inflate(R.layout.fragment_cms_page, container, false); init(); return mainView; } private void init() { //Set Sliding Menu enable homeActivity.setSlidingMenuEnable(false); // Setup Actionbar TextView actionBarTitle= (TextView) mainView.findViewById(R.id.actionBarTitle); ImageView actionBarRightMenu= (ImageView) mainView.findViewById(R.id.actionBarRightMenu); ImageView actionBarMenu= (ImageView) mainView.findViewById(R.id.actionBarMenu); switch (cmsPage) { case PRIVACY_POLICY: actionBarTitle.setText(getString(R.string.screenTitlePrivacyPolicy)); break; case TERMS_CONDITION: actionBarTitle.setText(getString(R.string.screenTitleTermsCondition)); break; } actionBarMenu.setImageResource(R.mipmap.ic_back); actionBarRightMenu.setVisibility(View.INVISIBLE); } @Override public void clickEvent(View v) { super.clickEvent(v); switch (v.getId()) { case R.id.actionBarMenu: // Back button onBackPressed(); break; } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if(reqCode==getResources().getInteger(R.integer.reqCodeSearchSpot)) { } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { ToastHelper.getInstance().showToast(getActivity(),object.toString()); } /** * Set About Us Content into webView */ private void setAboutUsContent(String content) { if (content != null && content.length() > 0) { webViewCMSPage.getSettings().setJavaScriptEnabled(true); webViewCMSPage.clearFormData(); webViewCMSPage.setBackgroundColor(Color.TRANSPARENT); webViewCMSPage.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null); webViewCMSPage.setWebViewClient(new WebViewClient() { @SuppressLint("InlinedApi") @Override public void onPageFinished(WebView view, String url) { } }); webViewCMSPage.loadDataWithBaseURL(null, content, "text/html", "utf-8", null); } } public void getCMSPageContent() { // Call<SearchSpotModel> objectCall = RestClient.getApiClient().searchSpot(searchFragment.searchStrSpot,pageNo);// homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeSearchSpot), showDialog); } @Override public void onBackPressed() { homeActivity.popFragment(); } }5)CreateNewSpotFragment.java===============================package com.eppico.fragments; import android.Manifest;import android.app.Activity;import android.app.Dialog;import android.content.ActivityNotFoundException;import android.content.ComponentName;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager;import android.content.pm.ResolveInfo;import android.database.Cursor;import android.graphics.Bitmap;import android.graphics.Color;import android.graphics.Typeface;import android.graphics.drawable.ColorDrawable;import android.location.Address;import android.location.Geocoder;import android.location.Location;import android.net.Uri;import android.os.AsyncTask;import android.os.Bundle;import android.os.Parcelable;import android.provider.MediaStore;import android.provider.Settings;import android.support.annotation.NonNull;import android.support.annotation.Nullable;import android.support.design.widget.TextInputLayout;import android.support.v4.app.ActivityCompat;import android.support.v4.content.ContextCompat;import android.support.v4.content.CursorLoader;import android.support.v7.app.AlertDialog;import android.support.v7.widget.ListPopupWindow;import android.util.Log;import android.view.Gravity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.WindowManager;import android.view.animation.Animation;import android.view.animation.AnimationUtils;import android.widget.AdapterView;import android.widget.EditText;import android.widget.FrameLayout;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.ListView;import android.widget.PopupWindow;import android.widget.RelativeLayout;import android.widget.TextView;import android.widget.Toast; import com.bumptech.glide.Glide;import com.eppico.MyApplication;import com.eppico.R;import com.eppico.activity.HomeActivity;import com.eppico.activity.ImageCropActivity;import com.eppico.adapter.CategoryAdapter;import com.eppico.api.RestClient;import com.eppico.interfaces.LocationUpdateListener;import com.eppico.models.CategoryModel;import com.eppico.models.CreateSpotModel;import com.eppico.models.LoginModel;import com.eppico.models.RadiusModel;import com.eppico.utility.Constants;import com.eppico.utility.CustomDialog;import com.eppico.utility.FileUtils;import com.eppico.utility.MyLog;import com.eppico.utility.PrefHelper;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils; import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Locale;import java.util.Map; import okhttp3.MediaType;import okhttp3.MultipartBody;import okhttp3.RequestBody;import retrofit2.Call;import retrofit2.Response; /** * Created by Admin on 12/12/2016. */ public class CreateNewSpotFragment extends BaseFragment /*implements View.OnClickListener, ApiResponseListener*/ { private View mview; private ImageView img_background, imgEdit; private TextView txtUploadimage, txtRadius, txtCategory, txtActionBarTitle; private EditText edtSpotName, edtSpotDesc; FrameLayout frameLayoutImage; /* public static final int RESULT_LOAD_CAMERA = 1; public static final int RESULT_LOAD_GALLERY = 2;*/ private boolean isActivityPaused; private String croppedImagePath, strAddress; // private RelativeLayout rlCategory, rlRadius; private TextInputLayout inputLayout_Spotname, inputLayout_Description; HomeActivity homeActivity; private ArrayList<RadiusModel> alstRadiusModels; private ArrayList<CategoryModel> alstCategoryModels; RestClient restClient; LoginModel loginModel; private Geocoder geocoder; private List<Address> addresses; int selectedRadius, selectedCategoryId = -1, selectedRadiusId = -1; Uri outputFileUri; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); String mLoginUserData = PrefHelper.getString(getString(R.string.prefLoginUserData), ""); if (mLoginUserData.length() > 0) { loginModel = (LoginModel) LoginModel.toModelClass(mLoginUserData, LoginModel.class); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mview = inflater.inflate(R.layout.fragment_createnewspot, container, false); ImageView actionBarMenu = (ImageView) mview.findViewById(R.id.actionBarMenu); ImageView actionBarRightMenu = (ImageView) mview.findViewById(R.id.actionBarRightMenu); actionBarRightMenu.setVisibility(View.GONE); TextView txtNext = (TextView) mview.findViewById(R.id.actionBarRightButton); txtNext.setVisibility(View.VISIBLE); txtActionBarTitle = (TextView) mview.findViewById(R.id.actionBarTitle); txtActionBarTitle.setText(getResources().getString(R.string.screenTitleCreateNewSpot)); homeActivity = (HomeActivity) getActivity(); actionBarMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { homeActivity.toggleSlidingMenu(); } }); init(); //setupClickListener(); return mview; } private void init() { // Set Sliding Menu enable homeActivity.setSlidingMenuEnable(true); homeActivity.setSelectedPositionInSlidingMenu(2); // Hide Keyboard on outside touch Utils.getInstance().setupOutSideTouchHideKeyboard(mview.findViewById(R.id.my_toolbar)); Utils.getInstance().setupOutSideTouchHideKeyboard(mview.findViewById(R.id.txtCategory)); Utils.getInstance().setupOutSideTouchHideKeyboard(mview.findViewById(R.id.txtRadius)); MyApplication myApplication = (MyApplication) getActivity().getApplication(); restClient = myApplication.getRestClient(); isActivityPaused = false; img_background = (ImageView) mview.findViewById(R.id.img_background); imgEdit = (ImageView) mview.findViewById(R.id.imgEdit); txtUploadimage = (TextView) mview.findViewById(R.id.txt_uploadimage); edtSpotName = (EditText) mview.findViewById(R.id.et_spotname); edtSpotDesc = (EditText) mview.findViewById(R.id.et_description); txtUploadimage = (TextView) mview.findViewById(R.id.txt_uploadimage); /*rlCategory = (RelativeLayout) mview.findViewById(R.id.rlCategory); rlRadius = (RelativeLayout) mview.findViewById(R.id.rlRadius);*/ txtCategory = (TextView) mview.findViewById(R.id.txtCategory); txtRadius = (TextView) mview.findViewById(R.id.txtRadius); frameLayoutImage = (FrameLayout) mview.findViewById(R.id.frameLayoutImage); inputLayout_Spotname = (TextInputLayout) mview.findViewById(R.id.input_lyt_spotname); inputLayout_Description = (TextInputLayout) mview.findViewById(R.id.input_lyt_description); inputLayout_Spotname.setTypeface(homeActivity.appInstance.fontRobotoLight); inputLayout_Description.setTypeface(homeActivity.appInstance.fontRobotoLight); ///Set height of image int screenWH[] = Utils.getInstance().getScreenWidthHeight(getActivity()); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) frameLayoutImage.getLayoutParams(); params.height = (int) (screenWH[0] * 0.50); frameLayoutImage.setLayoutParams(params); new GetLocationAsync((PrefHelper.getDouble(getString(R.string.prefUserLatitude), 0)), (PrefHelper.getDouble(getString(R.string.prefUserLongitude), 0))).execute(); getSpotRadius(); getCategory(); managePrevSelectedData(); } private void managePrevSelectedData() { if (alstCategoryModels != null && alstCategoryModels.size() > 0 && selectedCategoryId != -1) { for (int i = 0; i < alstCategoryModels.size(); i++) { if (alstCategoryModels.get(i).getCatId() == selectedCategoryId) { txtCategory.setText(alstCategoryModels.get(i).getCatName()); txtCategory.setTypeface(homeActivity.appInstance.fontRobotoRegular); } } } if (alstRadiusModels != null && alstRadiusModels.size() > 0 && selectedRadiusId != -1) { for (int i = 0; i < alstRadiusModels.size(); i++) { if (alstRadiusModels.get(i).getRadiusID() == selectedRadiusId) { txtRadius.setText(alstRadiusModels.get(i).getLength() + ""); txtRadius.setTypeface(homeActivity.appInstance.fontRobotoRegular); } } } //Set Spot image setSpotImage(croppedImagePath); } private void getCategory() { if (alstCategoryModels == null || alstCategoryModels.size() <= 0) { Call<List<CategoryModel>> objectCall = RestClient.getApiClient().getCategory(); restClient.makeApiRequest(getActivity(), objectCall, this, getResources().getInteger(R.integer.reqCodeCategory), true); } } private void getSpotRadius() { if (alstRadiusModels == null || alstRadiusModels.size() <= 0) { Call<List<RadiusModel>> objectCall = restClient.getApiClient().getSpotRadius(); restClient.makeApiRequest(getActivity(), objectCall, this, getResources().getInteger(R.integer.reqCodeRadius), true); } } public void clickEvent(View view) { switch (view.getId()) { case R.id.img_background: //dialogChoosePicture(); if (checkAndRequestPermissions()) { try { //Uri outputFileUri = getCaptureImageOutputUri(); outputFileUri = FileUtils.getInstance().getFileUri(getActivity(), FileUtils.MEDIA_TYPE.PICTURE); //Constants.IMAGE_URI = outputFileUri; Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); /*captureIntent.putExtra("uri", outputFileUri); captureIntent.putExtra("return-data", true); if (outputFileUri != null) { captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); }*/ startActivityForResult(captureIntent, Constants.REQ_CODE_CAPTURE_IMAGE); } catch (ActivityNotFoundException e) { e.getMessage(); } } break; case R.id.txtCategory: showCatRadiusPopup(alstCategoryModels, Constants.POPUP_TYPE.CATEGORY); /*if (Utils.getInstance().checkInternetConnection(getActivity())) { if (alstCategoryModels != null && alstCategoryModels.size() > 0) { showCategoryPopup(); } else { CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.no_category_available)); } } else { ToastHelper.getInstance().showToast(getActivity(), getActivity().getString(R.string.msgInternetConnectionNotAvailable)); }*/ break; case R.id.txtRadius: showCatRadiusPopup(alstRadiusModels, Constants.POPUP_TYPE.RADIUS); /*if (Utils.getInstance().checkInternetConnection(getActivity())) { if (alstRadiusModels != null && alstRadiusModels.size() > 0) { showRadiusPopup(); } else { CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.no_redius_available)); } } else { ToastHelper.getInstance().showToast(getActivity(), getActivity().getString(R.string.msgInternetConnectionNotAvailable)); }*/ break; case R.id.actionBarRightButton: if (FieldValidation()) { homeActivity.getCurrentLocation(new LocationUpdateListener() { @Override public void onLocationUpdate(Location location) { createNewSpot(location); } @Override public void onLocationPermissionDeny() { CustomDialog.getInstance().showMessageDialog(getActivity(), getString(R.string.msgEnableLocationPermissionToCreateNewSpot)); } @Override public void onGPSRequestDeny() { Toast.makeText(getActivity(), getString(R.string.msgEnableGPSToCreateNewSpot), Toast.LENGTH_LONG).show();// CustomDialog.getInstance().showMessageDialog(getActivity(),getString(R.string.msgEnableGPSToCreateNewSpot)); } }); } break; default: break; } } @Override public void onResume() { super.onResume(); isActivityPaused = false; /*if (Constants.CROPPED_BITMAP != null) { if (Constants.BTN_OK_CLICKED) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); Constants.CROPPED_BITMAP.compress(Bitmap.CompressFormat.JPEG, 100, bytes); txtUploadimage.setVisibility(View.INVISIBLE); // mImgArticle.setBackground(ContextCompat.getDrawable(getApplicationContext(), android.R.color.transparent)); img_background.setImageBitmap(Constants.CROPPED_BITMAP); mImgPath = getBitmapPath(); } }*/// else {// CustomDialog.getInstance().showMessageDialog(getActivity(),"",getResources().getString(R.string.unable_to_load_image));// } } @Override public void onPause() { super.onPause(); isActivityPaused = true; } /*public void showRadiusPopup() { // initialize a pop up window type if (alstRadiusModels == null || alstRadiusModels.size() <= 0) return; final PopupWindow popupWindow = new PopupWindow(getActivity());// Drawable transparentDrawable = new ColorDrawable(Color.TRANSPARENT);// popupWindow.setBackgroundDrawable(transparentDrawable); // the drop down list is a list view ListView listViewRadius = new ListView(getActivity()); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT ); params.setMargins(30, 0, 30, 0); //left,top,right,bottom listViewRadius.setBackgroundColor(getResources().getColor(R.color.white)); CategoryAdapter mCategoryAdapter = new CategoryAdapter(getActivity(), 0, null, alstRadiusModels); listViewRadius.setAdapter(mCategoryAdapter); // set the item click listener listViewRadius.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { // add some animation when a list item was clicked // dismiss the pop up popupWindow.dismiss(); ((TextView) view).setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); // get the text and set it as the button text String selectedItemText = ((TextView) view).getText().toString(); txtRadius.setText(selectedItemText); txtRadius.setTypeface(homeActivity.appInstance.fontRobotoRegular); // txtRadius.setTag(alstRadiusModels.get(i).getRadiusID()); selectedRadius = Integer.parseInt(alstRadiusModels.get(i).getLength()); selectedRadiusId = alstRadiusModels.get(i).getRadiusID(); } }); // some other visual settings popupWindow.setFocusable(true); int screenWH[]=Utils.getInstance().getScreenWidthHeight(getActivity()); popupWindow.setWidth(screenWH[0] - 60); popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); //popupWindow.showAtLocation(listViewRadius, Gravity.CENTER, 0, 0); // set the list view as pop up window content popupWindow.setContentView(listViewRadius); popupWindow.showAsDropDown(txtRadius, 0, 0); }*/ /*public void showCategoryPopup() { // initialize a pop up window type if (alstCategoryModels == null || alstCategoryModels.size() <= 0) return; final PopupWindow popupWindow = new PopupWindow(getActivity());// Drawable transparentDrawable = new ColorDrawable(Color.TRANSPARENT);// popupWindow.setBackgroundDrawable(transparentDrawable); // the drop down list is a list view View view = LayoutInflater.from(getActivity()).inflate(R.layout.popup_cat_radius, null, false); ListView listView = (ListView) view.findViewById(R.id.listView);// ListView listViewCat = new ListView(getActivity()); *//*LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT ); //params.setMargins(30, 0, 30, 0); //left,top,right,bottom listView.setLayoutParams(params);*//* CategoryAdapter mCategoryAdapter = new CategoryAdapter(getActivity(), 1, alstCategoryModels, null); // set our adapter and pass our pop up window contents listView.setAdapter(mCategoryAdapter); // set the item click listener listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { // add some animation when a list item was clicked // dismiss the pop up popupWindow.dismiss(); // get the text and set it as the button text String selectedItemText = ((TextView) view).getText().toString(); txtCategory.setText(selectedItemText); txtCategory.setTypeface(homeActivity.appInstance.fontRobotoRegular); selectedCategoryId = alstCategoryModels.get(i).getCatId();// txtCategory.setTag(alstCategoryModels.get(i).getCatId()); } }); // some other visual settings popupWindow.setFocusable(true); int mScreenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth(); popupWindow.setWidth(mScreenWidth - 60); popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); //popupWindow.showAtLocation(listViewCat, Gravity.CENTER, 0, 0); // set the list view as pop up window content popupWindow.setContentView(view); popupWindow.showAsDropDown(txtCategory, 0, 0); }*/ /**Show Category or Radius PopupView.*/ public void showCatRadiusPopup(ArrayList<?> listItems,final Constants.POPUP_TYPE popupType) { if (Utils.getInstance().checkInternetConnection(getActivity())) { //If ArrayList is null or empty show appropriate message if(listItems == null || listItems.size() <= 0) { switch (popupType) { case CATEGORY: CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.no_category_available)); return; case RADIUS: CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.no_redius_available)); return; } } } else { ToastHelper.getInstance().showToast(getActivity(), getActivity().getString(R.string.msgInternetConnectionNotAvailable)); return; } final PopupWindow popupWindow = new PopupWindow(getActivity());// Drawable transparentDrawable = new ColorDrawable(Color.TRANSPARENT);// popupWindow.setBackgroundDrawable(transparentDrawable); // the drop down list is a list view View view = LayoutInflater.from(getActivity()).inflate(R.layout.popup_cat_radius, null, false); ListView listView = (ListView) view.findViewById(R.id.listView); CategoryAdapter mCategoryAdapter = new CategoryAdapter(getActivity(), popupType, listItems); listView.setAdapter(mCategoryAdapter); // set the item click listener listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { // dismiss the pop up popupWindow.dismiss(); // get the text and set it as the button text String selectedItemText = ((TextView) view).getText().toString(); switch (popupType) { case CATEGORY: txtCategory.setText(selectedItemText); txtCategory.setTypeface(homeActivity.appInstance.fontRobotoRegular); selectedCategoryId = alstCategoryModels.get(i).getCatId(); break; case RADIUS: txtRadius.setText(selectedItemText); txtRadius.setTypeface(homeActivity.appInstance.fontRobotoRegular); selectedRadius = Integer.parseInt(alstRadiusModels.get(i).getLength()); selectedRadiusId = alstRadiusModels.get(i).getRadiusID(); break; } } }); popupWindow.setFocusable(true); int mScreenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth(); popupWindow.setWidth(mScreenWidth - 60); popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT); //popupWindow.showAtLocation(listViewCat, Gravity.CENTER, 0, 0); // set the list view as pop up window content popupWindow.setContentView(view); popupWindow.showAsDropDown(txtCategory, 0, 0); } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if (reqCode == getResources().getInteger(R.integer.reqCodeCategory)) { alstCategoryModels = new ArrayList<>(); alstCategoryModels.addAll((ArrayList<CategoryModel>) response.body()); //getSpotRadius(); } else if (reqCode == getResources().getInteger(R.integer.reqCodeRadius)) { alstRadiusModels = new ArrayList<>(); alstRadiusModels.addAll((ArrayList<RadiusModel>) response.body()); } else if (reqCode == getResources().getInteger(R.integer.reqCodeCreateSpot)) { //CustomDialog.getInstance().showMessageDialog(getActivity(), "", getResources().getString(R.string.spot_created_successfully)); CreateSpotModel createSpotModel = (CreateSpotModel) response.body(); createSpotModel.setRadius(selectedRadius); Bundle bundle = new Bundle(); bundle.putSerializable(getString(R.string.extraCreateSpotObj), createSpotModel); MapCreateNewSpotFragment mapCreateNewSpotFragment = new MapCreateNewSpotFragment(); mapCreateNewSpotFragment.setArguments(bundle); homeActivity.pushFragments(mapCreateNewSpotFragment, true, false, true); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { ToastHelper.getInstance().showToast(getActivity(), object.toString()); } public class CatDropdownOnItemClickListener implements AdapterView.OnItemClickListener { String TAG = "DogsDropdownOnItemClickListener.java"; @Override public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) { } } public Uri getImageUri(Context inContext, Bitmap inImage) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Article", null); return Uri.parse(path); } public String getPath(Uri uri) { String[] proj = {MediaStore.Images.Media.DATA}; CursorLoader cursorLoader = new CursorLoader(getActivity(), uri, proj, null, null, null); Cursor cursor = cursorLoader.loadInBackground(); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } public void dialogChoosePicture() { final Dialog dialog = new Dialog(getActivity(), 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.btnLibrary); btnGallery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if (checkAndRequestPermissions()) { Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, Constants.REQ_CODE_GALLERY_IMAGE); } } }); TextView btnCamera = (TextView) dialog.findViewById(R.id.btnCamera); btnCamera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if (checkAndRequestPermissions()) { try { //Uri outputFileUri = getCaptureImageOutputUri(); outputFileUri = FileUtils.getInstance().getFileUri(getActivity(), FileUtils.MEDIA_TYPE.PICTURE); //Constants.IMAGE_URI = outputFileUri; Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); /*captureIntent.putExtra("uri", outputFileUri); captureIntent.putExtra("return-data", true); if (outputFileUri != null) { captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); }*/ startActivityForResult(captureIntent, Constants.REQ_CODE_CAPTURE_IMAGE); } catch (ActivityNotFoundException e) { e.getMessage(); } } } }); TextView btnCancel = (TextView) dialog.findViewById(R.id.btnCancel); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == Constants.REQ_CODE_CAPTURE_IMAGE && resultCode == Activity.RESULT_OK) { /*Constants.IMAGE_URI = getPickImageResultUri(data); Intent intent = new Intent(getActivity(), ImageCropActivity.class); intent.putExtra("xratio", 50); intent.putExtra("yratio", 30); startActivity(intent);*/ Intent intent = new Intent(getActivity(), ImageCropActivity.class); intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 50); intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 30); intent.putExtra(ImageCropActivity.EXTRA_IMAGE_PATH, outputFileUri.getPath()); 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[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = getActivity().getContentResolver().query(selectedImageUri, projection, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(projection[0]); String picturePath = cursor.getString(columnIndex); // returns null cursor.close();*/ String picturePath = Utils.getInstance().getRealPathFromURI(getActivity(), selectedImageUri); //Copy Original File to app media folder String copiedFilepath = FileUtils.getInstance().copyFile(picturePath, FileUtils.getInstance().getFilePath(getActivity(), FileUtils.MEDIA_TYPE.PICTURE)); Intent intent = new Intent(getActivity(), ImageCropActivity.class); intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 50); intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 30); intent.putExtra(ImageCropActivity.EXTRA_IMAGE_PATH, copiedFilepath); 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) { croppedImagePath = bundle.getString(ImageCropActivity.EXTRA_IMAGE_PATH); MyLog.v("Cropped Image", "Cropped Image Path: " + croppedImagePath); setSpotImage(croppedImagePath); } } } private void setSpotImage(String spotImage) { if (croppedImagePath != null && croppedImagePath.length() > 0) { txtUploadimage.setVisibility(View.GONE); imgEdit.setVisibility(View.VISIBLE); Glide.with(getActivity()).load(new File(spotImage)).into(img_background); } else { txtUploadimage.setVisibility(View.VISIBLE); imgEdit.setVisibility(View.GONE); } } public Uri getPickImageResultUri(Intent data) { boolean isFromCamera = (data == null || data.getData() == null || data.getData().equals(Uri.fromFile(new File(getActivity().getExternalCacheDir().getPath(), "pro_pic" + ".jpeg")))); /*boolean isCamera = true; if (data != null) { String action = data.getAction(); isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE); }*/ return isFromCamera ? getCaptureImageOutputUri() : data.getData(); } /** * Get URI to image received from capture by camera. */ private Uri getCaptureImageOutputUri() { Uri outputFileUri = null; File getImage = getActivity().getExternalCacheDir(); if (getImage != null) { outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pro_pic.jpeg")); } return outputFileUri; } //===================================== CHANGE PROFILE IMAGE ================================================= /** * Create a chooser intent to select the source to get image from.<br/> * The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).<br/> * All possible sources are added to the intent chooser. */ public Intent getPickImageChooserIntent() { // Determine Uri of camera image to save. Uri outputFileUri = getCaptureImageOutputUri(); List<Intent> allIntents = new ArrayList<>(); PackageManager packageManager = getActivity().getPackageManager(); // collect all camera intents Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0); for (ResolveInfo res : listCam) { Intent intent = new Intent(captureIntent); intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); intent.setPackage(res.activityInfo.packageName); if (outputFileUri != null) { intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); } allIntents.add(intent); } // collect all gallery intents Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT); galleryIntent.setType("image/*"); List<ResolveInfo> listGallery = packageManager.queryIntentActivities(galleryIntent, 0); for (ResolveInfo res : listGallery) { Intent intent = new Intent(galleryIntent); intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); intent.setPackage(res.activityInfo.packageName); allIntents.add(intent); } // the main intent is the last in the list (fucking android) so pickup the useless one Intent mainIntent = allIntents.get(allIntents.size() - 1); for (Intent intent : allIntents) { if (intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) { mainIntent = intent; break; } } allIntents.remove(mainIntent); // Create a chooser from the main intent Intent chooserIntent = Intent.createChooser(mainIntent, "Select source"); // Add all other intents chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()])); return chooserIntent; } //============================== CHECK FOR RUNTIME PERMISSIONS MARSHMALLOW AND ABOVE ================================================ private void showPermissionDialog(String message, String posBtnTxt, String negBtnTxt, DialogInterface.OnClickListener okListener) { new AlertDialog.Builder(getActivity()) .setMessage(message) .setPositiveButton(posBtnTxt, okListener) .setNegativeButton(negBtnTxt, null) .create() .show(); } private boolean checkAndRequestPermissions() { int permissionSendMessage = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA); int locationPermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE); List<String> listPermissionsNeeded = new ArrayList<>(); if (locationPermission != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); } if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.CAMERA); } if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(getActivity(), listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), Constants.MY_PERMISSIONS_REQUEST_URI); return false; } return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) { switch (requestCode) { case Constants.MY_PERMISSIONS_REQUEST_URI: { Map<String, Integer> perms = new HashMap<>(); perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED); perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED); // Fill with actual results from user if (grantResults.length > 0) { for (int i = 0; i < permissions.length; i++) perms.put(permissions[i], grantResults[i]); // Check for both permissions if (perms.get(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED && perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // process the normal flow //else any one or both the permissions are not granted startActivityForResult(getPickImageChooserIntent(), 200); } else { //permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission// // shouldShowRequestPermissionRationale will return true //show the dialog or snackbar saying its necessary and try again otherwise proceed with setup. if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) { showPermissionDialog("App requires permissions for camera and storage to access media files", "Ok", "Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.e("permission dialog", "request perm settings which was clicked : " + which); checkAndRequestPermissions(); } }); } //permission is denied (and never ask again is checked) //shouldShowRequestPermissionRationale will return false else { showPermissionDialog("App requires permission for camera and storage to access media files", "Go to settings", "Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Log.e("permission dialog", "request perm settings which was clicked : " + which); Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null); intent.setData(uri); startActivityForResult(intent, Constants.REQUEST_PERMISSION_SETTING); } }); //proceed with logic by disabling the related features or quit the app. } } } } } } /** * Call create new spot webservice */ private void createNewSpot(Location location) { try { if (loginModel != null) { File file = new File(croppedImagePath); // create RequestBody instance from file RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); // MultipartBody.Part is used to send also the actual file name MultipartBody.Part body = MultipartBody.Part.createFormData("spotImage", file.getName(), requestFile); // add another part within the multipart request RequestBody catId = RequestBody.create(MediaType.parse("multipart/form-data"), "" + selectedCategoryId); RequestBody userId = RequestBody.create(MediaType.parse("multipart/form-data"), "" + loginModel.getUserId()); RequestBody radiusId = RequestBody.create(MediaType.parse("multipart/form-data"), "" + selectedRadiusId); RequestBody spotName = RequestBody.create(MediaType.parse("multipart/form-data"), Utils.getInstance().escapeJava(edtSpotName.getText().toString())); RequestBody spotDetailDesc = RequestBody.create(MediaType.parse("multipart/form-data"), Utils.getInstance().escapeJava(edtSpotDesc.getText().toString())); RequestBody spotLocation = RequestBody.create(MediaType.parse("multipart/form-data"), strAddress != null ? strAddress : ""); RequestBody spotLatLong = RequestBody.create(MediaType.parse("multipart/form-data"), location.getLatitude() + "," + location.getLongitude());// RequestBody spotLatLong = RequestBody.create(MediaType.parse("multipart/form-data"), (PrefHelper.getDouble(getString(R.string.prefUserLatitude), 0)) + "," + (PrefHelper.getDouble(getString(R.string.prefUserLongitude), 0)) + ""); Call<CreateSpotModel> objectCall = RestClient.getApiClient().createSpot(catId, /*userId,*/ radiusId, spotName, spotDetailDesc, spotLocation, spotLatLong, body); restClient.makeApiRequest(getActivity(), objectCall, this, getResources().getInteger(R.integer.reqCodeCreateSpot), true); } } catch (Exception e) { e.printStackTrace(); } } // Get Address using geocoder private class GetLocationAsync extends AsyncTask<String, Void, String> { // boolean duplicateResponse; double x, y; StringBuilder str; public GetLocationAsync(double latitude, double longitude) { x = latitude; y = longitude; } @Override protected void onPreExecute() { // txtLocation.setText(" Getting location "); } @Override protected String doInBackground(String... params) { try { geocoder = new Geocoder(getActivity(), Locale.ENGLISH); addresses = geocoder.getFromLocation(x, y, 1); str = new StringBuilder(); if (geocoder.isPresent() && addresses != null && addresses.size() > 0) { Address returnAddress = addresses.get(0); String localityString = returnAddress.getLocality(); String city = returnAddress.getCountryName(); String region_code = returnAddress.getCountryCode(); String zipcode = returnAddress.getPostalCode(); str.append(localityString + ""); str.append(city + "" + region_code + ""); str.append(zipcode + ""); } else { } } catch (IOException e) { Log.e("tag", e.getMessage()); } return null; } @Override protected void onPostExecute(String result) { try { if (addresses != null && addresses.size() > 0) { Log.e("", "Address" + strAddress); strAddress = addresses.get(0).getAddressLine(0) + ", " + addresses.get(0).getAddressLine(1) + ", " + addresses.get(0).getAddressLine(2) + ", " + addresses.get(0).getAddressLine(3); if (!Utils.validateString(strAddress)) { strAddress = +x + "," + y; } } PrefHelper.setString(getString(R.string.prefAddress), strAddress); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onProgressUpdate(Void... values) { } } public boolean FieldValidation() { boolean flag = true; if (!Utils.validateString(croppedImagePath)) { flag = false; CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.app_name), getResources().getString(R.string.please_choose_picture)); } else if (!Utils.validateString(edtSpotName.getText().toString())) { flag = false; CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.app_name), getResources().getString(R.string.please_enter_spot_name)); } else if (selectedCategoryId == -1) { flag = false; CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.app_name), getResources().getString(R.string.please_select_category)); } else if (selectedRadiusId == -1) { flag = false; CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.app_name), getResources().getString(R.string.please_select_radius)); } else if (!Utils.validateString(edtSpotDesc.getText().toString())) { flag = false; CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.app_name), getResources().getString(R.string.please_enter_spot_desc)); } return flag; } @Override public void onBackPressed() { homeActivity.popFragment(); } }6)EditProfileFragment.java============================package com.eppico.fragments; import android.Manifest;import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;import android.content.ActivityNotFoundException;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager;import android.database.Cursor;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.Nullable;import android.support.design.widget.TextInputLayout;import android.support.v4.app.ActivityCompat;import android.support.v4.content.ContextCompat;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.EditText;import android.widget.ImageView;import android.widget.TextView; import com.bumptech.glide.Glide;import com.bumptech.glide.load.resource.drawable.GlideDrawable;import com.bumptech.glide.request.RequestListener;import com.bumptech.glide.request.target.Target;import com.eppico.MyApplication;import com.eppico.R;import com.eppico.activity.HomeActivity;import com.eppico.activity.ImageCropActivity;import com.eppico.api.RestClient;import com.eppico.models.EditProfileModel;import com.eppico.models.LoginModel;import com.eppico.models.ReportAbuseModel;import com.eppico.utility.Constants;import com.eppico.utility.CustomDialog;import com.eppico.utility.FileUtils;import com.eppico.utility.MyLog;import com.eppico.utility.PrefHelper;import com.eppico.utility.Utils;import com.eppico.widgets.ShapedImageView; import java.io.File;import java.util.ArrayList;import java.util.List; import okhttp3.MediaType;import okhttp3.MultipartBody;import okhttp3.RequestBody;import retrofit2.Call;import retrofit2.Response; public class EditProfileFragment extends BaseFragment { //XML Components ShapedImageView imgUser, imgDefault; EditText edtFirstName, edtLastName; Uri outputFileUri; View mainView; ImageView imageButton; private String croppedImagePath; LoginModel loginModel; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); String mLoginUserData = PrefHelper.getString(getString(R.string.prefLoginUserData), ""); MyApplication myApplication = (MyApplication) getActivity().getApplication(); if (mLoginUserData.length() > 0) { loginModel = (LoginModel) LoginModel.toModelClass(mLoginUserData, LoginModel.class); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mainView = inflater.inflate(R.layout.fragment_edit_profile, container, false); init(); return mainView; } private void init() { //Set Sliding Menu disable homeActivity.setSlidingMenuEnable(false); // Hide Keyboard on outside touch Utils.getInstance().setupOutSideTouchHideKeyboard(mainView.findViewById(R.id.parentView)); imgUser = (ShapedImageView) mainView.findViewById(R.id.imgUser);// imgDefault = (ShapedImageView) mainView.findViewById(R.id.imgDefault); edtFirstName = (EditText) mainView.findViewById(R.id.edtFirstName); TextInputLayout inputFirstName = (TextInputLayout) mainView.findViewById(R.id.inputfirstName); inputFirstName.setTypeface(homeActivity.appInstance.fontRobotoLight); edtLastName = (EditText) mainView.findViewById(R.id.edtLastName); TextInputLayout inputLastName = (TextInputLayout) mainView.findViewById(R.id.inputLastName); inputLastName.setTypeface(homeActivity.appInstance.fontRobotoLight); if (Utils.validateString(loginModel.getFirstName())) { edtFirstName.setText(Utils.getInstance().unescapeJava(loginModel.getFirstName())); } if (Utils.validateString(loginModel.getLastName())) { edtLastName.setText(Utils.getInstance().unescapeJava(loginModel.getLastName())); } if (Utils.validateString(loginModel.getUserimage())) { Glide.with(getActivity()).load(loginModel.getUserimage()) .placeholder(R.mipmap.ic_default_user_list) .error(R.mipmap.ic_default_user_list) .into(imgUser); } // Setup Actionbar ImageView actionBarMenu = (ImageView) mainView.findViewById(R.id.actionBarMenu); ImageView actionBarRightMenu = (ImageView) mainView.findViewById(R.id.actionBarRightMenu); TextView actionBarRightButton = (TextView) mainView.findViewById(R.id.actionBarRightButton); TextView actionBarTitle = (TextView) mainView.findViewById(R.id.actionBarTitle); actionBarMenu.setImageResource(R.mipmap.ic_back); actionBarRightMenu.setVisibility(View.GONE); actionBarRightButton.setVisibility(View.VISIBLE); actionBarTitle.setText(getString(R.string.screenTitleEditProfile)); actionBarRightButton.setText(getString(R.string.actionBarDone)); } @Override public void clickEvent(View v) { super.clickEvent(v); switch (v.getId()) { case R.id.actionBarMenu: // Back button onBackPressed(); break; case R.id.actionBarRightButton: if (FieldValidation()) { callEditProfileAPI(); } break; case R.id.imgUser: dialogChoosePicture(); break; case R.id.imgEdit: dialogChoosePicture(); break; } } public void dialogChoosePicture() { final Dialog dialog = new Dialog(getActivity(), 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.btnLibrary); btnGallery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if (checkAndRequestPermissions()) { Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, Constants.REQ_CODE_GALLERY_IMAGE); } } }); TextView btnCamera = (TextView) dialog.findViewById(R.id.btnCamera); btnCamera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); if (checkAndRequestPermissions()) { try { //Uri outputFileUri = getCaptureImageOutputUri(); outputFileUri = FileUtils.getInstance().getFileUri(getActivity(), FileUtils.MEDIA_TYPE.PICTURE); //Constants.IMAGE_URI = outputFileUri; Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); /*captureIntent.putExtra("uri", outputFileUri); captureIntent.putExtra("return-data", true); if (outputFileUri != null) { captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); }*/ startActivityForResult(captureIntent, Constants.REQ_CODE_CAPTURE_IMAGE); } catch (ActivityNotFoundException e) { e.getMessage(); } } } }); TextView btnCancel = (TextView) dialog.findViewById(R.id.btnCancel); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == Constants.REQ_CODE_CAPTURE_IMAGE && resultCode == Activity.RESULT_OK) { /*Constants.IMAGE_URI = getPickImageResultUri(data); Intent intent = new Intent(getActivity(), ImageCropActivity.class); intent.putExtra("xratio", 50); intent.putExtra("yratio", 30); startActivity(intent);*/ Intent intent = new Intent(getActivity(), ImageCropActivity.class); intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 100); intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 100); intent.putExtra(ImageCropActivity.EXTRA_IMAGE_PATH, outputFileUri.getPath()); startActivityForResult(intent, Constants.REQ_CODE_CROP_IMAGE); } else if (requestCode == Constants.REQ_CODE_GALLERY_IMAGE && resultCode == Activity.RESULT_OK && null != data) { /*Constants.IMAGE_URI = getPickImageResultUri(data); Intent cropImage = new Intent(getActivity(), ImageCropActivity.class); cropImage.putExtra("xratio", 50); cropImage.putExtra("yratio", 30); startActivity(cropImage);*/ if(data!=null && data.getData()!=null) { Uri selectedImageUri = data.getData(); /*String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = getActivity().getContentResolver().query(selectedImageUri, projection, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(projection[0]); String picturePath = cursor.getString(columnIndex); // returns null cursor.close();*/ String picturePath = Utils.getInstance().getRealPathFromURI(getActivity(),selectedImageUri); //Copy Original File to app media folder String copiedFilepath=FileUtils.getInstance().copyFile(picturePath,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); intent.putExtra(ImageCropActivity.EXTRA_IMAGE_PATH, copiedFilepath); 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) { croppedImagePath = bundle.getString(ImageCropActivity.EXTRA_IMAGE_PATH); MyLog.v("Cropped Image", "Cropped Image Path: " + croppedImagePath); setSpotImage(croppedImagePath); } } } private void setSpotImage(String spotImage) { if (croppedImagePath != null && croppedImagePath.length() > 0) { Glide.with(getActivity()).load(new File(spotImage)).into(imgUser); } else { imgUser.setImageResource(R.mipmap.ic_default_profile); } } private boolean checkAndRequestPermissions() { int permissionSendMessage = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA); int locationPermission = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE); List<String> listPermissionsNeeded = new ArrayList<>(); if (locationPermission != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); } if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) { listPermissionsNeeded.add(Manifest.permission.CAMERA); } if (!listPermissionsNeeded.isEmpty()) { ActivityCompat.requestPermissions(getActivity(), listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), Constants.MY_PERMISSIONS_REQUEST_URI); return false; } return true; } /** * Call Login API with all facebook data */ private void callEditProfileAPI() { try { if (loginModel != null) { MultipartBody.Part body = null; if (Utils.validateString(croppedImagePath)) { File file = new File(croppedImagePath); // create RequestBody instance from file RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); // MultipartBody.Part is used to send also the actual file name body = MultipartBody.Part.createFormData("userProfile", file.getName(), requestFile); // add another part within the multipart request } RequestBody userId = RequestBody.create(MediaType.parse("multipart/form-data"), "" + loginModel.getUserId()); RequestBody firstName = RequestBody.create(MediaType.parse("multipart/form-data"), Utils.getInstance().escapeJava(edtFirstName.getText().toString().trim())); RequestBody lastName = RequestBody.create(MediaType.parse("multipart/form-data"), Utils.getInstance().escapeJava(edtLastName.getText().toString().trim())); Call<EditProfileModel> objectCall = RestClient.getApiClient().editProfile(/*userId, */firstName, lastName, body); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getResources().getInteger(R.integer.reqCodeEditProfile), true); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if (reqCode == getResources().getInteger(R.integer.reqCodeEditProfile)) { EditProfileModel editProfielModel = (EditProfileModel) response.body(); // String profileImageURL = String.format(getString(R.string.profileImageUrlFB), ""+loginModel.getUserId()); String loginUserData = PrefHelper.getString(getString(R.string.prefLoginUserData), ""); if (loginUserData.trim().length() > 0) { loginModel = (LoginModel) LoginModel.toModelClass(loginUserData, LoginModel.class); loginModel.setFirstName(editProfielModel.getFirstName()); loginModel.setLastName(editProfielModel.getLastName()); loginModel.setUserimage(editProfielModel.getUserimage()); //Save user data to preference PrefHelper.setString(getString(R.string.prefLoginUserData),loginModel.toJson().toString()); } // Update user data in sliding menu homeActivity.setupSlidingMenuData(loginModel); showProfileUpdateDialog(getActivity(), getResources().getString(R.string.profile_updated_successfully)); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { super.onApiError(call, object, reqCode); } //Show alert dialog public void showProfileUpdateDialog(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("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); onBackPressed(); } }); // create alert dialog AlertDialog alertDialog = builder.create(); // show it alertDialog.show(); } } public boolean FieldValidation() { boolean flag = true; if (!Utils.validateString(edtFirstName.getText().toString())) { flag = false; CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.please_enter_first_name)); } else if (!Utils.validateString(edtLastName.getText().toString())) { flag = false; CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.please_enter_last_name)); } return flag; } @Override public void onBackPressed() { homeActivity.popFragment(); } }7)EditSpotFragment.java============================package com.eppico.fragments; import android.app.AlertDialog;import android.content.DialogInterface;import android.os.Bundle;import android.support.design.widget.TextInputLayout;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.EditText;import android.widget.ImageView;import android.widget.RadioButton;import android.widget.TextView;import android.widget.Toast; import com.eppico.R;import com.eppico.api.RestClient;import com.eppico.models.EditProfileModel;import com.eppico.models.EditSpotModel;import com.eppico.models.InviteSpotDetailModel;import com.eppico.models.InviteSpotListModel;import com.eppico.models.LoginModel;import com.eppico.utility.Constants;import com.eppico.utility.CustomDialog;import com.eppico.utility.PrefHelper;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils; import org.apache.commons.lang3.StringEscapeUtils; import retrofit2.Call;import retrofit2.Response; public class EditSpotFragment extends BaseFragment { View mainView; EditText edtSpotName,edtSpotDesc; RadioButton radioActive,radioInActive; private InviteSpotDetailModel spotModel; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle=getArguments(); if(bundle!=null) { String strSpotModel=bundle.getString(getString(R.string.extraSpotModel)); if(strSpotModel.length()>0) { spotModel= (InviteSpotDetailModel) InviteSpotDetailModel.toModelClass(strSpotModel,InviteSpotDetailModel.class); } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mainView=inflater.inflate(R.layout.fragment_edit_spot, container, false); init(); setSpotData(spotModel); return mainView; } private void init() { //Set Sliding Menu enable homeActivity.setSlidingMenuEnable(false); // Hide Keyboard on outside touch Utils.getInstance().setupOutSideTouchHideKeyboard(mainView.findViewById(R.id.my_toolbar)); TextView actionBarTitle= (TextView) mainView.findViewById(R.id.actionBarTitle); ImageView actionBarMenu= (ImageView) mainView.findViewById(R.id.actionBarMenu); ImageView actionBarRightMenu= (ImageView) mainView.findViewById(R.id.actionBarRightMenu); TextView actionBarRightButton= (TextView) mainView.findViewById(R.id.actionBarRightButton); // Set Title actionBarTitle.setText(getString(R.string.screenTitleEditSpotDetails)); // Setup Actionbar actionBarMenu.setImageResource(R.mipmap.ic_back); actionBarRightMenu.setVisibility(View.GONE); actionBarRightButton.setVisibility(View.VISIBLE); actionBarRightButton.setText(getString(R.string.actionBarSave)); // Set TextInputLayout font TextInputLayout txtInputSpotName = (TextInputLayout) mainView.findViewById(R.id.txtInputSpotName); TextInputLayout txtInputDesc = (TextInputLayout) mainView.findViewById(R.id.txtInputDesc); txtInputSpotName.setTypeface(homeActivity.appInstance.fontRobotoLight); txtInputDesc.setTypeface(homeActivity.appInstance.fontRobotoLight); //Set Radio buttons radioActive= (RadioButton) mainView.findViewById(R.id.radioActive); radioInActive= (RadioButton) mainView.findViewById(R.id.radioInActive); radioActive.setTypeface(homeActivity.appInstance.fontRobotoLight); radioInActive.setTypeface(homeActivity.appInstance.fontRobotoLight); edtSpotName= (EditText) mainView.findViewById(R.id.edtSpotName); edtSpotDesc= (EditText) mainView.findViewById(R.id.edtSpotDesc); } private void setSpotData(InviteSpotDetailModel spotModel) { if(spotModel!=null) { /*edtSpotName.setText(Utils.getInstance().unescapeJava(spotModel.getSpotName())); edtSpotDesc.setText(Utils.getInstance().unescapeJava(spotModel.getSpotDetailDesc()));*/ edtSpotName.setText(spotModel.getSpotName()); edtSpotDesc.setText(spotModel.getSpotDetailDesc()); /**Note: 1= Active, 0= Inactive*/ if(spotModel.getIsActive()==1) radioActive.setChecked(true); else radioInActive.setChecked(true); } } @Override public void clickEvent(View v) { super.clickEvent(v); switch (v.getId()) { case R.id.actionBarMenu: // Back button onBackPressed(); break; case R.id.actionBarRightButton: if(edtSpotName.getText().toString().trim().length()==0) { edtSpotName.requestFocus(); CustomDialog.getInstance().showMessageDialog(getActivity(),getResources().getString(R.string.please_enter_spot_name)); } else if(edtSpotDesc.getText().toString().trim().length()==0) { edtSpotDesc.requestFocus(); CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.please_enter_spot_desc)); } else { /*Note: Show confirmation dialog before inactive spot*/ if(radioInActive.isChecked()) showInactiveConfirmationDialog(); else callEditSpotAPI(Constants.SPOT_ACTIVE_STATUS.ACITVE); } break; } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if (reqCode == getResources().getInteger(R.integer.reqCodeEditSpot)) { EditSpotModel editSpotModel = (EditSpotModel) response.body(); ToastHelper.getInstance().showToast(getActivity(),getString(R.string.spotUpdateSuccessfully)); onBackPressed();// String profileImageURL = String.format(getString(R.string.profileImageUrlFB), ""+loginModel.getUserId()); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { super.onApiError(call, object, reqCode); } private void callEditSpotAPI(Constants.SPOT_ACTIVE_STATUS spotActiveStatus) { /*int isActive=0; if(radioActive.isChecked()) isActive=1;*/ String spotName = Utils.getInstance().escapeJava(edtSpotName.getText().toString().trim()); String spotDesc = Utils.getInstance().escapeJava(edtSpotDesc.getText().toString().trim()); Call<EditSpotModel> objectCall = RestClient.getApiClient().editSpot(spotModel.getSpotId()+"",spotName,spotDesc,spotActiveStatus.ordinal()+""); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeEditSpot), true); } //Show inactive spot confirmation dialog public void showInactiveConfirmationDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); //builder.setTitle(title); builder.setCancelable(true); builder.setMessage(getString(R.string.msgConfirmInactiveSpot)); builder.setPositiveButton(getString(R.string.btnYes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); callEditSpotAPI(Constants.SPOT_ACTIVE_STATUS.INACTIVE); } }); builder.setNegativeButton(getString(R.string.btnNo), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); homeActivity.popFragment(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } @Override public void onBackPressed() { homeActivity.popFragment(); } }8)FollowersListFragment.java============================package com.eppico.fragments; import android.app.Dialog;import android.content.Context;import android.os.Bundle;import android.os.Handler;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.support.v7.widget.DividerItemDecoration;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.view.Gravity;import android.view.KeyEvent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.inputmethod.EditorInfo;import android.widget.Button;import android.widget.EditText;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import com.bumptech.glide.Glide;import com.eppico.R;import com.eppico.adapter.FollowersListAdapter;import com.eppico.api.RestClient;import com.eppico.models.CheckInUserModel;import com.eppico.models.FollowUserModel;import com.eppico.models.FollowersListModel;import com.eppico.utility.Constants;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils; import java.util.ArrayList;import java.util.List; import retrofit2.Call;import retrofit2.Response; /** * Created by manisha on 13/12/16. */ public class FollowersListFragment extends BaseFragment { // XML Components private View mainView; private RecyclerView recyclerViewFollowersList; private TextView txtActionBarTitle, txtNoRecords; EditText edtSearchUser; int totalCount = 0; boolean isLoading = false, isSearch = false; static final int FIRST_PAGE_NO = 0; int pageNo = FIRST_PAGE_NO; int pastVisiblesItems, visibleItemCount, totalItemCount; String searchStr = ""; int spotId; Constants.FROM_SCREEN fromScreen; Constants.FOLLOW_LIST followList; private ArrayList<FollowersListModel.Followuser> listFollowers; private ImageView actionBarMenu, actionBarRightMenu; private int userId; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getArguments(); if (bundle != null) { fromScreen = Constants.FROM_SCREEN.values()[bundle.getInt(getString(R.string.extraFromScreen))]; userId = bundle.getInt(getResources().getString(R.string.extraUserId)); if(fromScreen== Constants.FROM_SCREEN.SPOT_DETAIL) { spotId = bundle.getInt(getString(R.string.extraSpotId)); followList= Constants.FOLLOW_LIST.FOLLOWERS; } else if(fromScreen== Constants.FROM_SCREEN.PROFILE) followList= Constants.FOLLOW_LIST.values()[bundle.getInt(getString(R.string.extraFollowListType))]; } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mainView = inflater.inflate(R.layout.fragment_followers_list, container, false); init(); setSearchEvent(); return mainView; } public void init() { //Disable Sliding menu homeActivity.setSlidingMenuEnable(false); // Hide Keyboard on outside touch Utils.getInstance().setupOutSideTouchHideKeyboard(mainView.findViewById(R.id.parentView)); txtActionBarTitle = (TextView) mainView.findViewById(R.id.actionBarTitle); actionBarMenu = (ImageView) mainView.findViewById(R.id.actionBarMenu); actionBarRightMenu = (ImageView) mainView.findViewById(R.id.actionBarRightMenu); TextView txtNext = (TextView) mainView.findViewById(R.id.actionBarRightButton); edtSearchUser = (EditText) mainView.findViewById(R.id.edtSearch); // Set Title /*if(fromScreen== Constants.FROM_SCREEN.SPOT_DETAIL) txtActionBarTitle.setText(getString(R.string.screenTitleFollowers)); else if(fromScreen== Constants.FROM_SCREEN.PROFILE) { if(followList== Constants.FOLLOW_LIST.FOLLOWERS) txtActionBarTitle.setText(getString(R.string.screenTitleFollowers)); else txtActionBarTitle.setText(getString(R.string.screenTitleFollowing)); }*/ if(followList == Constants.FOLLOW_LIST.FOLLOWERS) txtActionBarTitle.setText(getString(R.string.screenTitleFollowers)); else txtActionBarTitle.setText(getString(R.string.screenTitleFollowing)); // Setup Actionbar actionBarMenu.setImageResource(R.mipmap.ic_back); actionBarRightMenu.setVisibility(View.VISIBLE); txtNext.setVisibility(View.GONE); edtSearchUser.setHint(getString(R.string.hintSearchUser)); txtNoRecords = (TextView) mainView.findViewById(R.id.txtNoRecords); initNSetRecyclerViewEvents(); new Handler().postDelayed(new Runnable() { @Override public void run() { resetListVariables(); getFollowersList(searchStr, pageNo, true); /*FollowersListAdapter adapter = new FollowersListAdapter(getActivity(), listFollowers, totalCount); recyclerViewFollowersList.setAdapter(adapter);*/ } }, getResources().getInteger(android.R.integer.config_mediumAnimTime)); } private void initNSetRecyclerViewEvents() { recyclerViewFollowersList = (RecyclerView) mainView.findViewById(R.id.recyclerViewFollowersList); final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); recyclerViewFollowersList.setLayoutManager(layoutManager); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerViewFollowersList.getContext(), layoutManager.getOrientation()); // dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this,R.drawable.divider)); recyclerViewFollowersList.addItemDecoration(dividerItemDecoration); recyclerViewFollowersList.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); //if (dy > 0) //check for scroll down // { visibleItemCount = layoutManager.getChildCount(); totalItemCount = layoutManager.getItemCount(); pastVisiblesItems = layoutManager.findFirstVisibleItemPosition(); if (!isLoading && totalCount > listFollowers.size()) { if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) { getFollowersList(searchStr, pageNo, false); } } //} } }); } public void setSearchEvent() { edtSearchUser.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { searchStr = edtSearchUser.getText().toString().trim(); if (searchStr.length() > 0) { Utils.getInstance().hideKeyboard(v, getActivity()); searchStr = edtSearchUser.getText().toString().trim(); if (searchStr.length() > 0) { isSearch = true; //pageNo=0; resetListVariables(); getFollowersList(searchStr, pageNo, true); } } else { //Toast.makeText(getActivity(), getActivity().getString(R.string.searchMessage), Toast.LENGTH_SHORT).show(); ToastHelper.getInstance().showToast(getActivity(), getString(R.string.enterSearchText)); edtSearchUser.requestFocus(); } } return true; } }); } @Override public void clickEvent(View v) { super.clickEvent(v); switch (v.getId()) { case R.id.actionBarRightMenu: //Toggle Search icon if (edtSearchUser.getVisibility() == View.VISIBLE) { searchStr = ""; edtSearchUser.setText(""); edtSearchUser.clearFocus(); edtSearchUser.setVisibility(View.GONE); txtActionBarTitle.setVisibility(View.VISIBLE); actionBarRightMenu.setVisibility(View.VISIBLE); //Set Menu icon actionBarMenu.setImageResource(R.mipmap.ic_back); } else { edtSearchUser.setVisibility(View.VISIBLE); txtActionBarTitle.setVisibility(View.GONE); actionBarRightMenu.setVisibility(View.GONE); //Set back icon actionBarMenu.setImageResource(R.mipmap.ic_back); edtSearchUser.requestFocus(); Utils.getInstance().showKeyboard(edtSearchUser, getActivity()); } /*if (!edtSearch.getText().toString().trim().equalsIgnoreCase("")) { MyLog.e("", "Search:" + edtSearch.getText().toString()); searchInviteList(); Utils.getInstance().hideKeyboard(view, getActivity()); }*/ break; case R.id.actionBarMenu: // Back button onBackPressed(); break; case R.id.actionBarRightButton: break; case R.id.txtFollow: if (v.getTag() != null) { FollowersListModel.Followuser followers = (FollowersListModel.Followuser) v.getTag(); if(followers.getUserIsFollowing()==Constants.FOLLOW_STATUS.FOLLOW.ordinal()) showUnFollowDialog(followers); else callUserFollowApi(followers); } break; case R.id.txtUserName: case R.id.imgUser: // if(v.getTag(R.string.tagId)!=null)// { FollowersListModel.Followuser followers = (FollowersListModel.Followuser) v.getTag(R.string.tagId); MyProfileFragment fragment = new MyProfileFragment(); Bundle mBundle = new Bundle(); mBundle.putInt(getString(R.string.extraUserId),followers.getUserId()); fragment.setArguments(mBundle); homeActivity.pushFragments(fragment, true, false, true);// } break; } } @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)) { isLoading = false; pageNo++; FollowersListModel followersListModel = (FollowersListModel) response.body(); totalCount = followersListModel.getTotalCount(); if (listFollowers == null) listFollowers = new ArrayList<FollowersListModel.Followuser>(); if (followersListModel.getFollowuser() != null) { listFollowers.addAll(followersListModel.getFollowuser()); } /*if(pageNo==4) listUsers=null; if(listUsers!=null && listUsers.size()>0) listAppUsers.addAll((ArrayList<AppUserModel.User>) response.body()); else isAllRecordsLoaded=true;*/ bindUserList(listFollowers); } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode, int position) { if (reqCode == getResources().getInteger(R.integer.reqCodeFollowUser)) { if(followList== Constants.FOLLOW_LIST.FOLLOWERS) { FollowUserModel followUserModel= (FollowUserModel) response.body(); FollowersListModel.Followuser followSpot=listFollowers.get(position); followSpot.setUserIsFollowing(followUserModel.getUserIsFollowing()); listFollowers.set(position,followSpot); bindUserList(listFollowers); } else { resetListVariables(); getFollowersList(searchStr, pageNo, true); } } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { ToastHelper.getInstance().showToast(getActivity(),object.toString(), Toast.LENGTH_LONG); } private void bindUserList(ArrayList<FollowersListModel.Followuser> alstCheckInUser) { if (alstCheckInUser != null && alstCheckInUser.size() > 0) { /*if(searchStr!=null && searchStr.length()>0 && pageNoSearch==1) recyclerViewInviteSpot.setAdapter(null);*/ recyclerViewFollowersList.setVisibility(View.VISIBLE); txtNoRecords.setVisibility(View.GONE); FollowersListAdapter adapter = (FollowersListAdapter) recyclerViewFollowersList.getAdapter(); if (adapter != null && adapter.getItemCount() > 0) { adapter.setListItems(alstCheckInUser); /*if(isAllRecordsLoaded) adapter.notifyItemRemoved(listAppUsers.size());*/ } else { adapter = new FollowersListAdapter(getActivity(), homeActivity.loginModel.getUserId(), alstCheckInUser, totalCount); recyclerViewFollowersList.setAdapter(adapter); } } else { recyclerViewFollowersList.setVisibility(View.GONE); txtNoRecords.setVisibility(View.VISIBLE); } } /** * Reset variables before search */ private void resetListVariables() { isLoading = false; pageNo = FIRST_PAGE_NO; totalCount = 0; visibleItemCount = 0; totalItemCount = 0; pastVisiblesItems = 0; listFollowers = new ArrayList<FollowersListModel.Followuser>(); recyclerViewFollowersList.setAdapter(null); } private void getFollowersList(String search, int pageNo, boolean showDialog) { // loginModel.getUserId(); isLoading = true; switch (fromScreen) { case SPOT_DETAIL: Call<FollowersListModel> objectCall = RestClient.getApiClient().getSpotFollowersList(/*homeActivity.loginModel.getUserId() + "",*/ spotId + "", String.valueOf(pageNo), search); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeGetFollowersList), showDialog); break; case PROFILE: Call<FollowersListModel> objectCallUserFollowers = RestClient.getApiClient().getUserFollowersList(userId+"",String.valueOf(pageNo), search,followList.ordinal()+""); homeActivity.restClient.makeApiRequest(getActivity(), objectCallUserFollowers, this, getActivity().getResources().getInteger(R.integer.reqCodeUserFollowersList), showDialog); break; } } private void callUserFollowApi(FollowersListModel.Followuser followers) { Constants.FOLLOW_STATUS followStatus; if(followers.getUserIsFollowing()==Constants.FOLLOW_STATUS.FOLLOW.ordinal()) followStatus= Constants.FOLLOW_STATUS.UNFOLLOW; else followStatus= Constants.FOLLOW_STATUS.FOLLOW; Call<FollowUserModel> objectCall = RestClient.getApiClient().followUser(/*homeActivity.loginModel.getUserId() + "",*/ followers.getUserId() + "", followStatus.ordinal()+""); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeFollowUser),followers.getPosition(), true); } /**Show UnFollow User confirmation dialog with spot image and spot name*/ private void showUnFollowDialog(final FollowersListModel.Followuser followers) { try { final Dialog dialog = new Dialog(getActivity(), R.style.DialogTheme); dialog.setCancelable(true); LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.dialog_unfollow, null); ImageView imgUser = (ImageView) view.findViewById(R.id.imgUser); TextView txtUserName = (TextView) view.findViewById(R.id.txtUserName); Button btnCancel = (Button) view.findViewById(R.id.btnCancel); Button btnUnfollow = (Button) view.findViewById(R.id.btnUnfollow); // Set font type btnCancel.setTypeface(homeActivity.appInstance.fontRobotoRegular); btnUnfollow.setTypeface(homeActivity.appInstance.fontRobotoRegular); txtUserName.setText(getString(R.string.btnUnfollow) + " " + followers.getFirstName() + " " + followers.getLastName() + "?"); Glide.with(getActivity()) .load(followers.getUserProfile()) .placeholder(R.mipmap.ic_default_user_list) .error(R.mipmap.ic_default_user_list) .into(imgUser); dialog.setContentView(view); /** Set Dialog width match parent */ dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); btnUnfollow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); callUserFollowApi(followers); } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); if (dialog.isShowing()) dialog.dismiss(); dialog.show(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onBackPressed() { if (isSearch) { isSearch = false; edtSearchUser.setText(""); resetListVariables(); actionBarRightMenu.performClick(); getFollowersList(searchStr, pageNo, true); } else if (edtSearchUser.getVisibility() == View.VISIBLE) actionBarRightMenu.performClick(); else homeActivity.popFragment(); } }9)FollowingSpotFragment.java=============================package com.eppico.fragments; import android.app.Dialog;import android.content.Context;import android.os.Bundle;import android.os.Handler;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.support.v7.widget.DividerItemDecoration;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.view.KeyEvent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.inputmethod.EditorInfo;import android.widget.Button;import android.widget.EditText;import android.widget.ImageView;import android.widget.TextView; import com.bumptech.glide.Glide;import com.eppico.R;import com.eppico.activity.BaseActivity;import com.eppico.adapter.FollowingSpotAdapter;import com.eppico.adapter.InviteSpotAdapter;import com.eppico.api.RestClient;import com.eppico.interfaces.RecyclerViewItemClickListener;import com.eppico.models.FollowSpotModel;import com.eppico.models.FollowUserModel;import com.eppico.models.FollowersListModel;import com.eppico.models.FollowingListModel;import com.eppico.utility.Constants;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils;import com.eppico.widgets.ShapedImageView; import java.util.ArrayList; import retrofit2.Call;import retrofit2.Response; /** * Created by manisha on 3/1/17. */ public class FollowingSpotFragment extends BaseFragment { View view; RecyclerView recyclerView; private ArrayList<FollowingListModel.FollowingSpot> alstFollowingSpot; private TextView txtActionBarTitle; private EditText edtSearch; private ImageView actionBarMenu, actionBarRightMenu; int pageIndex = Constants.FIRST_PAGE_NO; TextView txtNoRecords; boolean isLoading = false, isSearch = false; int pastVisiblesItems, visibleItemCount, totalItemCount; int totalCount; String searchStr = ""; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_following_spot, container, false); init(); new Handler().postDelayed(new Runnable() { @Override public void run() { resetVariables(); getFoolowingSpotList(searchStr, pageIndex, true); } }, 400); return view; } public void init() { //Enable Sliding menu homeActivity.setSlidingMenuEnable(true); homeActivity.setSelectedPositionInSlidingMenu(5); // Hide Keyboard on outside touch Utils.getInstance().setupOutSideTouchHideKeyboard(view.findViewById(R.id.parentView)); /*String mLoginUserData = PrefHelper.getString(getString(R.string.prefLoginUserData), ""); MyApplication myApplication = (MyApplication) getActivity().getApplication(); restClient = myApplication.getRestClient(); if (mLoginUserData.length() > 0) { loginModel = (LoginModel) LoginModel.toModelClass(mLoginUserData, LoginModel.class); }*/ txtNoRecords = (TextView) view.findViewById(R.id.txtNoRecords); //Set Search hint text and text color edtSearch = (EditText) view.findViewById(R.id.edtSearch); //edtSearch.setHintTextColor(ContextCompat.getColor(getActivity(), R.color.white)); edtSearch.setHint(getString(R.string.hintSearchSpot)); txtActionBarTitle = (TextView) view.findViewById(R.id.actionBarTitle); actionBarRightMenu = (ImageView) view.findViewById(R.id.actionBarRightMenu); actionBarMenu = (ImageView) view.findViewById(R.id.actionBarMenu); TextView txtNext = (TextView) view.findViewById(R.id.actionBarRightButton); actionBarRightMenu.setVisibility(View.VISIBLE); txtNext.setVisibility(View.GONE); //Set Title txtActionBarTitle.setText(getResources().getString(R.string.following_spots)); setSearchEvent(); initNSetRecyclerViewEvents(); if (isSearch) { actionBarRightMenu.performClick(); } } private void setSearchEvent() { edtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { searchStr = edtSearch.getText().toString().trim(); if (searchStr.length() > 0) { Utils.getInstance().hideKeyboard(v, getActivity()); searchStr = edtSearch.getText().toString().trim(); if (searchStr.length() > 0) { isSearch = true; resetVariables();// searchInviteList(searchStr,pageIndex,true); getFoolowingSpotList(searchStr, pageIndex, true); } } else { //Toast.makeText(getActivity(), getActivity().getString(R.string.searchMessage), Toast.LENGTH_SHORT).show(); ToastHelper.getInstance().showToast(getActivity(), getString(R.string.enterSearchText)); edtSearch.requestFocus(); } } return true; } }); } private void initNSetRecyclerViewEvents() { recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewFollowingSpot); final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); recyclerView.setLayoutManager(layoutManager); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), layoutManager.getOrientation()); // dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this,R.drawable.divider)); recyclerView.addItemDecoration(dividerItemDecoration); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); //if (dy > 0) // check for scroll down // { visibleItemCount = layoutManager.getChildCount(); totalItemCount = layoutManager.getItemCount(); pastVisiblesItems = layoutManager.findFirstVisibleItemPosition(); if (!isLoading && totalCount > alstFollowingSpot.size()) { if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) { /*if(isSearch) searchInviteList(searchStr,pageIndex,false); else getInviteList(searchStr,pageIndex,false);*/ getFoolowingSpotList(searchStr, pageIndex, false); } } // } } }); /*recyclerView.addOnItemTouchListener(new RecyclerViewItemClickListener(getActivity(), new RecyclerViewItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Fragment fragment = new InviteSpotDetailFragment(); Bundle mBundle = new Bundle(); mBundle.putInt(getResources().getString(R.string.extraSpotId), alstFollowingSpot.get(position).getSpotId()); fragment.setArguments(mBundle); homeActivity.pushFragments(fragment, true, false, true); } }));*/ } public void clickEvent(View view) { switch (view.getId()) { case R.id.actionBarRightMenu: //Toggle Search icon if (edtSearch.getVisibility() == View.VISIBLE) { searchStr = ""; edtSearch.setText(searchStr); edtSearch.clearFocus(); edtSearch.setVisibility(View.GONE); txtActionBarTitle.setVisibility(View.VISIBLE); actionBarRightMenu.setVisibility(View.VISIBLE); //Set Menu icon actionBarMenu.setImageResource(R.mipmap.ic_menu); } else { edtSearch.setVisibility(View.VISIBLE); txtActionBarTitle.setVisibility(View.GONE); actionBarRightMenu.setVisibility(View.GONE); //Set back icon actionBarMenu.setImageResource(R.mipmap.ic_back); edtSearch.requestFocus(); Utils.getInstance().showKeyboard(edtSearch, getActivity()); } break; case R.id.actionBarMenu: // onBackPressed(); handleBackPressEvent(false); break; case R.id.linFollowingSpotMain: if (view.getTag() != null) { FollowingListModel.FollowingSpot followingSpot = (FollowingListModel.FollowingSpot) view.getTag(); Fragment fragment = new InviteSpotDetailFragment(); Bundle mBundle = new Bundle(); mBundle.putInt(getResources().getString(R.string.extraSpotId), followingSpot.getSpotId()); fragment.setArguments(mBundle); homeActivity.pushFragments(fragment, true, false, true); } break; case R.id.txtFollowing: if (view.getTag() != null) { FollowingListModel.FollowingSpot followingSpot = (FollowingListModel.FollowingSpot) view.getTag(); showUnFollowDialog(followingSpot); } break; } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if (reqCode == getActivity().getResources().getInteger(R.integer.reqCodeGetFollowingSpotList)) { isLoading = false; pageIndex++; FollowingListModel followingSpotListModel = (FollowingListModel) response.body(); totalCount = followingSpotListModel.getTotalCount(); if (alstFollowingSpot == null) alstFollowingSpot = new ArrayList<FollowingListModel.FollowingSpot>(); if (followingSpotListModel.getFollowingSpot() != null) alstFollowingSpot.addAll(followingSpotListModel.getFollowingSpot()); bindSpotList(alstFollowingSpot); } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode, int position) { if (reqCode == getResources().getInteger(R.integer.reqCodeFollowSpot)) { resetVariables(); getFoolowingSpotList(searchStr, pageIndex, true); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { if (reqCode == getActivity().getResources().getInteger(R.integer.reqCodeGetFollowingSpotList)) { isLoading = false; ToastHelper.getInstance().showToast(getActivity(), object.toString()); } } private void getFoolowingSpotList(String searchStr, int pageNo, boolean showDialog) { if (homeActivity.loginModel != null) { isLoading = true; Call<FollowingListModel> objectCall = null;// objectCall = RestClient.getApiClient().followingSpotList("93", searchStr, String.valueOf(pageNo)); objectCall = RestClient.getApiClient().followingSpotList(/*""+homeActivity.loginModel.getUserId(),*/ searchStr, String.valueOf(pageNo)); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeGetFollowingSpotList), showDialog); } } private void bindSpotList(ArrayList<FollowingListModel.FollowingSpot> listFollowingSpot) { if (listFollowingSpot != null && listFollowingSpot.size() > 0) { recyclerView.setVisibility(View.VISIBLE); txtNoRecords.setVisibility(View.GONE); FollowingSpotAdapter mFllowingSpotAdapter = (FollowingSpotAdapter) recyclerView.getAdapter(); if (mFllowingSpotAdapter != null && mFllowingSpotAdapter.getItemCount() > 0) { /*if(isAllRecordsLoaded) adapter.notifyItemRemoved(listAppUsers.size());*/ mFllowingSpotAdapter.setListItems(listFollowingSpot); } else { mFllowingSpotAdapter = new FollowingSpotAdapter(getActivity(), listFollowingSpot, totalCount); recyclerView.setAdapter(mFllowingSpotAdapter); } } else { recyclerView.setVisibility(View.GONE); txtNoRecords.setVisibility(View.VISIBLE); } } private void resetVariables() { isLoading = false; pageIndex = Constants.FIRST_PAGE_NO; totalCount = 0; visibleItemCount = 0; totalItemCount = 0; pastVisiblesItems = 0; alstFollowingSpot = new ArrayList<FollowingListModel.FollowingSpot>(); recyclerView.setAdapter(null); } /** * Show UnFollow Spot confirmation dialog with spot image and spot name */ private void showUnFollowDialog(final FollowingListModel.FollowingSpot followingSpot) { try { final Dialog dialog = new Dialog(getActivity(), R.style.DialogTheme); dialog.setCancelable(true); LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.dialog_unfollow, null); ShapedImageView imgUser = (ShapedImageView) view.findViewById(R.id.imgUser); TextView txtUserName = (TextView) view.findViewById(R.id.txtUserName); Button btnCancel = (Button) view.findViewById(R.id.btnCancel); Button btnUnfollow = (Button) view.findViewById(R.id.btnUnfollow); imgUser.setShapeMode(ShapedImageView.SHAPE_MODE_ROUND_RECT); // Set font type btnCancel.setTypeface(homeActivity.appInstance.fontRobotoRegular); btnUnfollow.setTypeface(homeActivity.appInstance.fontRobotoRegular); txtUserName.setText(getString(R.string.btnUnfollow) + " " + followingSpot.getSpotName() + "?"); Glide.with(getActivity()) .load(followingSpot.getSpotImage()) .placeholder(R.mipmap.spot_default_img) .error(R.mipmap.spot_default_img) .into(imgUser); dialog.setContentView(view); /** Set Dialog width match parent */ dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); btnUnfollow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); callFollowSpotAPI(followingSpot, Constants.FOLLOW_STATUS.UNFOLLOW); } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); if (dialog.isShowing()) dialog.dismiss(); dialog.show(); } catch (Exception e) { e.printStackTrace(); } } public void callFollowSpotAPI(FollowingListModel.FollowingSpot followingSpot, Constants.FOLLOW_STATUS followStatus) { Call<FollowSpotModel> objectCall = RestClient.getApiClient().followSpot(followingSpot.getSpotId() + "", followingSpot.getSpotFollowerId() + "", followStatus.ordinal() + ""); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getResources().getInteger(R.integer.reqCodeFollowSpot), followingSpot.getPosition(), true); } private void handleBackPressEvent(boolean isHardwareBackButton) { if (isSearch) { isSearch = false; resetVariables(); actionBarRightMenu.performClick(); getFoolowingSpotList(searchStr, pageIndex, true); } else if (edtSearch.getVisibility() == View.VISIBLE) { actionBarRightMenu.performClick(); } else if (homeActivity.isSlidingMenuOpen() || !isHardwareBackButton) // Open Sliding menu on click of menu icon homeActivity.toggleSlidingMenu(); else homeActivity.popFragment(); } @Override public void onBackPressed() { handleBackPressEvent(true); /*if (isSearch) { isSearch = false; resetVariables(); actionBarRightMenu.performClick(); getFoolowingSpotList(searchStr, pageIndex, true); } else if (edtSearch.getVisibility() == View.VISIBLE) { actionBarRightMenu.performClick(); } else homeActivity.toggleSlidingMenu();*/ } }9)HomeFragment.java===========================package com.eppico.fragments; import android.content.Context;import android.net.Uri;import android.os.Bundle;import android.support.v4.app.Fragment;import android.util.Log;import android.view.KeyEvent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.inputmethod.EditorInfo;import android.widget.EditText;import android.widget.ImageView;import android.widget.TextView; import com.eppico.R;import com.eppico.activity.HomeActivity;import com.eppico.models.AppUserModel;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils; import java.util.HashMap; public class HomeFragment extends BaseFragment { View mainView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mainView=inflater.inflate(R.layout.fragment_home, container, false); init(); return mainView; } private void init() { //Set Sliding Menu enable homeActivity.setSlidingMenuEnable(true); homeActivity.setSelectedPositionInSlidingMenu(0); // Set Title TextView actionBarTitle= (TextView) mainView.findViewById(R.id.actionBarTitle); actionBarTitle.setText(getString(R.string.screenTitleHomeFeeds)); // Setup Actionbar ImageView actionBarRightMenu= (ImageView) mainView.findViewById(R.id.actionBarRightMenu); actionBarRightMenu.setVisibility(View.INVISIBLE); } @Override public void clickEvent(View v) { super.clickEvent(v); switch (v.getId()) { case R.id.actionBarMenu: // Menu button homeActivity.toggleSlidingMenu(); break; } } @Override public void onBackPressed() { homeActivity.popFragment(); } }10)InvitedSpotFragment.java============================package com.eppico.fragments; import android.os.Bundle;import android.os.Handler;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.support.v4.content.ContextCompat;import android.support.v7.widget.DividerItemDecoration;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.view.KeyEvent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.inputmethod.EditorInfo;import android.widget.EditText;import android.widget.ImageView;import android.widget.TextView; import com.eppico.MyApplication;import com.eppico.R;import com.eppico.activity.BaseActivity;import com.eppico.activity.HomeActivity;import com.eppico.adapter.InviteSpotAdapter;import com.eppico.api.ApiResponseListener;import com.eppico.api.RestClient;import com.eppico.interfaces.RecyclerViewItemClickListener;import com.eppico.models.BaseModel;import com.eppico.models.InviteSpotListModel;import com.eppico.models.LoginModel;import com.eppico.utility.Constants;import com.eppico.utility.PrefHelper;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils; import java.util.ArrayList; import retrofit2.Call;import retrofit2.Response; /** * Created by manisha on 13/12/16. */ public class InvitedSpotFragment extends BaseFragment { View view; RecyclerView recyclerView; InviteSpotAdapter mInviteSpotAdapter; private ArrayList<InviteSpotListModel.SpotInvitaionUserList> alstInviteSpot;// LoginModel loginModel; private TextView txtNext, txtActionBarTitle; private EditText edtSearch; private ImageView actionBarMenu,actionBarRightMenu; int pageIndex = Constants.FIRST_PAGE_NO; TextView txtNoRecords; boolean isLoading = false, isSearch = false; int pastVisiblesItems, visibleItemCount, totalItemCount; int totalCount; String searchStr = ""; Constants.SPOT_LIST_TYPE spotListType; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle=getArguments(); if(bundle!=null) { spotListType=Constants.SPOT_LIST_TYPE.values()[bundle.getInt(getString(R.string.extraSpotListType),Constants.SPOT_LIST_TYPE.INVITED_SPOT.ordinal())]; } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_invite_spot, container, false); init(); new Handler().postDelayed(new Runnable() { @Override public void run() { resetVariables(); getSpotList(searchStr, pageIndex, true); } }, 400); return view; } public void init() { //Enable Sliding menu homeActivity.setSlidingMenuEnable(true); // Hide Keyboard on outside touch Utils.getInstance().setupOutSideTouchHideKeyboard(view.findViewById(R.id.parentView)); /*String mLoginUserData = PrefHelper.getString(getString(R.string.prefLoginUserData), ""); MyApplication myApplication = (MyApplication) getActivity().getApplication(); restClient = myApplication.getRestClient(); if (mLoginUserData.length() > 0) { loginModel = (LoginModel) LoginModel.toModelClass(mLoginUserData, LoginModel.class); }*/ txtNoRecords = (TextView) view.findViewById(R.id.txtNoRecords); //Set Search hint text and text color edtSearch = (EditText) view.findViewById(R.id.edtSearch); //edtSearch.setHintTextColor(ContextCompat.getColor(getActivity(), R.color.white)); edtSearch.setHint(getString(R.string.hintSearchSpot)); txtActionBarTitle = (TextView) view.findViewById(R.id.actionBarTitle); actionBarRightMenu = (ImageView) view.findViewById(R.id.actionBarRightMenu); actionBarMenu = (ImageView) view.findViewById(R.id.actionBarMenu); TextView txtNext = (TextView) view.findViewById(R.id.actionBarRightButton); actionBarRightMenu.setVisibility(View.VISIBLE); txtNext.setVisibility(View.GONE); //Set Title if(spotListType== Constants.SPOT_LIST_TYPE.INVITED_SPOT) { homeActivity.setSelectedPositionInSlidingMenu(3); txtActionBarTitle.setText(getResources().getString(R.string.screenTitleInvitedSpot)); } else { homeActivity.setSelectedPositionInSlidingMenu(4); txtActionBarTitle.setText(getResources().getString(R.string.screenTitleMySpot)); } setSearchEvent(); initNSetRecyclerViewEvents(); if (isSearch) { actionBarRightMenu.performClick(); } } private void setSearchEvent() { edtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { searchStr = edtSearch.getText().toString().trim(); if (searchStr.length() > 0) { Utils.getInstance().hideKeyboard(v, getActivity()); searchStr = edtSearch.getText().toString().trim(); if (searchStr.length() > 0) { isSearch = true; resetVariables();// searchInviteList(searchStr,pageIndex,true); getSpotList(searchStr, pageIndex, true); } } else { //Toast.makeText(getActivity(), getActivity().getString(R.string.searchMessage), Toast.LENGTH_SHORT).show(); ToastHelper.getInstance().showToast(getActivity(), getString(R.string.enterSearchText)); edtSearch.requestFocus(); } } return true; } }); } private void initNSetRecyclerViewEvents() { recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewInviteSpot); final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); recyclerView.setLayoutManager(layoutManager); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),layoutManager.getOrientation()); dividerItemDecoration.setDrawable(ContextCompat.getDrawable(getActivity(),R.drawable.divider_spot_list)); recyclerView.addItemDecoration(dividerItemDecoration); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); //if (dy > 0) //check for scroll down // { visibleItemCount = layoutManager.getChildCount(); totalItemCount = layoutManager.getItemCount(); pastVisiblesItems = layoutManager.findFirstVisibleItemPosition(); if (!isLoading && totalCount > alstInviteSpot.size()) { if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) { /*if(isSearch) searchInviteList(searchStr,pageIndex,false); else getInviteList(searchStr,pageIndex,false);*/ getSpotList(searchStr, pageIndex, false); } } //} } }); recyclerView.addOnItemTouchListener(new RecyclerViewItemClickListener(getActivity(), new RecyclerViewItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Fragment fragment = new InviteSpotDetailFragment(); Bundle mBundle = new Bundle();// mBundle.putString(getResources().getString(R.string.inviteSpotID), String.valueOf(alstInviteSpot.get(position).getSpotId())); InviteSpotListModel.SpotInvitaionUserList spotInvitaionUserList=new InviteSpotListModel.SpotInvitaionUserList(); InviteSpotListModel spotListModel=new InviteSpotListModel(); mBundle.putInt(getResources().getString(R.string.extraSpotId), alstInviteSpot.get(position).getSpotId()); fragment.setArguments(mBundle); homeActivity.pushFragments(fragment, true, false, true); } })); } private void getSpotList(String searchStr, int pageNo, boolean showDialog) { if (homeActivity.loginModel != null) { isLoading = true; Call<InviteSpotListModel> objectCall=null; if(spotListType == Constants.SPOT_LIST_TYPE.INVITED_SPOT) objectCall = RestClient.getApiClient().inviteSpotList(/*""+homeActivity.loginModel.getUserId(),*/ searchStr, String.valueOf(pageNo)); else objectCall = RestClient.getApiClient().mySpotList(/*""+homeActivity.loginModel.getUserId(),*/ searchStr, String.valueOf(pageNo)); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeInviteSpot), showDialog); } } /*private void getMySpotList(String searchStr, int pageNo, boolean showDialog) { if (loginModel != null) { isLoading = true;// Call<InviteSpotListModel> objectCall = RestClient.getApiClient().inviteSpotList(""+loginModel.getUserId(), searchStr, String.valueOf(pageNo)); Call<InviteSpotListModel> objectCall = RestClient.getApiClient().mySpotList(""+loginModel.getUserId(), searchStr, String.valueOf(pageNo)); restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeInviteSpot), showDialog); } }*/ @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if (reqCode == getActivity().getResources().getInteger(R.integer.reqCodeInviteSpot)) { isLoading = false; pageIndex++; InviteSpotListModel inviteSpotListModel = (InviteSpotListModel) response.body(); totalCount = inviteSpotListModel.getTotalCount(); if (alstInviteSpot == null) alstInviteSpot = new ArrayList<InviteSpotListModel.SpotInvitaionUserList>(); if (inviteSpotListModel.getSpotInvitaionUserList() != null) alstInviteSpot.addAll(inviteSpotListModel.getSpotInvitaionUserList()); bindSpotList(alstInviteSpot); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { if (reqCode == getActivity().getResources().getInteger(R.integer.reqCodeInviteSpot)) { isLoading = false; ToastHelper.getInstance().showToast(getActivity(), object.toString()); } } private void bindSpotList(ArrayList<InviteSpotListModel.SpotInvitaionUserList> listInvitedSpot) { if (listInvitedSpot != null && listInvitedSpot.size() > 0) { recyclerView.setVisibility(View.VISIBLE); txtNoRecords.setVisibility(View.GONE); InviteSpotAdapter mInviteSpotAdapter = (InviteSpotAdapter) recyclerView.getAdapter(); if (mInviteSpotAdapter != null && mInviteSpotAdapter.getItemCount() > 0) { /*if(isAllRecordsLoaded) adapter.notifyItemRemoved(listAppUsers.size());*/ mInviteSpotAdapter.setListItems(listInvitedSpot); } else { mInviteSpotAdapter = new InviteSpotAdapter(getActivity(), listInvitedSpot, totalCount); recyclerView.setAdapter(mInviteSpotAdapter); } } else { recyclerView.setVisibility(View.GONE); txtNoRecords.setVisibility(View.VISIBLE); } } public void clickEvent(View view) { switch (view.getId()) { case R.id.actionBarRightMenu: //Toggle Search icon if (edtSearch.getVisibility() == View.VISIBLE) { searchStr = ""; edtSearch.setText(searchStr); edtSearch.clearFocus(); edtSearch.setVisibility(View.GONE); txtActionBarTitle.setVisibility(View.VISIBLE); actionBarRightMenu.setVisibility(View.VISIBLE); //Set Menu icon actionBarMenu.setImageResource(R.mipmap.ic_menu); } else { edtSearch.setVisibility(View.VISIBLE); txtActionBarTitle.setVisibility(View.GONE); actionBarRightMenu.setVisibility(View.GONE); //Set back icon actionBarMenu.setImageResource(R.mipmap.ic_back); edtSearch.requestFocus(); Utils.getInstance().showKeyboard(edtSearch, getActivity()); } break; case R.id.actionBarMenu: handleBackPressEvent(false); break; } } private void resetVariables() { isLoading = false; pageIndex = Constants.FIRST_PAGE_NO; totalCount = 0; visibleItemCount = 0; totalItemCount = 0; pastVisiblesItems = 0; alstInviteSpot = new ArrayList<InviteSpotListModel.SpotInvitaionUserList>(); recyclerView.setAdapter(null); } private void handleBackPressEvent(boolean isHardwareBackButton) { if (isSearch) { isSearch = false; resetVariables(); actionBarRightMenu.performClick(); getSpotList(searchStr, pageIndex, true); } else if (edtSearch.getVisibility() == View.VISIBLE) { actionBarRightMenu.performClick(); } else if (homeActivity.isSlidingMenuOpen() || !isHardwareBackButton) // Open Sliding menu on click of menu icon homeActivity.toggleSlidingMenu(); else { homeActivity.popFragment();// homeActivity.pushFragments(new HomeFragment(),true,true,false); } } @Override public void onBackPressed() { handleBackPressEvent(true); /*if (isSearch) { isSearch = false; resetVariables(); actionBarRightMenu.performClick(); getSpotList(searchStr, pageIndex, true); } else if (edtSearch.getVisibility() == View.VISIBLE) { actionBarRightMenu.performClick(); } else if(homeActivity.isSlidingMenuOpen()) homeActivity.toggleSlidingMenu(); else homeActivity.popFragment();*/ } }11)InviteFriendsFragment.java==============================package com.eppico.fragments; import android.content.Intent;import android.os.Bundle;import android.os.Handler;import android.support.annotation.Nullable;import android.support.v7.widget.DividerItemDecoration;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.view.KeyEvent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.inputmethod.EditorInfo;import android.widget.CheckBox;import android.widget.CompoundButton;import android.widget.EditText;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; import com.eppico.R;import com.eppico.adapter.AppUserListAdapter;import com.eppico.api.ApiResponseListener;import com.eppico.api.RestClient;import com.eppico.models.AppUserModel;import com.eppico.models.CheckInUserModel;import com.eppico.models.CreateSpotModel;import com.eppico.models.InviteFriendModel;import com.eppico.utility.Constants;import com.eppico.utility.MyLog;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils;import com.facebook.CallbackManager;import com.facebook.FacebookCallback;import com.facebook.FacebookException;import com.facebook.share.model.GameRequestContent;import com.facebook.share.widget.GameRequestDialog; import org.json.JSONArray;import org.json.JSONObject; import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; import okhttp3.RequestBody;import retrofit2.Call;import retrofit2.Response; /** * Created by manisha on 13/12/16. */ public class InviteFriendsFragment extends BaseFragment implements ApiResponseListener { // XML Components EditText edtSearchUser; RecyclerView recyclerViewInviteSpot; TextView txtNoRecords; CheckBox checkboxInviteAll; View mainView; ArrayList<AppUserModel.User> listAppUsers; HashMap<Integer,AppUserModel.User> selectedUsersList; //CreateSpotModel createSpotModel; int spotId; Constants.FROM_SCREEN fromScreen; boolean isLoading=false,isSearch=false; int pageNo=Constants.FIRST_PAGE_NO; int pastVisiblesItems, visibleItemCount, totalItemCount; int totalCount,totalUserCount=-1; String searchStr=""; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle=getArguments(); if(bundle!=null) { // createSpotModel= (CreateSpotModel) bundle.getSerializable(getString(R.string.paramCreateSpotObj)); spotId= bundle.getInt(getString(R.string.extraSpotId)); if(bundle.containsKey(getString(R.string.extraFromScreen))) fromScreen= Constants.FROM_SCREEN.values()[bundle.getInt(getString(R.string.extraFromScreen))]; } initFBInviteDialog(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mainView = inflater.inflate(R.layout.fragment_invite_friends, container, false); init(); setSearchEvent(); return mainView; } public void init() { //getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // Set Sliding Menu disable homeActivity.setSlidingMenuEnable(false); homeActivity.setSelectedPositionInSlidingMenu(2); // Hide Keyboard on outside touch Utils.getInstance().setupOutSideTouchHideKeyboard(mainView.findViewById(R.id.parentView)); // Set Title TextView actionBarTitle= (TextView) mainView.findViewById(R.id.actionBarTitle); actionBarTitle.setText(getString(R.string.screenTitleInviteFriends)); // Setup Actionbar ImageView actionBarMenu= (ImageView) mainView.findViewById(R.id.actionBarMenu); ImageView actionBarRightMenu= (ImageView) mainView.findViewById(R.id.actionBarRightMenu); TextView actionBarRightButton= (TextView) mainView.findViewById(R.id.actionBarRightButton); actionBarMenu.setImageResource(R.mipmap.ic_back); actionBarRightMenu.setVisibility(View.GONE); actionBarRightButton.setVisibility(View.VISIBLE); actionBarRightButton.setText(getString(R.string.actionBarDone)); edtSearchUser= (EditText) mainView.findViewById(R.id.edtSearchUser); txtNoRecords= (TextView) mainView.findViewById(R.id.txtNoRecords); checkboxInviteAll= (CheckBox) mainView.findViewById(R.id.checkboxInviteAll); //edtSearch.clearFocus(); //setCheckBoxEvent(); // Hide Invite all button if user comes from My spot detail screen if(fromScreen== Constants.FROM_SCREEN.SPOT_DETAIL) checkboxInviteAll.setVisibility(View.GONE); else checkboxInviteAll.setVisibility(View.VISIBLE); initNSetRecyclerViewEvents(); new Handler().postDelayed(new Runnable() { @Override public void run() { if(listAppUsers!=null && listAppUsers.size()>0) bindUserList(listAppUsers); else getAppUsers(pageNo,true); } },getResources().getInteger(android.R.integer.config_mediumAnimTime)); } public void setSearchEvent() { edtSearchUser.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { searchStr=edtSearchUser.getText().toString().trim(); if (searchStr.length() > 0) { Utils.getInstance().hideKeyboard(v,getActivity()); isSearch=true; //pageNo=0; resetListVariables(); searchUser(searchStr,pageNo,true); } else { //Toast.makeText(getActivity(), getActivity().getString(R.string.searchMessage), Toast.LENGTH_SHORT).show(); ToastHelper.getInstance().showToast(getActivity(),getString(R.string.enterSearchText)); edtSearchUser.requestFocus(); } } return true; } }); } private void initNSetRecyclerViewEvents() { recyclerViewInviteSpot= (RecyclerView) mainView.findViewById(R.id.recyclerViewInviteSpot); final LinearLayoutManager layoutManager=new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false); recyclerViewInviteSpot.setLayoutManager(layoutManager); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerViewInviteSpot.getContext(),layoutManager.getOrientation()); // dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this,R.drawable.divider)); recyclerViewInviteSpot.addItemDecoration(dividerItemDecoration); recyclerViewInviteSpot.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); // if(dy > 0) //check for scroll down //{ visibleItemCount = layoutManager.getChildCount(); totalItemCount = layoutManager.getItemCount(); pastVisiblesItems = layoutManager.findFirstVisibleItemPosition(); if(!isLoading && totalCount>listAppUsers.size()) { if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) { //loading = false; MyLog.v("InviteFriends", "Last Item Wow !"); if(isSearch) searchUser(searchStr,pageNo,false); else getAppUsers(pageNo,false); //Do pagination.. i.e. fetch new data } } //} } }); } private void setCheckBoxEvent() { checkboxInviteAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { if(listAppUsers!=null && listAppUsers.size()>0) { if(selectedUsersList==null) selectedUsersList=new HashMap<Integer, AppUserModel.User>(); if(isChecked) { for(int i=0;i<listAppUsers.size();i++) selectedUsersList.put(listAppUsers.get(i).getUserId(),listAppUsers.get(i)); } else selectedUsersList=new HashMap<Integer, AppUserModel.User>(); } bindUserList(listAppUsers); } }); } private void setInviteAllCheckbox() { if(selectedUsersList!=null && selectedUsersList.size()==totalUserCount) checkboxInviteAll.setChecked(true); else checkboxInviteAll.setChecked(false); } @Override public void clickEvent(View v) { super.clickEvent(v); switch (v.getId()) { case R.id.actionBarMenu: // Back button onBackPressed(); break; case R.id.imgClear: edtSearchUser.setText(""); if(isSearch) { isSearch=false; resetListVariables(); getAppUsers(pageNo,true); } break; case R.id.txtInvite: try { if(v.getTag()!=null) { if(selectedUsersList==null) selectedUsersList=new HashMap<Integer, AppUserModel.User>(); AppUserModel.User appUser= (AppUserModel.User) v.getTag(); // User can not invite already invited user if(shouldAddToSelectedUserList(appUser)) { if(selectedUsersList.containsKey(appUser.getUserId())) selectedUsersList.remove(appUser.getUserId()); else selectedUsersList.put(appUser.getUserId(),appUser); //appUserModel.setSeleted(!appUserModel.isSeleted()); bindUserList(listAppUsers); setInviteAllCheckbox(); } } }catch (Exception e) { e.printStackTrace(); } break; case R.id.checkboxInviteAll: if(listAppUsers!=null && listAppUsers.size()>0) { if(selectedUsersList==null) selectedUsersList=new HashMap<Integer, AppUserModel.User>(); if(checkboxInviteAll.isChecked()) { for(int i=0;i<listAppUsers.size();i++) { AppUserModel.User user=listAppUsers.get(i); if(shouldAddToSelectedUserList(user)) selectedUsersList.put(user.getUserId(),user); } } else selectedUsersList=new HashMap<Integer, AppUserModel.User>(); } bindUserList(listAppUsers); break; case R.id.actionBarRightButton: if(selectedUsersList!=null && selectedUsersList.size()>0) callAPIOfInviteFriends(); else { if(fromScreen== Constants.FROM_SCREEN.CREATE_SPOT_MAP) ToastHelper.getInstance().showToast(getActivity(),getString(R.string.selectFriend)); else homeActivity.popFragment(); // If user comes from My spot detail screen dont check validation } break; case R.id.txtInviteFromFB: showFBInviteFriendsDialog(); break; } } GameRequestDialog requestDialog; CallbackManager callbackManagerGame; private void initFBInviteDialog() { callbackManagerGame = CallbackManager.Factory.create(); requestDialog = new GameRequestDialog(this); requestDialog.registerCallback(callbackManagerGame, new FacebookCallback<GameRequestDialog.Result>() { public void onSuccess(GameRequestDialog.Result result) { //String id = result.getId(); //MyLog.v("initGameRequest","onSuccess: " + result.getRequestRecipients().get(0)); /*ToastHelper.getInstance().showToast(getActivity(),getString(R.string.msgSpotInvitationSent),Toast.LENGTH_LONG); homeActivity.removeAllFragment(); homeActivity.pushFragments(new HomeFragment(),true,false,true);*/ redirectToNextScreen(); } public void onCancel() { MyLog.v("initGameRequest","onCancel: "); } public void onError(FacebookException error) { //MyLog.v("initGameRequest","onError: " + error.getMessage()); if(error.getMessage()!=null && error.getMessage().length()>0) ToastHelper.getInstance().showToast(getActivity(),error.getMessage(), Toast.LENGTH_LONG); } } ); } private void showFBInviteFriendsDialog() { GameRequestContent content = new GameRequestContent.Builder() .setMessage("Come play this level with me") .build(); requestDialog.show(content); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); /*if (mCallbackManager.onActivityResult(requestCode, resultCode, data)) { return; }*/ if (callbackManagerGame.onActivityResult(requestCode, resultCode, data)) { return; } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if(reqCode==getResources().getInteger(R.integer.reqCodeGetAppUserList)) { isLoading=false; pageNo++; AppUserModel appUserModel= (AppUserModel) response.body(); totalCount=appUserModel.getTotalCount(); /*Note: totalUserCount variable contain total number of user available on API. Initialize this variable only once and not initialize variable * at search time because in server there is 100 users but while search you get only 2 user at that time it totalUserCount initialize wrong */ if(totalUserCount==-1 && !isSearch) totalUserCount=appUserModel.getTotalCount(); if(listAppUsers==null) listAppUsers=new ArrayList<AppUserModel.User>(); if(checkboxInviteAll.isChecked() && appUserModel.getUser()!=null && appUserModel.getUser().size()>0) { for(int i=0;i<appUserModel.getUser().size();i++) { AppUserModel.User user=appUserModel.getUser().get(i); if(shouldAddToSelectedUserList(user)) selectedUsersList.put(user.getUserId(),user); } } if(appUserModel.getUser()!=null) { listAppUsers.addAll(appUserModel.getUser()); } /*if(pageNo==4) listUsers=null; if(listUsers!=null && listUsers.size()>0) listAppUsers.addAll((ArrayList<AppUserModel.User>) response.body()); else isAllRecordsLoaded=true;*/ bindUserList(listAppUsers); } else if(reqCode==getResources().getInteger(R.integer.reqCodeSearchAppUser)) { /*if(searchStr!=null && searchStr.length()>0 && pageNoSearch==FIRST_PAGE_NO) recyclerViewInviteSpot.setAdapter(null);*/ isLoading=false; pageNo++; AppUserModel appUserModel= (AppUserModel) response.body(); totalCount=appUserModel.getTotalCount(); if(listAppUsers==null) listAppUsers=new ArrayList<AppUserModel.User>(); if(appUserModel.getUser()!=null) { listAppUsers.addAll(appUserModel.getUser()); } bindUserList(listAppUsers); } else if(reqCode==getResources().getInteger(R.integer.reqCodeInviteFriends)) { redirectToNextScreen(); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { isLoading=false; ToastHelper.getInstance().showToast(getActivity(),object.toString()); } /**Redirect user as per he comes from screen*/ private void redirectToNextScreen() { if(fromScreen!=null) { switch (fromScreen) { case CREATE_SPOT_MAP: homeActivity.removeAllFragment(); ToastHelper.getInstance().showToast(getActivity(),getString(R.string.msgSpotInvitationSent),Toast.LENGTH_LONG); homeActivity.pushFragments(new HomeFragment(),true,false,true); break; case SPOT_DETAIL: // User invite form My spot /**Here onBackPressed() not called. Because of Search user and invite them at that time onBackPressed() called it will hide searchview * and get call get user app list API*/ ToastHelper.getInstance().showToast(getActivity(),getString(R.string.msgSpotInvitationSentDetail),Toast.LENGTH_LONG); homeActivity.popFragment(); break; } } } private boolean shouldAddToSelectedUserList(AppUserModel.User user) { if(user!=null) return user.getIsInvitedSpot()==Constants.INVITATION_STATUS.NOT_INVITED.ordinal(); return false; } /**Call API of get APP users*/ public void getAppUsers(int pageNo,boolean showDialog) { /*if(pageNo==FIRST_PAGE_NO) resetListVariables();*/ isLoading=true; Call<AppUserModel> objectCall = RestClient.getApiClient().getAppUserList(pageNo,homeActivity.loginModel.getUserId(),spotId); homeActivity.restClient.makeApiRequest(getActivity(),objectCall,this,getResources().getInteger(R.integer.reqCodeGetAppUserList),showDialog); } /**Call API of search users*/ public void searchUser(String strSearch,int pageNo,boolean showDialog) { /*if(pageNo==FIRST_PAGE_NO) resetListVariables();*/ isLoading=true; Call objectCall = RestClient.getApiClient().searchAppUser(strSearch,pageNo+"",spotId); homeActivity.restClient.makeApiRequest(getActivity(),objectCall,this,getResources().getInteger(R.integer.reqCodeSearchAppUser),showDialog); } /**Reset variables before search*/ private void resetListVariables() { isLoading=false; pageNo=Constants.FIRST_PAGE_NO; totalCount=0; visibleItemCount =0; totalItemCount = 0; pastVisiblesItems = 0; listAppUsers=new ArrayList<AppUserModel.User>(); recyclerViewInviteSpot.setAdapter(null); } private void callAPIOfInviteFriends() { /* Call<InviteFriendModel> objectCall = RestClient.getApiClient().inviteFriends("80","70","11111111","test name", "test ls name","testEmail@gmail.com","0");*/ /* Call<InviteFriendModel> objectCall = RestClient.getApiClient().inviteFriends(homeActivity.loginModel.getUserId()+"",createSpotModel.getSpotId()+"","11111111","test name","test ls name","testEmail@gmail.com", "0");*/ /*Call<InviteFriendModel> objectCall = RestClient.getApiClient().inviteFriends(homeActivity.loginModel.getUserId()+"",createSpotModel.getSpotId()+"","71","0"); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, InviteFriendsFragment.this, 10, true);*/ try { if(selectedUsersList!=null && selectedUsersList.size()>0) { /**Note: 0 = Invite All, 1= Invite selected friends*/ int invitationType=0; int spInviteType=0; //// 0 = App user, 1= Facebook user(But now we can not invite facebook users using API) JSONArray jArraySelectedFriends=new JSONArray(); if(!checkboxInviteAll.isChecked()) { invitationType=1; for (Map.Entry<Integer, AppUserModel.User> entry : selectedUsersList.entrySet()) { JSONObject jObjParam=new JSONObject(); jObjParam.put("spInviteFBId",entry.getKey()); /*JSONObject jObjParam=new JSONObject(); jObjParam.put("userId",homeActivity.loginModel.getUserId() +""); jObjParam.put("spotId",spotId+""); jObjParam.put("spInviteFBId",entry.getKey()); jObjParam.put("spInviteType","0");*/ // 0 = App user, 1= Facebook user(But now we can not invite facebook users using API) jArraySelectedFriends.put(jObjParam); } } Call<List<InviteFriendModel>> objectCall = RestClient.getApiClient().inviteFriends(spotId+"",/*homeActivity.loginModel.getUserId() +"",*/invitationType+"",spInviteType+"",jArraySelectedFriends.toString()); // Call<List<InviteFriendModel>> objectCall = RestClient.getApiClient().inviteFriends(jsonArray.toString()); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, InviteFriendsFragment.this, getResources().getInteger(R.integer.reqCodeInviteFriends), true); } }catch (Exception e) { e.printStackTrace(); } /*try { JSONArray jsonArray=new JSONArray(); JSONObject jObjParam=new JSONObject(); jObjParam.put("userId",homeActivity.loginModel.getUserId() +""); jObjParam.put("spotId",createSpotModel.getSpotId()+""); jObjParam.put("spInviteFBId","80"); jObjParam.put("spInviteType","0"); jsonArray.put(jObjParam); RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),jsonArray.toString()); Call<InviteFriendModel> objectCall = RestClient.getApiClient().inviteFriends(body); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, InviteFriendsFragment.this, 10, true); }catch (Exception e) { e.printStackTrace(); }*/ } private void bindUserList(ArrayList<AppUserModel.User> listAppUsers) { if(listAppUsers!=null && listAppUsers.size()>0) { /*if(searchStr!=null && searchStr.length()>0 && pageNoSearch==1) recyclerViewInviteSpot.setAdapter(null);*/ recyclerViewInviteSpot.setVisibility(View.VISIBLE); txtNoRecords.setVisibility(View.GONE); AppUserListAdapter adapter= (AppUserListAdapter) recyclerViewInviteSpot.getAdapter(); if(adapter!=null && adapter.getItemCount()>0) { adapter.setListItems(listAppUsers,selectedUsersList); /*if(isAllRecordsLoaded) adapter.notifyItemRemoved(listAppUsers.size());*/ } else { adapter=new AppUserListAdapter(getActivity(),listAppUsers,selectedUsersList,totalCount); recyclerViewInviteSpot.setAdapter(adapter); } } else { recyclerViewInviteSpot.setVisibility(View.GONE); txtNoRecords.setVisibility(View.VISIBLE); } } @Override public void onBackPressed() { if(isSearch) { isSearch=false; edtSearchUser.setText(""); resetListVariables(); getAppUsers(pageNo,true); } else homeActivity.popFragment(); } }12)InviteSpotDetailFragment.java=====================================package com.eppico.fragments; import android.app.Activity;import android.app.Dialog;import android.content.Context;import android.content.Intent;import android.content.pm.PackageManager;import android.location.Location;import android.net.Uri;import android.os.Bundle;import android.os.Handler;import android.provider.MediaStore;import android.support.annotation.NonNull;import android.support.annotation.Nullable;import android.support.v4.app.ActivityCompat;import android.support.v4.app.Fragment;import android.support.v4.content.ContextCompat;import android.support.v7.widget.GridLayoutManager;import android.support.v7.widget.RecyclerView;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import com.bumptech.glide.Glide;import com.eppico.R;import com.eppico.activity.ImageCropActivity;import com.eppico.adapter.InviteSpotDetailAdapter;import com.eppico.api.ApiResponseListener;import com.eppico.api.RestClient;import com.eppico.fabmenu.FloatingActionMenu;import com.eppico.interfaces.LocationUpdateListener;import com.eppico.models.BaseModel;import com.eppico.models.CheckedInSpotModel;import com.eppico.models.CommentListModel;import com.eppico.models.FollowSpotModel;import com.eppico.models.InviteSpotDetailModel;import com.eppico.utility.Constants;import com.eppico.utility.CustomDialog;import com.eppico.utility.FileUtils;import com.eppico.utility.MyLog;import com.eppico.utility.PermissionUtil;import com.eppico.utility.PrefHelper;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils;import com.eppico.widgets.ShapedImageView; import java.io.File;import java.util.ArrayList; import retrofit2.Call;import retrofit2.Response; /** * Created by manisha on 19/12/16. */ public class InviteSpotDetailFragment extends BaseFragment implements ApiResponseListener { View view; private RecyclerView recyclerSpot; private InviteSpotDetailAdapter mInviteSpotPostAdapter; private TextView txtLeaderShip; private TextView txtNoRecords,txtInviteFriends,txtFollow; View dividerInviteFriend; ImageView imgEdit; LinearLayout linBottomTab; private ArrayList<InviteSpotDetailModel.PostMediaDetails> alstSpotDetail; // private String spotId = ""; int pageNo = Constants.FIRST_PAGE_NO; int totalCount = 0; InviteSpotDetailModel mInviteSpotDetailModel; boolean isLoading = false; int pastVisiblesItems, visibleItemCount, totalItemCount; FloatingActionMenu fabMenu; Uri outputFileUri; final int REQ_CODE_PERMISSION_CAMERA=40; final int REQ_CODE_PERMISSION_GALLERY=41; Constants.POST_MEDIA_TYPE postMediaType; GridLayoutManager gridManager; private ArrayList<CommentListModel> alstComment; //private InviteSpotListModel.SpotInvitaionUserList spotModel; private int spotId; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle=getArguments(); if(bundle!=null) { spotId=bundle.getInt(getString(R.string.extraSpotId)); /*String strSpotModel=bundle.getString(getString(R.string.extraSpotModel)); if(strSpotModel.length()>0) { spotModel= (InviteSpotListModel.SpotInvitaionUserList) InviteSpotListModel.toModelClass(strSpotModel,InviteSpotListModel.SpotInvitaionUserList.class); }*/ } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_spot_detail, container, false); inItView(); initFabMenu(); return view; } private void inItView() { // Bundle mBundle = getArguments();// spotId = mBundle.getString(getResources().getString(R.string.inviteSpotID)); //Disable Sliding menu homeActivity.setSlidingMenuEnable(false); txtNoRecords = (TextView) view.findViewById(R.id.txtNoRecords); imgEdit = (ImageView) view.findViewById(R.id.imgEdit); dividerInviteFriend = view.findViewById(R.id.dividerInviteFriend); txtInviteFriends = (TextView) view.findViewById(R.id.txtInviteFriends); txtLeaderShip = (TextView) view.findViewById(R.id.txtLeaderShip); txtFollow = (TextView) view.findViewById(R.id.txtFollow); linBottomTab = (LinearLayout) view.findViewById(R.id.linBottomTab); initNSetRecyclerViewEvents(); new Handler().postDelayed(new Runnable() { @Override public void run() { resetListVariables(); getSpotDetail(pageNo, true); } }, 400); } private void initNSetRecyclerViewEvents() { recyclerSpot = (RecyclerView) view.findViewById(R.id.recyclerViewSpotDetail); gridManager = new GridLayoutManager(getActivity(), 4); alstSpotDetail = new ArrayList<>(); gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { if (position == 0) { return 4; } else if (position >= (alstSpotDetail.size() + 1)) { return 4; } else { return 1; } } }); recyclerSpot.setLayoutManager(gridManager); recyclerSpot.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); //if (dy > 0) //check for scroll down //{ visibleItemCount = gridManager.getChildCount(); totalItemCount = gridManager.getItemCount(); pastVisiblesItems = gridManager.findFirstVisibleItemPosition(); if (!isLoading && totalCount > alstSpotDetail.size()) { if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) { getSpotDetail(pageNo, false); } } //} } }); } /**Setup view according Spot. * 1. Show FAB Menu * 2. Show Edit icon id spot is logged in user * 3. Hide Invite Friends button if spot is inactive * 4. Hide Add button if spot is inactive*/ private void setViewForSpot() { if(mInviteSpotDetailModel==null) return; //Set Visibility of FAB Menu fabMenu.setVisibility(View.VISIBLE); // Make Visible bottom tab layout linBottomTab.setVisibility(View.VISIBLE); //Show Edit icon if spot is logged in user if(mInviteSpotDetailModel.getUserId()==homeActivity.loginModel.getUserId()) imgEdit.setVisibility(View.VISIBLE); else imgEdit.setVisibility(View.GONE); //Show Invite Friend button only for MySpot active if(mInviteSpotDetailModel.getUserId()==homeActivity.loginModel.getUserId() && isSpotActive()) { txtInviteFriends.setVisibility(View.VISIBLE); dividerInviteFriend.setVisibility(View.VISIBLE); } else { txtInviteFriends.setVisibility(View.GONE); dividerInviteFriend.setVisibility(View.GONE); } //Hide Add button if spot is inactive if(isSpotActive()) fabMenu.setVisibility(View.VISIBLE); else fabMenu.setVisibility(View.GONE); setSpotFollowStatusNCounts(); } /**Return true if spot is active otherwise return false*/ private boolean isSpotActive() { if(mInviteSpotDetailModel!=null) { if(mInviteSpotDetailModel.getIsActive()==Constants.SPOT_ACTIVE_STATUS.ACITVE.ordinal()) // 1= Active 0= Inactive return true; } return false; } /**Set Follow button status, set Followers count and Checked in user count*/ private void setSpotFollowStatusNCounts() { if(mInviteSpotDetailModel.getIsSpotFollow()==Constants.FOLLOW_STATUS.FOLLOW.ordinal()) { txtFollow.setText(getString(R.string.btnFollowingSpotDetail)); txtFollow.setTextColor(ContextCompat.getColor(getActivity(),R.color.txtSelectedColor)); txtFollow.setCompoundDrawablesWithIntrinsicBounds(0,R.mipmap.ic_follow_selected, 0, 0); } else { txtFollow.setText(getString(R.string.btnFollowSpotDetail)); txtFollow.setTextColor(ContextCompat.getColor(getActivity(),R.color.txtNormalColor)); txtFollow.setCompoundDrawablesWithIntrinsicBounds(0,R.mipmap.ic_follow, 0, 0); } // Update followers count and don't show no record message bindPostList(alstSpotDetail,false); } /** * Reset variables before search */ private void resetListVariables() { isLoading = false; pageNo = Constants.FIRST_PAGE_NO; totalCount = 0; visibleItemCount = 0; totalItemCount = 0; pastVisiblesItems = 0; alstSpotDetail = new ArrayList<InviteSpotDetailModel.PostMediaDetails>(); recyclerSpot.setAdapter(null); } private void initFabMenu() { fabMenu = (FloatingActionMenu) view.findViewById(R.id.fabMenu); fabMenu.setClosedOnTouchOutside(true); fabMenu.setOnMenuButtonClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(fabMenu.isOpened()) fabMenu.toggle(true); else callCheckedInSpotApi();// fabMenu.toggle(true); } }); } @Override public void clickEvent(View v) { super.clickEvent(v); switch (v.getId()) { case R.id.txtCheckInUserCount: if(isSpotActive()) { Fragment fragment = new CheckInUserFragment(); Bundle mBundle = new Bundle(); mBundle.putString("CheckInSpotId",spotId+""); fragment.setArguments(mBundle); homeActivity.pushFragments(fragment, true, false, true); } else CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.msgSpotIsInactive)); break; case R.id.txtFollowersCount: if(isSpotActive()) { FollowersListFragment followersListFragment = new FollowersListFragment(); Bundle bundleFollowers = new Bundle(); bundleFollowers.putInt(getString(R.string.extraFromScreen), Constants.FROM_SCREEN.SPOT_DETAIL.ordinal()); bundleFollowers.putInt(getString(R.string.extraSpotId), spotId); followersListFragment.setArguments(bundleFollowers); homeActivity.pushFragments(followersListFragment, true, false, true); } else CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.msgSpotIsInactive)); break; case R.id.imgBack: onBackPressed(); break; case R.id.fabGallery: postMediaType= Constants.POST_MEDIA_TYPE.IMAGE; openGallery(); fabMenu.toggle(true); break; case R.id.fabCamera: postMediaType= Constants.POST_MEDIA_TYPE.IMAGE; openCameraForCaptureImage(); fabMenu.toggle(true); break; case R.id.fabVideo: postMediaType= Constants.POST_MEDIA_TYPE.VIDEO; openCameraForVideo(); fabMenu.toggle(true); break; case R.id.lytPost: PostDetailFragment fragment1 = new PostDetailFragment(); InviteSpotDetailModel.PostMediaDetails postDetail = (InviteSpotDetailModel.PostMediaDetails) v.getTag(); int postId = postDetail.getPostId(); Bundle mBundle1 = new Bundle(); mBundle1.putInt(getString(R.string.extraFromScreen), Constants.FROM_SCREEN.SPOT_DETAIL.ordinal()); mBundle1.putString(getResources().getString(R.string.extraPostId), String.valueOf(postId)); mBundle1.putString(getResources().getString(R.string.extraSpotId), spotId+""); mBundle1.putString(getResources().getString(R.string.extraMediaId), ""+postDetail.getMediaID());// mBundle1.putInt(getResources().getString(R.string.extraIsActive),mInviteSpotDetailModel.getIsActive()); fragment1.setArguments(mBundle1); homeActivity.pushFragments(fragment1, true, false, true); break; case R.id.imgEdit: EditSpotFragment editSpotFragment = new EditSpotFragment(); Bundle bundle = new Bundle(); bundle.putString(getResources().getString(R.string.extraSpotModel), BaseModel.toJson(mInviteSpotDetailModel)); editSpotFragment.setArguments(bundle); homeActivity.pushFragments(editSpotFragment, true, false, true); break; case R.id.txtInviteFriends: Bundle bundleInviteFriend=new Bundle(); bundleInviteFriend.putInt(getString(R.string.extraSpotId),spotId); bundleInviteFriend.putInt(getString(R.string.extraFromScreen), Constants.FROM_SCREEN.SPOT_DETAIL.ordinal()); InviteFriendsFragment inviteFriendsFragment=new InviteFriendsFragment(); inviteFriendsFragment.setArguments(bundleInviteFriend); homeActivity.pushFragments(inviteFriendsFragment,true,false,true); break; case R.id.txtFollow: if(isSpotActive()) { if(mInviteSpotDetailModel.getIsSpotFollow()==Constants.FOLLOW_STATUS.FOLLOW.ordinal()) showUnFollowDialog(); else callFollowSpotAPI(Constants.FOLLOW_STATUS.FOLLOW); } else CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.msgSpotIsInactive)); break; case R.id.txtLeaderShip: if(alstSpotDetail != null && alstSpotDetail.size() > 0) { LeaderShipBoardFragment leaderShipFragment = new LeaderShipBoardFragment(); Bundle bundle1 = new Bundle(); bundle1.putString(getResources().getString(R.string.extraSpotId), "" + spotId); bundle1.putInt(getString(R.string.extraLeaderShipType), Constants.LEADER_SHIP_TYPE.LEADERSHIP.ordinal()); leaderShipFragment.setArguments(bundle1); homeActivity.pushFragments(leaderShipFragment, true, false, true); }else{ CustomDialog.getInstance().showMessageDialog(getActivity(),getResources().getString(R.string.be_the_leader_by_adding_posts)); } break; } } private void openCameraForCaptureImage() { /*if(ActivityCompat.checkSelfPermission(getActivity(),Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { MyLog.v("openCameraForCaptureImage","Write Storage Permission: "); }*/ ArrayList<String> listPermissionsNeed=PermissionUtil.getInstance().getCameraPermissionsList(); if(checkCameraPermissions(listPermissionsNeed,REQ_CODE_PERMISSION_CAMERA,true)) { outputFileUri= FileUtils.getInstance().getFileUri(getActivity(), FileUtils.MEDIA_TYPE.PICTURE); Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);// captureIntent.putExtra("return-data", true); startActivityForResult(captureIntent, Constants.REQ_CODE_CAPTURE_IMAGE); } } private void openCameraForVideo() { ArrayList<String> listPermissionsNeed=PermissionUtil.getInstance().getCameraPermissionsList(); if(checkCameraPermissions(listPermissionsNeed,REQ_CODE_PERMISSION_CAMERA,true)) { ToastHelper.getInstance().showToast(getActivity(),getString(R.string.msgVideoLimit),Toast.LENGTH_LONG); outputFileUri= FileUtils.getInstance().getFileUri(getActivity(), FileUtils.MEDIA_TYPE.VIDEO); Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 30); // 30 Seconds startActivityForResult(intent, Constants.REQ_CODE_RECORD_VIDEO); } } 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); } } 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; } @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 { if(postMediaType== Constants.POST_MEDIA_TYPE.IMAGE) openCameraForCaptureImage(); else openCameraForVideo(); } 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; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == Constants.REQ_CODE_CAPTURE_IMAGE && resultCode == Activity.RESULT_OK ) { if(outputFileUri!=null) { Intent intent = new Intent(getActivity(), ImageCropActivity.class); /*Post Detail Screen Post Image width=1000 Height=720. According that dimension below ratio is passed*/ intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 25); intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 18); intent.putExtra(ImageCropActivity.EXTRA_IMAGE_PATH, outputFileUri.getPath()); startActivityForResult(intent,Constants.REQ_CODE_CROP_IMAGE); } else ToastHelper.getInstance().showToast(getActivity(),getString(R.string.msgFileNotFound)); } else if (requestCode == Constants.REQ_CODE_RECORD_VIDEO && resultCode == Activity.RESULT_OK ) { if(outputFileUri!=null) { Bundle fragBundle=new Bundle(); fragBundle.putString(getString(R.string.extraPostMediaPath),outputFileUri.getPath()); fragBundle.putString(getString(R.string.extraSpotId),spotId+""); fragBundle.putInt(getString(R.string.extraPostMediaType),Constants.POST_MEDIA_TYPE.VIDEO.ordinal()); AddPostFragment addPostFragment=new AddPostFragment(); addPostFragment.setArguments(fragBundle); homeActivity.pushFragments(addPostFragment,true,false,true); } else ToastHelper.getInstance().showToast(getActivity(),getString(R.string.msgFileNotFound)); } 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[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = getActivity().getContentResolver().query(selectedImageUri, projection, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(projection[0]); String picturePath = cursor.getString(columnIndex); cursor.close();*/ String picturePath = Utils.getInstance().getRealPathFromURI(getActivity(),selectedImageUri); //Copy Original File to app media folder String copiedFilepath=FileUtils.getInstance().copyFile(picturePath,FileUtils.getInstance().getFilePath(getActivity(), FileUtils.MEDIA_TYPE.PICTURE)); Intent intent = new Intent(getActivity(), ImageCropActivity.class); intent.putExtra(ImageCropActivity.EXTRA_X_RATIO, 25); intent.putExtra(ImageCropActivity.EXTRA_Y_RATIO, 18); intent.putExtra(ImageCropActivity.EXTRA_IMAGE_PATH, copiedFilepath); startActivityForResult(intent,Constants.REQ_CODE_CROP_IMAGE); } else ToastHelper.getInstance().showToast(getActivity(),getString(R.string.msgFileNotFound)); } else if(requestCode==Constants.REQ_CODE_CROP_IMAGE && resultCode == Activity.RESULT_OK && data!=null) { Bundle bundle=data.getExtras(); if(bundle!=null) { String croppedImagePath=bundle.getString(ImageCropActivity.EXTRA_IMAGE_PATH); if(Utils.getInstance().getFileSizeInMb(new File(croppedImagePath))>2) { // ToastHelper.getInstance().showToast(getActivity(),getString(R.string.msgFileSize)); CustomDialog.getInstance().showMessageDialog(getActivity(),getString(R.string.msgFileSize)); return; } MyLog.v("Cropped Image", "Cropped Image Path: " + croppedImagePath); Bundle fragBundle=new Bundle(); fragBundle.putString(getString(R.string.extraPostMediaPath),croppedImagePath); fragBundle.putString(getString(R.string.extraSpotId),spotId+""); fragBundle.putInt(getString(R.string.extraPostMediaType),Constants.POST_MEDIA_TYPE.IMAGE.ordinal()); AddPostFragment addPostFragment=new AddPostFragment(); addPostFragment.setArguments(fragBundle); homeActivity.pushFragments(addPostFragment,true,false,true); } else ToastHelper.getInstance().showToast(getActivity(),getString(R.string.msgFileNotFound)); } } private void callCheckedInSpotApi() { homeActivity.getCurrentLocation(new LocationUpdateListener() { @Override public void onLocationUpdate(Location location) { //printDistance(location); Call<CheckedInSpotModel> objectCall = RestClient.getApiClient().checkedInSpot(spotId+"",/*homeActivity.loginModel.getUserId()+"",*/location.getLatitude()+"",location.getLongitude()+""); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, InviteSpotDetailFragment.this, getActivity().getResources().getInteger(R.integer.reqCodeCheckedInSpot), true); } @Override public void onLocationPermissionDeny() { ToastHelper.getInstance().showToast(getActivity(),getString(R.string.allowLocatonPermissionToAddPost),Toast.LENGTH_LONG); } @Override public void onGPSRequestDeny() { ToastHelper.getInstance().showToast(getActivity(),getString(R.string.enableGPSToAddPost), Toast.LENGTH_LONG); } }); } private void printDistance(Location location) { //TODO Temporary store lat-lng into preference String strLatLong[]=mInviteSpotDetailModel.getSpotLatLong().split(","); double latitude = Double.parseDouble(strLatLong[0]); double longitude = Double.parseDouble(strLatLong[1]); if(latitude>0 && longitude>0) { Location endPoint=new Location("locationA"); endPoint.setLatitude(latitude); endPoint.setLongitude(longitude); double distance=location.distanceTo(endPoint); ToastHelper.getInstance().showToast(getActivity(),"Spot Radius: " + mInviteSpotDetailModel.getRadiusId() +" Distance (In Meter): " + distance + " Acuracy: " + location.getAccuracy(),Toast.LENGTH_LONG); MyLog.v("LocationManager","Spot Radius: " + mInviteSpotDetailModel.getRadiusId() +" Distance(In Meter): "+ distance); } } private void bindPostList(ArrayList<InviteSpotDetailModel.PostMediaDetails> listInviteSpot, boolean showNoRecordMsg) { if (listInviteSpot != null && listInviteSpot.size() > 0) { recyclerSpot.setVisibility(View.VISIBLE); txtNoRecords.setVisibility(View.GONE); InviteSpotDetailAdapter adapter = (InviteSpotDetailAdapter) recyclerSpot.getAdapter(); if (adapter != null && adapter.getItemCount() > 0) { // adapter.notifyItemRemoved(alstSpotDetail.size()); adapter.setListItems(listInviteSpot,mInviteSpotDetailModel); } else { adapter = new InviteSpotDetailAdapter(getActivity(), listInviteSpot, mInviteSpotDetailModel, totalCount); recyclerSpot.setAdapter(adapter); } } else { //Show No record message only first time if(showNoRecordMsg) ToastHelper.getInstance().showToast(getActivity(),getString(R.string.msgNoPostFound),Toast.LENGTH_LONG); resetListVariables(); recyclerSpot.setVisibility(View.VISIBLE); txtNoRecords.setVisibility(View.GONE);// InviteSpotDetailModel.PostMediaDetails model = new InviteSpotDetailModel.PostMediaDetails();// listInviteSpot.add(model); InviteSpotDetailAdapter adapter = new InviteSpotDetailAdapter(getActivity(), listInviteSpot, mInviteSpotDetailModel, totalCount); recyclerSpot.setAdapter(adapter); } } public void getSpotDetail(int pageNo, boolean showDialog) { isLoading = true; Call<InviteSpotDetailModel> objectCall = RestClient.getApiClient().inviteSpotDetail(/*homeActivity.loginModel.getUserId()+"",*/spotId+"", String.valueOf(pageNo)); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getResources().getInteger(R.integer.reqCodeSpotDetail), showDialog); } /**Show UnFollow Spot confirmation dialog with spot image and spot name*/ private void showUnFollowDialog() { try { final Dialog dialog = new Dialog(getActivity(), R.style.DialogTheme); dialog.setCancelable(true); LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.dialog_unfollow, null); ShapedImageView imgUser = (ShapedImageView) view.findViewById(R.id.imgUser); TextView txtUserName = (TextView) view.findViewById(R.id.txtUserName); Button btnCancel = (Button) view.findViewById(R.id.btnCancel); Button btnUnfollow = (Button) view.findViewById(R.id.btnUnfollow); imgUser.setShapeMode(ShapedImageView.SHAPE_MODE_ROUND_RECT); // Set font type btnCancel.setTypeface(homeActivity.appInstance.fontRobotoRegular); btnUnfollow.setTypeface(homeActivity.appInstance.fontRobotoRegular); txtUserName.setText(getString(R.string.btnUnfollow) + " " + mInviteSpotDetailModel.getSpotName()+ "?"); Glide.with(getActivity()) .load(mInviteSpotDetailModel.getSpotImage()) .placeholder(R.mipmap.spot_default_img) .error(R.mipmap.spot_default_img) .into(imgUser); dialog.setContentView(view); /** Set Dialog width match parent */ dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); btnUnfollow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); callFollowSpotAPI(Constants.FOLLOW_STATUS.UNFOLLOW); } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); if (dialog.isShowing()) dialog.dismiss(); dialog.show(); } catch (Exception e) { e.printStackTrace(); } } public void callFollowSpotAPI(Constants.FOLLOW_STATUS followStatus) { /*Constants.FOLLOW_STATUS followStatus; if(mInviteSpotDetailModel.getIsSpotFollow()==Constants.FOLLOW_STATUS.FOLLOW.ordinal()) followStatus= Constants.FOLLOW_STATUS.UNFOLLOW; else followStatus= Constants.FOLLOW_STATUS.FOLLOW;*/ Call<FollowSpotModel> objectCall = RestClient.getApiClient().followSpot(spotId+"", /*homeActivity.loginModel.getUserId()+"",*/mInviteSpotDetailModel.getSpotFollowerId()+"",followStatus.ordinal()+""); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getResources().getInteger(R.integer.reqCodeFollowSpot), true); } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if (reqCode == getResources().getInteger(R.integer.reqCodeSpotDetail)) { mInviteSpotDetailModel = (InviteSpotDetailModel) response.body(); totalCount = mInviteSpotDetailModel.getPostMedia().getTotalCount(); isLoading = false; pageNo++; if (alstSpotDetail == null) alstSpotDetail = new ArrayList<InviteSpotDetailModel.PostMediaDetails>(); if (mInviteSpotDetailModel.getPostMedia().getPostMediaDetails() != null) { { alstSpotDetail.addAll(mInviteSpotDetailModel.getPostMedia().getPostMediaDetails()); } } bindPostList(alstSpotDetail,true); setViewForSpot(); } else if(reqCode==getResources().getInteger(R.integer.reqCodeCheckedInSpot)) { CheckedInSpotModel checkedInSpotModel= (CheckedInSpotModel) response.body(); if(checkedInSpotModel.getAllow()) { fabMenu.toggle(true); mInviteSpotDetailModel.setSpotNoOfUsers(checkedInSpotModel.getTotalCheckInUser()); // Set checked in user count setSpotFollowStatusNCounts(); return; } CustomDialog.getInstance().showMessageDialog(getActivity(),getString(R.string.msgGotoSpotLocation)); } else if(reqCode==getResources().getInteger(R.integer.reqCodeFollowSpot)) { FollowSpotModel followSpotModel= (FollowSpotModel) response.body(); mInviteSpotDetailModel.setIsSpotFollow(followSpotModel.getSpotIsFollowing()); // Set Spot following status mInviteSpotDetailModel.setSpotFollowerId(followSpotModel.getSpotFollowerId()); // Set Spot followers id mInviteSpotDetailModel.setSpotFollowings(followSpotModel.getSpotFollowersCount()); // Set Followers count setSpotFollowStatusNCounts(); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { ToastHelper.getInstance().showToast(getActivity(),object.toString()); } @Override public void onBackPressed() { resetListVariables(); homeActivity.popFragment(); } }13)LeaderShipBoardFragment.java=======================================package com.eppico.fragments; import android.graphics.Typeface;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v7.widget.DividerItemDecoration;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast; import com.bumptech.glide.Glide;import com.eppico.R;import com.eppico.adapter.AppUserListAdapter;import com.eppico.adapter.LeaderShipBoardAdapter;import com.eppico.api.RestClient;import com.eppico.interfaces.RecyclerViewItemClickListener;import com.eppico.models.AppUserModel;import com.eppico.models.InviteSpotListModel;import com.eppico.models.LeadershipBoardModel;import com.eppico.utility.Constants;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils; import java.util.ArrayList;import java.util.List; import retrofit2.Call;import retrofit2.Response; /** * Created by manisha on 30/12/16. */ public class LeaderShipBoardFragment extends BaseFragment { View view; private RecyclerView recyclerView; private TextView txtNoRecords, txtActionBarTitle; Constants.LEADER_SHIP_TYPE strType; private ArrayList<LeadershipBoardModel> alstLeaderShip, alstToppers, alstLeaderShipList; String spotId; private TextView txtLeaderOneName, txtLeaderOneCount, txtLeaderTwoName, txtLeaderTwoCount, txtLeaderthreeName, txtLeaderThreeCount; private LinearLayout lytOne, lytTwo, lytThree, lytTopView; private ImageView imgLeaderOne, imgLeaderTwo, imgLeaderThree; LeaderShipBoardAdapter adapter; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getArguments(); if (bundle != null) { spotId = bundle.getString(getResources().getString(R.string.extraSpotId)); strType = Constants.LEADER_SHIP_TYPE.values()[bundle.getInt(getString(R.string.extraLeaderShipType), Constants.LEADER_SHIP_TYPE.LEADERSHIP.ordinal())]; } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fregment_leadership, container, false); inItData(); getLeadershipData(spotId, true); inItRecyclerView(); return view; } private void inItData() { txtActionBarTitle = (TextView) view.findViewById(R.id.actionBarTitle); if (strType == Constants.LEADER_SHIP_TYPE.LEADERSHIP) { txtActionBarTitle.setText(getString(R.string.leader_ship_board)); } else { txtActionBarTitle.setText(getString(R.string.championship)); } // Setup Actionbar ImageView actionBarMenu = (ImageView) view.findViewById(R.id.actionBarMenu); ImageView actionBarRightMenu = (ImageView) view.findViewById(R.id.actionBarRightMenu); TextView actionBarRightButton = (TextView) view.findViewById(R.id.actionBarRightButton); actionBarMenu.setImageResource(R.mipmap.ic_back); actionBarRightMenu.setVisibility(View.GONE); actionBarRightButton.setVisibility(View.INVISIBLE); actionBarRightButton.setText(getString(R.string.actionBarDone)); txtLeaderOneName = (TextView) view.findViewById(R.id.txtLeaderOneName); txtLeaderOneCount = (TextView) view.findViewById(R.id.txtLeaderOneCount); txtLeaderTwoName = (TextView) view.findViewById(R.id.txtLeaderTwoName); txtLeaderTwoCount = (TextView) view.findViewById(R.id.txtLeaderTwoCount); txtLeaderthreeName = (TextView) view.findViewById(R.id.txtLeaderThreeName); txtNoRecords = (TextView) view.findViewById(R.id.txtNoRecords); txtLeaderthreeName.setTypeface(homeActivity.appInstance.fontRobotoLight); txtLeaderThreeCount = (TextView) view.findViewById(R.id.txtLeaderThreeCount); imgLeaderOne = (ImageView) view.findViewById(R.id.imgLeaderOne); imgLeaderTwo = (ImageView) view.findViewById(R.id.imgLeaderTwo); imgLeaderThree = (ImageView) view.findViewById(R.id.imgLeaderThree); lytOne = (LinearLayout) view.findViewById(R.id.lytLeaderOne); lytTwo = (LinearLayout) view.findViewById(R.id.lytLeaderTwo); lytThree = (LinearLayout) view.findViewById(R.id.lytLeaderThree); lytTopView = (LinearLayout) view.findViewById(R.id.lytTopView); } public void inItRecyclerView() { recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL)); alstLeaderShipList = new ArrayList<>(); } private void getLeadershipData(String spotId, boolean showDialog) { if (homeActivity.loginModel != null) { Call<List<LeadershipBoardModel>> objectCall = null; objectCall = RestClient.getApiClient().leadershipBoard(spotId); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeLeaderShipBoard), showDialog); } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if (reqCode == getActivity().getResources().getInteger(R.integer.reqCodeLeaderShipBoard)) { lytTopView.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.VISIBLE); txtNoRecords.setVisibility(View.GONE); alstLeaderShip = new ArrayList<>(); alstLeaderShipList = new ArrayList<>(); alstLeaderShip.addAll((ArrayList<LeadershipBoardModel>) response.body()); if (alstLeaderShip.size() > 0) { if (alstLeaderShip.size() > 3) { lytTopView.setVisibility(View.VISIBLE); recyclerView.setVisibility(View.VISIBLE); for (int i = 3; i < alstLeaderShip.size(); i++) { alstLeaderShipList.add(alstLeaderShip.get(i)); } } else { recyclerView.setVisibility(View.GONE); } setToppers(alstLeaderShip); adapter = new LeaderShipBoardAdapter(getActivity(), alstLeaderShipList); recyclerView.setAdapter(adapter); } else { lytTopView.setVisibility(View.GONE); recyclerView.setVisibility(View.GONE); txtNoRecords.setVisibility(View.VISIBLE); } } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { if (reqCode == getActivity().getResources().getInteger(R.integer.reqCodeLeaderShipBoard)) { lytTopView.setVisibility(View.GONE); recyclerView.setVisibility(View.GONE); ToastHelper.getInstance().showToast(getActivity(), object.toString()); } } public void setToppers(ArrayList<LeadershipBoardModel> alstLeaderShip) { if (alstLeaderShip != null && alstLeaderShip.size() > 0) { if (alstLeaderShip != null && alstLeaderShip.size() == 1) { recyclerView.setVisibility(View.GONE); lytOne.setVisibility(View.VISIBLE); lytTwo.setVisibility(View.GONE); lytThree.setVisibility(View.GONE); setLeaderOne(alstLeaderShip); } else if (alstLeaderShip != null && alstLeaderShip.size() == 2) { recyclerView.setVisibility(View.GONE); lytOne.setVisibility(View.VISIBLE); lytTwo.setVisibility(View.VISIBLE); lytThree.setVisibility(View.GONE); setLeaderOne(alstLeaderShip); setLeaderTwo(alstLeaderShip); } else if (alstLeaderShip != null && alstLeaderShip.size() >= 3) { lytOne.setVisibility(View.VISIBLE); lytTwo.setVisibility(View.VISIBLE); lytThree.setVisibility(View.VISIBLE); setLeaderOne(alstLeaderShip); setLeaderTwo(alstLeaderShip); setLeaderThree(alstLeaderShip); } } else { lytOne.setVisibility(View.GONE); lytTwo.setVisibility(View.GONE); lytThree.setVisibility(View.GONE); recyclerView.setVisibility(View.GONE); } } public void setLeaderOne(ArrayList<LeadershipBoardModel> alstLeaderShip) { if (Utils.validateString(alstLeaderShip.get(0).getFirstName())) { txtLeaderOneName.setText(alstLeaderShip.get(0).getFirstName()); } if (Utils.validateString(alstLeaderShip.get(0).getPoint())) { txtLeaderOneCount.setText(alstLeaderShip.get(0).getPoint()); } if (Utils.validateString(alstLeaderShip.get(0).getUserProfile())) { Glide.with(getActivity()).load(alstLeaderShip.get(0).getUserProfile()) .placeholder(R.mipmap.ic_default_user_list) .error(R.mipmap.ic_default_user_list) .into(imgLeaderOne); } else imgLeaderOne.setImageResource(R.mipmap.ic_default_user_list); } public void setLeaderTwo(ArrayList<LeadershipBoardModel> alstLeaderShip) { if ((Utils.validateString(alstLeaderShip.get(1).getFirstName()))) { txtLeaderTwoName.setText(alstLeaderShip.get(1).getFirstName()); } if (Utils.validateString(alstLeaderShip.get(1).getPoint())) { txtLeaderTwoCount.setText(alstLeaderShip.get(1).getPoint()); } if (Utils.validateString(alstLeaderShip.get(1).getUserProfile())) { Glide.with(getActivity()).load(alstLeaderShip.get(1).getUserProfile()) .placeholder(R.mipmap.ic_default_user_list) .error(R.mipmap.ic_default_user_list) .into(imgLeaderTwo); } else imgLeaderTwo.setImageResource(R.mipmap.ic_default_user_list); } public void setLeaderThree(ArrayList<LeadershipBoardModel> alstLeaderShip) { if ((Utils.validateString(alstLeaderShip.get(2).getFirstName()))) { txtLeaderthreeName.setText(alstLeaderShip.get(2).getFirstName()); } if (Utils.validateString(alstLeaderShip.get(2).getPoint())) { txtLeaderThreeCount.setText(alstLeaderShip.get(2).getPoint()); } if (Utils.validateString(alstLeaderShip.get(2).getUserProfile())) { Glide.with(getActivity()).load(alstLeaderShip.get(2).getUserProfile()) .placeholder(R.mipmap.ic_default_user_list) .error(R.mipmap.ic_default_user_list) .into(imgLeaderThree); } else imgLeaderThree.setImageResource(R.mipmap.ic_default_user_list); } @Override public void clickEvent(View v) { super.clickEvent(v); switch (v.getId()) { case R.id.actionBarMenu: // Back button onBackPressed(); break; } } @Override public void onBackPressed() { super.onBackPressed(); homeActivity.popFragment(); } }14)LeaderShpBoardListFragment.java=======================================package com.eppico.fragments; import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v7.widget.DividerItemDecoration;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import com.eppico.R;import com.eppico.adapter.LeaderShipBoardAdapter;import com.eppico.adapter.LeaderShipBoardListAdapter;import com.eppico.api.RestClient;import com.eppico.models.LeadershipBoardModel;import com.eppico.models.UserLeaderShipListModel;import java.util.ArrayList;import java.util.List;import retrofit2.Call;import retrofit2.Response; /** * Created by manisha on 4/1/17. */ public class LeaderShpBoardListFragment extends BaseFragment { private View view; private RecyclerView recyclerView; private TextView txtNoRecords, txtActionBarTitle; private ArrayList<UserLeaderShipListModel> alstLeaderShip; LeaderShipBoardListAdapter adapter; private String spotId=""; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_leadership_list, container, false); inItData(); inItRecyclerView(); getLeadershipData(true); return view; } public void inItData() { txtActionBarTitle = (TextView) view.findViewById(R.id.actionBarTitle); txtActionBarTitle.setText(getString(R.string.leader_ship_board)); // Setup Actionbar ImageView actionBarMenu = (ImageView) view.findViewById(R.id.actionBarMenu); ImageView actionBarRightMenu = (ImageView) view.findViewById(R.id.actionBarRightMenu); TextView actionBarRightButton = (TextView) view.findViewById(R.id.actionBarRightButton); txtNoRecords = (TextView)view.findViewById(R.id.txtNoRecords); actionBarMenu.setImageResource(R.mipmap.ic_back); actionBarRightMenu.setVisibility(View.GONE); actionBarRightButton.setVisibility(View.INVISIBLE); actionBarRightButton.setText(getString(R.string.actionBarDone)); } public void inItRecyclerView() { recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); alstLeaderShip = new ArrayList<>(); recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), LinearLayoutManager.VERTICAL)); adapter = new LeaderShipBoardListAdapter(getActivity(),alstLeaderShip); recyclerView.setAdapter(adapter); } private void getLeadershipData(boolean showDialog) { Call<List<UserLeaderShipListModel>> objectCall = null; objectCall = RestClient.getApiClient().userLeadershipBoard(); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeLeaderShipBoardUser), showDialog); } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if (reqCode == getActivity().getResources().getInteger(R.integer.reqCodeLeaderShipBoardUser)) { recyclerView.setVisibility(View.VISIBLE); txtNoRecords.setVisibility(View.GONE); alstLeaderShip.clear(); alstLeaderShip.addAll((ArrayList<UserLeaderShipListModel>) response.body()); if (alstLeaderShip != null && alstLeaderShip.size() > 0) { adapter = new LeaderShipBoardListAdapter(getActivity(), alstLeaderShip); recyclerView.setAdapter(adapter); } else { recyclerView.setVisibility(View.GONE); txtNoRecords.setVisibility(View.VISIBLE); } } } @Override public void clickEvent(View v) { super.clickEvent(v); switch (v.getId()) { case R.id.actionBarMenu: // Back button onBackPressed(); break; case R.id.lytSpot: if(v.getTag()!=null) { UserLeaderShipListModel model = (UserLeaderShipListModel) v.getTag(); InviteSpotDetailFragment fragment = new InviteSpotDetailFragment(); Bundle mBundle = new Bundle(); mBundle.putInt(getResources().getString(R.string.extraSpotId), Integer.parseInt(model.getSpotId())); fragment.setArguments(mBundle); homeActivity.pushFragments(fragment, true, false, true); } break; } } @Override public void onBackPressed() { super.onBackPressed(); homeActivity.popFragment(); } }15)MapCreateNewSpotFragment.java=========================================package com.eppico.fragments; /** * Created by Admin on 12/12/2016. */ import android.graphics.Color;import android.os.Bundle;import android.os.Handler;import android.support.annotation.Nullable;import android.support.v4.app.FragmentManager;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import com.eppico.R;import com.eppico.models.CreateSpotModel;import com.eppico.utility.Constants;import com.eppico.utility.CustomDialog;import com.google.android.gms.maps.CameraUpdateFactory;import com.google.android.gms.maps.GoogleMap;import com.google.android.gms.maps.OnMapReadyCallback;import com.google.android.gms.maps.SupportMapFragment;import com.google.android.gms.maps.model.BitmapDescriptorFactory;import com.google.android.gms.maps.model.CircleOptions;import com.google.android.gms.maps.model.LatLng;import com.google.android.gms.maps.model.MarkerOptions; public class MapCreateNewSpotFragment extends BaseFragment implements OnMapReadyCallback { private GoogleMap googleMap; private View mainView; CreateSpotModel createSpotModel; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getArguments(); if(bundle != null) { createSpotModel= (CreateSpotModel) bundle.getSerializable(getString(R.string.extraCreateSpotObj)); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mainView = inflater.inflate(R.layout.fragment_createnewspot_map, container, false); init(); initMap(); return mainView; } private void init() { // Set Sliding Menu disable homeActivity.setSlidingMenuEnable(false); homeActivity.setSelectedPositionInSlidingMenu(2); // Setup Actionbar ImageView actionBarMenu= (ImageView) mainView.findViewById(R.id.actionBarMenu); ImageView actionBarRightMenu= (ImageView) mainView.findViewById(R.id.actionBarRightMenu); TextView actionBarRightButton= (TextView) mainView.findViewById(R.id.actionBarRightButton); TextView actionBarTitle= (TextView) mainView.findViewById(R.id.actionBarTitle); actionBarMenu.setImageResource(R.mipmap.ic_back); actionBarRightMenu.setVisibility(View.GONE); actionBarRightButton.setVisibility(View.VISIBLE); actionBarTitle.setText(getString(R.string.screenTitleCreateNewSpot)); actionBarRightButton.setText(getString(R.string.actionBarNext)); } /* private void initUI() { SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager() .findFragmentById(R.id.map_createnewspot); mapFragment.getMapAsync(this); }*/ /*Initialize Google map*/ private void initMap() { try { // SupportMapFragment mapFragment = (SupportMapFragment) fragmentManager.findFragmentById(R.id.googleMap);// mapFragment.getMapAsync(this); if (googleMap != null) { drawCircleOnMap(); } else { CustomDialog.getInstance().show(getActivity(),true); new Handler().postDelayed(new Runnable() { @Override public void run() { //CustomDialog.getInstance().hide(); if (isAdded()) { FragmentManager fm = getChildFragmentManager(); SupportMapFragment mapFragment = SupportMapFragment.newInstance(); fm.beginTransaction().replace(R.id.mapContainer, mapFragment).commit(); mapFragment.getMapAsync(MapCreateNewSpotFragment.this); } } }, 400); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onMapReady(GoogleMap googleMap) { CustomDialog.getInstance().hide(); this.googleMap = googleMap; // Add a marker in Sydney, Australia, and move the camera.// LatLng sydney = new LatLng(23.0225, 72.5714); //googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney")); /* this.googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney)); this.googleMap.animateCamera(CameraUpdateFactory.zoomIn()); this.googleMap.animateCamera(CameraUpdateFactory.zoomTo(14), 1000, null);*/ /*this.googleMap.addMarker(new MarkerOptions() .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_pin)) .anchor(0.5f, 0.5f) // Anchors the marker on the bottom left .position(new LatLng(23.0225, 72.5714)).title("Marker in Sydney")); Circle circle = this.googleMap.addCircle(new CircleOptions() .center(new LatLng(23.0225, 72.5714)) .radius(30) .strokeWidth(10) .strokeColor(Color.BLACK) .fillColor(Color.TRANSPARENT));*/ drawCircleOnMap(); } private void drawCircleOnMap() { try { if(createSpotModel!=null && createSpotModel.getSpotLatLong()!=null && createSpotModel.getSpotLatLong().length()>0) { String[] strLatLng = createSpotModel.getSpotLatLong().split(","); double latitude = Double.parseDouble(strLatLng[0]); double longitude = Double.parseDouble(strLatLng[1]); LatLng latLng=new LatLng(latitude, longitude); googleMap.clear(); googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); googleMap.animateCamera(CameraUpdateFactory.zoomIn()); googleMap.animateCamera(CameraUpdateFactory.zoomTo(18.7f), 1000, null); googleMap.addMarker(new MarkerOptions() .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_pin)) .anchor(0.5f, 0.5f) // Anchors the marker on the bottom left .position(latLng)); googleMap.addCircle(new CircleOptions() .center(latLng) .radius((createSpotModel.getRadius()>0?createSpotModel.getRadius():30)) .strokeWidth(8) .strokeColor(Color.BLACK) .fillColor(Color.TRANSPARENT)); } }catch (Exception e) { e.printStackTrace(); } } @Override public void clickEvent(View v) { super.clickEvent(v); switch (v.getId()) { case R.id.actionBarMenu: // Back button onBackPressed(); break; case R.id.actionBarRightButton: Bundle bundle=new Bundle();// bundle.putSerializable(getString(R.string.paramCreateSpotObj),createSpotModel); bundle.putInt(getString(R.string.extraSpotId),createSpotModel.getSpotId()); bundle.putInt(getString(R.string.extraFromScreen), Constants.FROM_SCREEN.CREATE_SPOT_MAP.ordinal()); InviteFriendsFragment inviteFriendsFragment=new InviteFriendsFragment(); inviteFriendsFragment.setArguments(bundle); homeActivity.pushFragments(inviteFriendsFragment,true,false,true); break; } } @Override public void onBackPressed() { homeActivity.popFragment(); } }16)MyProfileFragment.java==========================package com.eppico.fragments; import android.app.Dialog;import android.content.ClipData;import android.content.ClipboardManager;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Color;import android.graphics.drawable.BitmapDrawable;import android.os.Bundle;import android.os.Handler;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.support.v7.widget.GridLayoutManager;import android.support.v7.widget.RecyclerView;import android.util.DisplayMetrics;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.Button;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.ListView;import android.widget.PopupWindow;import android.widget.TextView;import android.widget.Toast;import com.bumptech.glide.Glide;import com.eppico.MyApplication;import com.eppico.R;import com.eppico.activity.HomeActivity;import com.eppico.adapter.InviteSpotDetailAdapter;import com.eppico.adapter.ProfileDetailAdapter;//import com.eppico.adapter.ProfilePostAdapter;import com.eppico.api.ApiResponseListener;import com.eppico.api.RestClient;import com.eppico.models.CheckInUserModel;import com.eppico.models.CheckedInSpotModel;import com.eppico.models.FollowUserModel;import com.eppico.models.InviteSpotDetailModel;import com.eppico.models.InviteSpotListModel;import com.eppico.models.LoginModel;import com.eppico.models.ProfileDetailModel;import com.eppico.utility.Constants;import com.eppico.utility.CustomDialog;import com.eppico.utility.PrefHelper;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils;import com.eppico.widgets.EasyDialog; import java.util.ArrayList;import java.util.Arrays; import retrofit2.Call;import retrofit2.Response; /** * Created by manisha on 17/12/16. */ public class MyProfileFragment extends BaseFragment { private View view; private ImageView actionBarMenu, actionBarRightMenu; private TextView txtNext, txtActionBarTitle, txtNoRecords; private RecyclerView recyclerProfilePost; static final int FIRST_PAGE_NO = 0; int pageNo = FIRST_PAGE_NO; int totalCount = 0; ProfileDetailModel profileDetailModel; ArrayList<ProfileDetailModel.PostMediaDetails> listPostMedia; boolean isLoading = false; int pastVisiblesItems, visibleItemCount, totalItemCount; GridLayoutManager gridManager; Constants.FROM_SCREEN fromScreen; private int userId; ProfileDetailAdapter adapter; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle mBundle = getArguments(); if (mBundle != null) { fromScreen = Constants.FROM_SCREEN.values()[mBundle.getInt(getString(R.string.extraFromScreen))]; userId = mBundle.getInt(getResources().getString(R.string.extraUserId)); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_my_profile, container, false); init(); initNSetRecyclerViewEvents(); new Handler().postDelayed(new Runnable() { @Override public void run() { if (homeActivity.loginModel != null) { resetListVariables(); getProfileDetail(pageNo, true); /*profileDetailModel= (ProfileDetailModel) ProfileDetailModel.toModelClass(Constants.strProfileResp,ProfileDetailModel.class); bindUserList(profileDetailModel);*/ } } }, 400); return view; } private void init() { //Set Sliding Menu enable homeActivity.setSlidingMenuEnable(true); homeActivity.setSelectedPositionInSlidingMenu(-1); TextView txtActionBarTitle = (TextView) view.findViewById(R.id.actionBarTitle); TextView txtNext = (TextView) view.findViewById(R.id.actionBarRightButton); actionBarRightMenu = (ImageView) view.findViewById(R.id.actionBarRightMenu); actionBarMenu = (ImageView) view.findViewById(R.id.actionBarMenu); txtNext.setVisibility(View.GONE); txtNoRecords = (TextView) view.findViewById(R.id.txtNoRecords); if (homeActivity.loginModel != null) { if (homeActivity.loginModel.getUserId() == userId) { if (fromScreen != null && fromScreen == Constants.FROM_SCREEN.MENU) { txtActionBarTitle.setText(getResources().getString(R.string.my_profile_title)); actionBarRightMenu.setImageResource(R.mipmap.ic_more); actionBarRightMenu.setVisibility(View.VISIBLE); actionBarMenu.setImageResource(R.mipmap.ic_menu); } else { txtActionBarTitle.setText(getResources().getString(R.string.my_profile_title)); actionBarRightMenu.setImageResource(R.mipmap.ic_more); actionBarRightMenu.setVisibility(View.VISIBLE); actionBarMenu.setImageResource(R.mipmap.ic_back); } } else { txtActionBarTitle.setText(getResources().getString(R.string.other_profile_title)); actionBarRightMenu.setVisibility(View.INVISIBLE); actionBarMenu.setImageResource(R.mipmap.ic_back); } } } private void getProfileDetail(int pageNo, boolean showDialog) { if (homeActivity.loginModel != null) { isLoading = true; Call<ProfileDetailModel> objectCall = RestClient.getApiClient().getProfileDetail("" + userId, String.valueOf(pageNo)); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeProfileDetail), showDialog); } } private void callUserFollowApi(ProfileDetailModel profileDetail) { Constants.FOLLOW_STATUS followStatus; // TODO Later Change This condition if(profileDetailModel.getUserIsFollowing()==Constants.FOLLOW_STATUS.FOLLOW.ordinal()) followStatus= Constants.FOLLOW_STATUS.UNFOLLOW; else followStatus= Constants.FOLLOW_STATUS.FOLLOW; Call<FollowUserModel> objectCall = RestClient.getApiClient().followUser(/*homeActivity.loginModel.getUserId() + "",*/ userId + "", followStatus.ordinal()+""); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeFollowUser), true); } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if (reqCode == getResources().getInteger(R.integer.reqCodeProfileDetail)) { profileDetailModel = (ProfileDetailModel) response.body(); totalCount = profileDetailModel.getPostMedia().getTotalCount(); if (listPostMedia == null) listPostMedia = new ArrayList<ProfileDetailModel.PostMediaDetails>(); listPostMedia.addAll(profileDetailModel.getPostMedia().getPostMediaDetails()); isLoading = false; pageNo++; /*if (alstProfileDetail == null) alstProfileDetail = new ArrayList<ProfileDetailModel.PostMediaDetails>(); if (mProfileDetailModel.getPostMedia().getPostMediaDetails() != null) { { alstProfileDetail.addAll(mProfileDetailModel.getPostMedia().getPostMediaDetails()); } }*/ bindUserList(profileDetailModel, listPostMedia); } if (reqCode == getResources().getInteger(R.integer.reqCodeFollowUser)) { FollowUserModel followUserModel= (FollowUserModel) response.body(); profileDetailModel.setUserIsFollowing(followUserModel.getUserIsFollowing()); adapter.notifyDataSetChanged(); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { isLoading = false; ToastHelper.getInstance().showToast(getActivity(), object.toString()); } private void initNSetRecyclerViewEvents() { recyclerProfilePost = (RecyclerView) view.findViewById(R.id.recyclerProfilePost); final int columnCount = 4; gridManager = new GridLayoutManager(getActivity(), columnCount);// alstProfileDetail = new ArrayList<>(); gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { if (position == 0) { return columnCount; } else if (position >= (listPostMedia.size() + 1)) { return columnCount; } else { return 1; } } }); recyclerProfilePost.setLayoutManager(gridManager); recyclerProfilePost.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); //if (dy > 0) //check for scroll down //{ visibleItemCount = gridManager.getChildCount(); totalItemCount = gridManager.getItemCount(); pastVisiblesItems = gridManager.findFirstVisibleItemPosition(); if (!isLoading && totalCount > profileDetailModel.getPostMedia().getPostMediaDetails().size()) { if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) { getProfileDetail(pageNo, true); } } //} } }); } private void bindUserList(ProfileDetailModel profileDetailModel, ArrayList<ProfileDetailModel.PostMediaDetails> listPostMedia) { /*if (listPostMedia != null && listPostMedia.size() > 0) { txtNoRecords.setVisibility(View.GONE); ProfileDetailAdapter adapter = (ProfileDetailAdapter) recyclerProfilePost.getAdapter(); if (adapter != null && adapter.getItemCount() > 0) { //adapter.notifyItemRemoved(alstProfileDetail.size()); adapter.setListItems(listPostMedia); } else { adapter = new ProfileDetailAdapter(getActivity(),profileDetailModel,listPostMedia); recyclerProfilePost.setAdapter(adapter); } } else { resetListVariables(); txtNoRecords.setVisibility(View.GONE);// ProfileDetailAdapter adapter = new ProfileDetailAdapter(getActivity(), listProfileDetail, mProfileDetailModel, totalCount);// recyclerProfilePost.setAdapter(adapter); }*/ txtNoRecords.setVisibility(View.GONE); adapter = (ProfileDetailAdapter) recyclerProfilePost.getAdapter(); if (adapter != null && adapter.getItemCount() > 0) { //adapter.notifyItemRemoved(alstProfileDetail.size()); adapter.setListItems(listPostMedia); } else { adapter = new ProfileDetailAdapter(getActivity(), profileDetailModel, listPostMedia, homeActivity.loginModel.getUserId()); recyclerProfilePost.setAdapter(adapter); } if (listPostMedia == null || listPostMedia.size() == 0) ToastHelper.getInstance().showToast(getActivity(), getString(R.string.msgNoPostFound), Toast.LENGTH_LONG); } /** * Reset variables before search */ private void resetListVariables() { isLoading = false; pageNo = FIRST_PAGE_NO; totalCount = 0; visibleItemCount = 0; totalItemCount = 0; pastVisiblesItems = 0; listPostMedia = new ArrayList<ProfileDetailModel.PostMediaDetails>(); recyclerProfilePost.setAdapter(null); } private void popUpDialog() { View popupView = LayoutInflater.from(getActivity()).inflate(R.layout.popup_view, null); final EasyDialog easyDialog = new EasyDialog(getActivity()) .setLayout(popupView) .setBackgroundColor(Color.WHITE) .setLocationByAttachedView(actionBarRightMenu) .setGravity(EasyDialog.GRAVITY_BOTTOM) .setTouchOutsideDismiss(true) .setMatchParent(false).setOutsideColor(Color.TRANSPARENT).show() .setOutsideColor(Color.TRANSPARENT) .show(); popupView.findViewById(R.id.txtEdit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { easyDialog.dismiss(); } }); popupView.findViewById(R.id.txtLeaderShipBoard).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { easyDialog.dismiss(); } }); popupView.findViewById(R.id.txtChampionShip).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { easyDialog.dismiss(); } }); } private void showPopup() { final PopupWindow popupWindow = new PopupWindow(getActivity()); LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View viewPopup = layoutInflater.inflate(R.layout.popup_view, null); viewPopup.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); final TextView txtEdit = (TextView) viewPopup.findViewById(R.id.txtEdit); TextView txtLeaderShipBoard = (TextView) viewPopup.findViewById(R.id.txtLeaderShipBoard); TextView txtChampionShip = (TextView) viewPopup.findViewById(R.id.txtChampionShip); txtChampionShip.setVisibility(View.GONE); View.OnClickListener onClickListener = new View.OnClickListener() { @Override public void onClick(View view) { popupWindow.dismiss(); switch (view.getId()) { case R.id.txtEdit: homeActivity.pushFragments(new EditProfileFragment(), true, false, true); break; case R.id.txtLeaderShipBoard: Bundle bundle = new Bundle(); bundle.putString(getResources().getString(R.string.extraSpotId), "" + profileDetailModel.getPostMedia().getPostMediaDetails().get(0).getSpotId()); bundle.putInt(getString(R.string.extraLeaderShipType), Constants.LEADER_SHIP_TYPE.LEADERSHIP.ordinal()); LeaderShpBoardListFragment leaderShip = new LeaderShpBoardListFragment(); leaderShip.setArguments(bundle); homeActivity.pushFragments(leaderShip, true, false, true); break; case R.id.txtChampionShip: CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.strComingSoon)); /* LeaderShipBoardFragment championShip = new LeaderShipBoardFragment(); Bundle bundle1 = new Bundle(); bundle1.putInt(getString(R.string.extraLeaderShipType), Constants.LEADER_SHIP_TYPE.CHMAPIONSHIP.ordinal()); homeActivity.pushFragments(championShip, true, false, true);*/ break; } } }; txtEdit.setOnClickListener(onClickListener); txtLeaderShipBoard.setOnClickListener(onClickListener); txtChampionShip.setOnClickListener(onClickListener); popupWindow.setContentView(viewPopup); int screenWH[] = Utils.getInstance().getScreenWidthHeight(getActivity()); popupWindow.setWidth((int) (screenWH[0] / 2));// popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); popupWindow.setFocusable(true); popupWindow.setBackgroundDrawable(new BitmapDrawable()); /* BitmapDrawable bd = (BitmapDrawable) this.getResources().getDrawable(R.mipmap.menu_dots); int height = bd.getBitmap().getHeight();*/ int topOffset = getResources().getDimensionPixelSize(R.dimen.dp20); int leftOffset = getResources().getDimensionPixelSize(R.dimen.dp10); popupWindow.showAsDropDown(actionBarRightMenu, 0, -topOffset); } @Override public void clickEvent(View v) { super.clickEvent(v); switch (v.getId()) { case R.id.actionBarMenu: if (homeActivity.loginModel.getUserId() == userId) { if (fromScreen != null && fromScreen == Constants.FROM_SCREEN.MENU) { homeActivity.toggleSlidingMenu(); } else { onBackPressed(); } } else { onBackPressed(); } break; case R.id.actionBarRightMenu: // popUpDialog(); showPopup(); break; case R.id.lytPost: Fragment fragment1 = new PostDetailFragment(); ProfileDetailModel.PostMediaDetails postMediaDetails = (ProfileDetailModel.PostMediaDetails) v.getTag(); Bundle mBundle1 = new Bundle(); mBundle1.putInt(getString(R.string.extraFromScreen), Constants.FROM_SCREEN.PROFILE.ordinal()); mBundle1.putString(getResources().getString(R.string.extraPostId), postMediaDetails.getPostId() + ""); mBundle1.putString(getResources().getString(R.string.extraSpotId), postMediaDetails.getSpotId() + ""); fragment1.setArguments(mBundle1); homeActivity.pushFragments(fragment1, true, false, true); break; case R.id.linFollowers: case R.id.linFollowing: FollowersListFragment followersListFragment = new FollowersListFragment(); Bundle bundleFollowers = new Bundle(); bundleFollowers.putInt(getString(R.string.extraFromScreen), Constants.FROM_SCREEN.PROFILE.ordinal()); bundleFollowers.putInt(getString(R.string.extraUserId), userId); if (v.getId() == R.id.linFollowers) bundleFollowers.putInt(getString(R.string.extraFollowListType), Constants.FOLLOW_LIST.FOLLOWERS.ordinal()); else bundleFollowers.putInt(getString(R.string.extraFollowListType), Constants.FOLLOW_LIST.FOLLOWING.ordinal()); followersListFragment.setArguments(bundleFollowers); homeActivity.pushFragments(followersListFragment, true, false, true); break; case R.id.txtFollow: if(profileDetailModel.getUserIsFollowing()== Constants.FOLLOW_STATUS.FOLLOW.ordinal()) showUnFollowDialog(profileDetailModel); else callUserFollowApi(profileDetailModel); break; } } /**Show UnFollow User confirmation dialog with spot image and spot name*/ private void showUnFollowDialog(final ProfileDetailModel profileModel) { try { final Dialog dialog = new Dialog(getActivity(), R.style.DialogTheme); dialog.setCancelable(true); LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.dialog_unfollow, null); ImageView imgUser = (ImageView) view.findViewById(R.id.imgUser); TextView txtUserName = (TextView) view.findViewById(R.id.txtUserName); Button btnCancel = (Button) view.findViewById(R.id.btnCancel); Button btnUnfollow = (Button) view.findViewById(R.id.btnUnfollow); // Set font type btnCancel.setTypeface(homeActivity.appInstance.fontRobotoRegular); btnUnfollow.setTypeface(homeActivity.appInstance.fontRobotoRegular); txtUserName.setText(getString(R.string.btnUnfollow) + " " + profileModel.getFirstName() + " " + profileModel.getLastName() + "?"); Glide.with(getActivity()) .load(profileModel.getUserProfile()) .placeholder(R.mipmap.ic_default_user_list) .error(R.mipmap.ic_default_user_list) .into(imgUser); dialog.setContentView(view); /** Set Dialog width match parent */ dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); btnUnfollow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); callUserFollowApi(profileModel); } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); if (dialog.isShowing()) dialog.dismiss(); dialog.show(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onBackPressed() { homeActivity.popFragment(); } }17)PostDetailFragment.java===========================package com.eppico.fragments; import android.app.AlertDialog;import android.app.Dialog;import android.content.DialogInterface;import android.content.Intent;import android.graphics.Color;import android.graphics.drawable.ColorDrawable;import android.net.Uri;import android.os.Bundle;import android.os.Handler;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.text.Editable;import android.text.TextUtils;import android.text.TextWatcher;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.EditText;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView; import com.bumptech.glide.Glide;import com.bumptech.glide.load.resource.drawable.GlideDrawable;import com.bumptech.glide.request.RequestListener;import com.bumptech.glide.request.target.Target;import com.eppico.MyApplication;import com.eppico.R;import com.eppico.activity.FullScreenViewActivity;import com.eppico.activity.HomeActivity;import com.eppico.adapter.PostDetailAdapter;import com.eppico.api.ApiResponseListener;import com.eppico.api.RestClient;import com.eppico.models.CheckInUserModel;import com.eppico.models.CommentListModel;import com.eppico.models.DeletePostModel;import com.eppico.models.FollowUserModel;import com.eppico.models.LikeModel;import com.eppico.models.LoginModel;import com.eppico.models.PostDetailModel;import com.eppico.utility.Constants;import com.eppico.utility.CustomDialog;import com.eppico.utility.PrefHelper;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils;import com.eppico.widgets.TouchImageView; import java.util.ArrayList; import retrofit2.Call;import retrofit2.Response; /** * Created by manisha on 16/12/16. */ public class PostDetailFragment extends BaseFragment implements ApiResponseListener { RestClient restClient; View view; LinearLayout linAddComment; private TextView txtActionBarTitle, txtViewComment; String postId = "", spotId = "", mediaId = ""; private ArrayList<PostDetailModel.PostComments> alstPostDetail; PostDetailModel postDetailModel; private EditText edtComment; CommentListModel commentListModel; private RecyclerView recyclerView; boolean isLoading = false; int pastVisiblesItems, visibleItemCount, totalItemCount; int pageNo = Constants.FIRST_PAGE_NO; int totalCount = 0, totalLike = 0; PostDetailAdapter adapter; private LinearLayout lytSend; public boolean isViewComment = false, isLike = false; Constants.FROM_SCREEN fromScreen; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getArguments(); if (bundle != null) { postId = bundle.getString(getResources().getString(R.string.extraPostId)); spotId = bundle.getString(getResources().getString(R.string.extraSpotId)); mediaId = bundle.getString(getResources().getString(R.string.extraMediaId)); if(bundle.containsKey(getString(R.string.extraFromScreen))) fromScreen= Constants.FROM_SCREEN.values()[bundle.getInt(getString(R.string.extraFromScreen))];// mIsActive = bundle.getInt(getResources().getString(R.string.extraIsActive)); } } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_post_detail, container, false); MyApplication myApplication = (MyApplication) getActivity().getApplication(); restClient = myApplication.getRestClient(); ImageView actionBarMenu = (ImageView) view.findViewById(R.id.actionBarMenu); ImageView actionBarRightMenu = (ImageView) view.findViewById(R.id.actionBarRightMenu); actionBarMenu.setImageResource(R.mipmap.ic_back); actionBarRightMenu.setVisibility(View.INVISIBLE); // Hide Keyboard on outside touch Utils.getInstance().setupOutSideTouchHideKeyboard(view.findViewById(R.id.my_toolbar)); Utils.getInstance().setupOutSideTouchHideKeyboard(view.findViewById(R.id.my_toolbar)); Utils.getInstance().setupOutSideTouchHideKeyboard(view.findViewById(R.id.lytSend)); txtActionBarTitle = (TextView) view.findViewById(R.id.actionBarTitle); txtActionBarTitle.setText(getResources().getString(R.string.post_detail_title)); txtViewComment = (TextView) view.findViewById(R.id.txtViewComment); linAddComment = (LinearLayout) view.findViewById(R.id.linAddComment); lytSend = (LinearLayout) view.findViewById(R.id.lytSend); edtComment = (EditText) view.findViewById(R.id.edtComment); homeActivity = (HomeActivity) getActivity(); initNSetRecyclerViewEvents(); // new Handler().postDelayed(new Runnable() {// @Override// public void run() {// getPostDetail(postId, "" + pageNo, true);// }// }, 400); return view; } public void getPostDetail(String postId, String pageNo, boolean showDialog) { if (Utils.validateString(postId)) { isLoading = true; Call objectCall = RestClient.getApiClient().postDetail(postId, pageNo); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getResources().getInteger(R.integer.reqCodePostDetail), showDialog); } else { CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.app_name), getResources().getString(R.string.post_id_not_available)); } } public void callDeletePostAPI() { PostDetailModel.PostDetails postDetails = postDetailModel.getPostDetails().get(0); Call<DeletePostModel> objectCall = RestClient.getApiClient().deletePost(/*homeActivity.loginModel.getUserId(),*/ postDetails.getSpotId(), postDetails.getPostId(), postDetails.getMediaID()); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getResources().getInteger(R.integer.reqCodePostDelete), true); } public void reportAbuse(String userId, String spotId, String postId, String mediaID, String msg, boolean showDialog) { if (Utils.validateString(postId)) { Call objectCall = RestClient.getApiClient().reportAbuse(userId, spotId, postId, mediaID, msg); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getResources().getInteger(R.integer.reqCodeReportAbuse), showDialog); } else { CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.app_name), getResources().getString(R.string.post_id_not_available)); } } public void addComment(String spotId, String postId, String msg, boolean showDialog) { if (Utils.validateString(postId)) { Call objectCall = RestClient.getApiClient().writeComment(spotId, postId, msg); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getResources().getInteger(R.integer.reqCodeAddComment), showDialog); } else { CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.app_name), getResources().getString(R.string.post_id_not_available)); } } public void deleteComment(String commentId, String postId, boolean showDialog) { if (Utils.validateString(postId)) { Call objectCall = RestClient.getApiClient().deleteComment(postId, commentId); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getResources().getInteger(R.integer.reqCodeDeleteComment), showDialog); } else { CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.app_name), getResources().getString(R.string.post_id_not_available)); } } public void likeComment(String postId, String mediaId, boolean showDialog) { if (Utils.validateString(postId)) { Call objectCall = RestClient.getApiClient().likeComment(spotId, postId, mediaId); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getResources().getInteger(R.integer.reqCodeLikepost), showDialog); } else { CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.app_name), getResources().getString(R.string.post_id_not_available)); } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if (reqCode == getActivity().getResources().getInteger(R.integer.reqCodePostDetail)) { postDetailModel = (PostDetailModel) response.body(); totalCount = postDetailModel.getPostDetails().get(0).getPostcomment().getTotalCount(); totalLike = postDetailModel.getPostDetails().get(0).getTotalLikes(); isLoading = false; pageNo++; if (alstPostDetail == null) alstPostDetail = new ArrayList<PostDetailModel.PostComments>(); if (postDetailModel.getPostDetails().get(0).getPostcomment().getPostComments() != null) { { alstPostDetail.addAll(postDetailModel.getPostDetails().get(0).getPostcomment().getPostComments()); } } // if (totalCount > 0) {// txtBeTheFirst.setVisibility(View.GONE);// } else {// txtBeTheFirst.setVisibility(View.VISIBLE);// } if (totalCount > 10) { if (isViewComment) { txtViewComment.setVisibility(View.GONE); } else { txtViewComment.setVisibility(View.VISIBLE); } } else { txtViewComment.setVisibility(View.GONE); } bindUserList(alstPostDetail); setViewBasedOnSpotStatus(); } else if (reqCode == getResources().getInteger(R.integer.reqCodeReportAbuse)) { postDetailModel.getPostDetails().get(0).setIsAbuse(1); CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.report_abuse_successfully)); } else if (reqCode == getResources().getInteger(R.integer.reqCodePostDelete)) { DeletePostModel deletePostModel = (DeletePostModel) response.body(); ToastHelper.getInstance().showToast(getActivity(), getString(R.string.postDeleteSuccessfully)); onBackPressed(); } else if (reqCode == getResources().getInteger(R.integer.reqCodeAddComment)) { PostDetailModel.PostComments commentModel = (PostDetailModel.PostComments) response.body(); edtComment.setText(""); alstPostDetail.add(0, commentModel); bindUserList(alstPostDetail); if (totalCount >= 0) { adapter.setTotalCount(++totalCount, alstPostDetail, isViewComment); } adapter.notifyDataSetChanged(); } else if (reqCode == getResources().getInteger(R.integer.reqCodeDeleteComment)) { resetListVariables(); getPostDetail(postId, "" + pageNo, true); } else if (reqCode == getResources().getInteger(R.integer.reqCodeLikepost)) { LikeModel likeModel = (LikeModel) response.body(); bindUserList(alstPostDetail); postDetailModel.getPostDetails().get(0).setIsLike(1); postDetailModel.getPostDetails().get(0).setTotalLikes(likeModel.getTotalLikes()); adapter.setLike(postDetailModel); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { ToastHelper.getInstance().showToast(getActivity(),object.toString()); } /**Set view based on spot status*/ private void setViewBasedOnSpotStatus() { if(isSpotActive()) { linAddComment.setVisibility(View.VISIBLE); }else linAddComment.setVisibility(View.GONE); } /**Return true if spot is active otherwise return false*/ private boolean isSpotActive() { if(postDetailModel!=null && postDetailModel.getPostDetails()!=null && postDetailModel.getPostDetails().size()>0) { if(postDetailModel.getPostDetails().get(0).getIsSpotActive()==0) // 0= Active 1= Inactive return true; } return false; } private void showConfirmAlert(final String type, final PostDetailModel.PostComments comments) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); //builder.setTitle(title); builder.setCancelable(true); if (type.equalsIgnoreCase(getResources().getString(R.string.post))) builder.setMessage(getString(R.string.msgConfirmDeletePost)); else builder.setMessage(getString(R.string.msgConfirmDeleteComment)); builder.setPositiveButton(getString(R.string.btnYes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); if (type.equalsIgnoreCase(getResources().getString(R.string.post))) callDeletePostAPI(); else { deleteComment("" + comments.getCommentId(), "" + comments.getPostId(), true); } } }); builder.setNegativeButton(getString(R.string.btnNo), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); // create alert dialog AlertDialog alertDialog = builder.create(); // show it alertDialog.show(); } private void initNSetRecyclerViewEvents() { recyclerView = (RecyclerView) view.findViewById(R.id.recyclerViewComment); final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); recyclerView.setLayoutManager(layoutManager); recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); if (isViewComment) { //if (dy > 0) //check for scroll down //{ visibleItemCount = layoutManager.getChildCount(); totalItemCount = layoutManager.getItemCount(); pastVisiblesItems = layoutManager.findFirstVisibleItemPosition(); if (!isLoading && totalCount > alstPostDetail.size()) { if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) { getPostDetail(postId, "" + pageNo, false); } } //} } } }); new Handler().postDelayed(new Runnable() { @Override public void run() { resetListVariables(); getPostDetail(postId, "" + pageNo, true); } }, 400); } private void bindUserList(ArrayList<PostDetailModel.PostComments> alstpostDetail) { if (alstpostDetail != null && alstpostDetail.size() > 0) { recyclerView.setVisibility(View.VISIBLE);// txtNoRecords.setVisibility(View.GONE); adapter = (PostDetailAdapter) recyclerView.getAdapter(); if (adapter != null && adapter.getItemCount() > 0) { adapter.notifyItemRemoved(alstpostDetail.size()); } else { adapter = new PostDetailAdapter(getActivity(), alstpostDetail, postDetailModel, totalCount, homeActivity.loginModel.getUserId(), isViewComment,postDetailModel.getPostDetails().get(0).getIsSpotActive()); recyclerView.setAdapter(adapter); } } else { // ToastHelper.getInstance().showToast(getActivity(), getString(R.string.msgNoPostFound), Toast.LENGTH_LONG); resetListVariables(); recyclerView.setVisibility(View.VISIBLE);// txtNoRecords.setVisibility(View.GONE); adapter = new PostDetailAdapter(getActivity(), alstpostDetail, postDetailModel, totalCount, homeActivity.loginModel.getUserId(), isViewComment,postDetailModel.getPostDetails().get(0).getIsSpotActive()); recyclerView.setAdapter(adapter); } } @Override public void clickEvent(View v) { super.clickEvent(v); switch (v.getId()) { case R.id.actionBarMenu: // Back event onBackPressed(); break; case R.id.imgPlayIcon: if (postDetailModel.getPostDetails().get(0).getMediaType().equals(Constants.POST_MEDIA_TYPE.VIDEO.ordinal() + "")) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(postDetailModel.getPostDetails().get(0).getMediaUrl())); intent.setDataAndType(Uri.parse(postDetailModel.getPostDetails().get(0).getMediaUrl()), "video/mp4"); startActivity(intent); } break; case R.id.imgPost: if (postDetailModel.getPostDetails().get(0).getMediaType().equals(Constants.POST_MEDIA_TYPE.IMAGE.ordinal() + "")) { openImageInFullScreen(postDetailModel.getPostDetails().get(0).getMediaUrl()); /*Intent mIntent = new Intent(getActivity(), FullScreenViewActivity.class); mIntent.putExtra(getResources().getString(R.string.extraBigImage), postDetailModel.getPostDetails().get(0).getMediaUrl()); startActivity(mIntent);*/ } break; case R.id.imgReportAbuse: if (postDetailModel.getPostDetails().get(0).getUserId() == homeActivity.loginModel.getUserId()) showConfirmAlert(getResources().getString(R.string.post), null); else { if (postDetailModel.getPostDetails().get(0).getIsAbuse() == 0) { showReportAbusedialog(); } else { CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.you_have_alredy_report_abuse_this_post)); } } break; case R.id.lytSend: if (homeActivity.loginModel != null && spotId != null && postId != null) { if (!TextUtils.isEmpty(edtComment.getText().toString().trim())) { Utils.getInstance().hideKeyboard(edtComment, getActivity()); addComment(spotId, postId, edtComment.getText().toString().trim(), true); } else { CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.please_add_comment)); } } break; case R.id.txtLike: // Spot is inactive disable like if(isSpotActive()) { if (postDetailModel.getPostDetails().get(0).getIsLike() == 0) { if (postId != null && ("" + postDetailModel.getPostDetails().get(0).getMediaID() != null)) { likeComment(postId, "" + postDetailModel.getPostDetails().get(0).getMediaID(), true); } } else { CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.you_have_alredy_like_this_post)); } } else CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.msgSpotIsInactive)); break; case R.id.txtDelete: PostDetailModel.PostComments comments = (PostDetailModel.PostComments) v.getTag(); showConfirmAlert(getResources().getString(R.string.comment), comments); break; case R.id.txtViewComment: txtViewComment.setVisibility(View.GONE); isViewComment = true; adapter.setTotalCount(totalCount, alstPostDetail, isViewComment); break; case R.id.txtSpotName: // Redirect to spot detail if spot is active. Only spot owner will redirect to inactive spot if(isSpotActive() || postDetailModel.getPostDetails().get(0).getSpotUserId()==homeActivity.loginModel.getUserId()) { if(fromScreen== Constants.FROM_SCREEN.SPOT_DETAIL){ homeActivity.popFragment(); }else{ Fragment fragment = new InviteSpotDetailFragment(); Bundle mBundle = new Bundle(); mBundle.putInt(getString(R.string.extraSpotId),Integer.parseInt(spotId)); fragment.setArguments(mBundle); homeActivity.pushFragments(fragment, true, false, true); } } else CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getResources().getString(R.string.msgSpotIsInactive)); break; case R.id.txtName: case R.id.imgUser: Fragment fragment = new MyProfileFragment(); Bundle mBundle = new Bundle(); mBundle.putInt(getString(R.string.extraUserId),postDetailModel.getPostDetails().get(0).getUserId()); fragment.setArguments(mBundle); homeActivity.pushFragments(fragment, true, false, true); break; case R.id.imgCommentUser: PostDetailModel.PostComments postComments = (PostDetailModel.PostComments) v.getTag(R.string.tagId); Fragment fragment1 = new MyProfileFragment(); Bundle mBundle1 = new Bundle(); mBundle1.putInt(getString(R.string.extraUserId),postComments.getUserId()); fragment1.setArguments(mBundle1); homeActivity.pushFragments(fragment1, true, false, true); break; } } /**Show Image in full screen with zoom functionality*/ private void openImageInFullScreen(String imageUrl) { if(imageUrl!=null && imageUrl.length()>0) { final Dialog dialog=new Dialog(getActivity(),R.style.DialogTheme); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.setContentView(R.layout.dialog_fullscreen_view); /* Set Dialog width match parent*/ dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT); final TouchImageView imgPost= (TouchImageView) dialog.findViewById(R.id.imgPost); ImageView imgClose= (ImageView) dialog.findViewById(R.id.imgClose); /**Note: Set Zoomable false until image not load, and set scale type CENTER_INSIDE to display placeholder proper*/ imgPost.enableZoom(false); imgPost.setScaleType(ImageView.ScaleType.CENTER_INSIDE); Glide.with(this) .load(imageUrl) .placeholder(R.mipmap.ic_default_spot_list) .error(R.mipmap.ic_default_spot_list) .listener(new RequestListener<String, GlideDrawable>() { @Override public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) { imgPost.enableZoom(false); return false; } @Override public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) { imgPost.enableZoom(true); imgPost.setScaleType(ImageView.ScaleType.MATRIX); return false; } }) .dontAnimate() .into(imgPost); imgClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); dialog.show(); } } public void showReportAbusedialog() { final Dialog dialog = new Dialog(getActivity(), android.R.style.Theme_Dialog); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.setContentView(R.layout.report_abuse_dialog); final TextView txtOk = (TextView) dialog.findViewById(R.id.txtOk); TextView txtCancel = (TextView) dialog.findViewById(R.id.txtCancel); final EditText edtReportAbuse = (EditText) dialog.findViewById(R.id.edtReportAbuse); txtOk.setEnabled(false); txtOk.setTextColor(Color.parseColor("#CCCCCC")); //disable edtReportAbuse.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) { String reportAbus = edtReportAbuse.getText().toString().trim(); if (edtReportAbuse.getText() != null && edtReportAbuse.getText().toString().trim().length() > 0) { txtOk.setTextColor(Color.parseColor("#585858")); //Enable txtOk.setEnabled(true); } else { txtOk.setEnabled(false); txtOk.setTextColor(Color.parseColor("#CCCCCC")); //disable } } @Override public void afterTextChanged(Editable editable) { } }); txtOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); Utils.getInstance().hideKeyboard(edtReportAbuse, getActivity()); if (homeActivity.loginModel != null) { reportAbuse("" + homeActivity.loginModel.getUserId(), spotId, postId, mediaId, edtReportAbuse.getText().toString().trim(), true); } } }); txtCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); } /** * Reset variables before search */ private void resetListVariables() { isLoading = false; pageNo = Constants.FIRST_PAGE_NO; totalCount = 0; visibleItemCount = 0; totalItemCount = 0; pastVisiblesItems = 0; alstPostDetail = new ArrayList<PostDetailModel.PostComments>(); recyclerView.setAdapter(null); } @Override public void onBackPressed() { resetListVariables(); homeActivity.popFragment(); } }18)SearchFragment.java=======================package com.eppico.fragments; import android.os.Bundle;import android.support.design.widget.TabLayout;import android.support.v4.app.Fragment;import android.support.v4.content.ContextCompat;import android.support.v4.view.ViewPager;import android.view.KeyEvent;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.inputmethod.EditorInfo;import android.widget.EditText;import android.widget.ImageView;import android.widget.TextView; import com.eppico.R;import com.eppico.adapter.SearchPagerAdapter;import com.eppico.api.RestClient;import com.eppico.interfaces.ClickEventListener;import com.eppico.models.FollowersListModel;import com.eppico.utility.Constants;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils; import retrofit2.Call; public class SearchFragment extends BaseFragment { // XML Components View mainView; ViewPager viewPagerSearch; TabLayout tabLayoutSearch; EditText edtSearchSpotUser; Constants.TAB_SEARCH currentTab = Constants.TAB_SEARCH.SPOT; SearchPagerAdapter searchPagerAdapter; boolean isSpotSearch,isUserSearch; String searchStrSpot="",searchStrUser=""; ClickEventListener clickEventListener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mainView=inflater.inflate(R.layout.fragment_search, container, false); init(); setSearchEvent(); initTabLayout(); return mainView; } private void init() { // Hide Keyboard on outside touch Utils.getInstance().setupOutSideTouchHideKeyboard(mainView.findViewById(R.id.parentView)); //Set Sliding Menu enable homeActivity.setSlidingMenuEnable(true); homeActivity.setSelectedPositionInSlidingMenu(1); //Setup Actionbar TextView actionBarTitle= (TextView) mainView.findViewById(R.id.actionBarTitle); ImageView actionBarRightMenu= (ImageView) mainView.findViewById(R.id.actionBarRightMenu); actionBarTitle.setText(getString(R.string.screenTitleSearch)); actionBarRightMenu.setVisibility(View.INVISIBLE); edtSearchSpotUser= (EditText) mainView.findViewById(R.id.edtSearchSpotUser); } private void initTabLayout() { viewPagerSearch= (ViewPager) mainView.findViewById(R.id.viewPagerSearch); tabLayoutSearch= (TabLayout) mainView.findViewById(R.id.tabLayoutSearch); if(searchPagerAdapter==null) searchPagerAdapter=new SearchPagerAdapter(getActivity(),getChildFragmentManager()); viewPagerSearch.setAdapter(searchPagerAdapter); tabLayoutSearch.setupWithViewPager(viewPagerSearch); // Iterate over all tabs and set the custom view for (int i = 0; i < tabLayoutSearch.getTabCount(); i++) { TabLayout.Tab tab = tabLayoutSearch.getTabAt(i); tab.setCustomView(searchPagerAdapter.getTabView(i)); } tabLayoutSearch.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPagerSearch) { @Override public void onTabSelected(TabLayout.Tab tab) { super.onTabSelected(tab); currentTab= Constants.TAB_SEARCH.values()[tab.getPosition()]; TextView txtTabTitle= (TextView) tab.getCustomView().findViewById(R.id.txtTabTitle); txtTabTitle.setTextColor(ContextCompat.getColor(getActivity(),R.color.tabTextColorSelected)); setViewAccordingToSelectedTab(); } @Override public void onTabUnselected(TabLayout.Tab tab) { super.onTabUnselected(tab); TextView txtTabTitle= (TextView) tab.getCustomView().findViewById(R.id.txtTabTitle); txtTabTitle.setTextColor(ContextCompat.getColor(getActivity(),R.color.tabTextColorNormal)); setViewAccordingToSelectedTab(); } @Override public void onTabReselected(TabLayout.Tab tab) { super.onTabReselected(tab); /*TextView txtTabTitle= (TextView) tab.getCustomView().findViewById(R.id.txtTabTitle); txtTabTitle.setTextColor(ContextCompat.getColor(getActivity(),R.color.tabTextColorSelected)); setViewAccordingToSelectedTab();*/ onTabSelected(tab); } }); tabLayoutSearch.post(new Runnable() { @Override public void run() { resetVariablesOfAllTabFragments(); tabLayoutSearch.getTabAt(currentTab.ordinal()).select(); } }); /*tabLayoutSearch.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { TextView txtTabTitle= (TextView) tab.getCustomView().findViewById(R.id.txtTabTitle); txtTabTitle.setTextColor(ContextCompat.getColor(getActivity(),R.color.tabTextColorSelected)); } @Override public void onTabUnselected(TabLayout.Tab tab) { TextView txtTabTitle= (TextView) tab.getCustomView().findViewById(R.id.txtTabTitle); txtTabTitle.setTextColor(ContextCompat.getColor(getActivity(),R.color.tabTextColorNormal)); } @Override public void onTabReselected(TabLayout.Tab tab) { TextView txtTabTitle= (TextView) tab.getCustomView().findViewById(R.id.txtTabTitle); txtTabTitle.setTextColor(ContextCompat.getColor(getActivity(),R.color.tabTextColorSelected)); } });*/ } /**Rest all tab variables to load call API for every time*/ private void resetVariablesOfAllTabFragments() { if(searchPagerAdapter!=null && searchPagerAdapter.getCount()>0) { for (int i = 0; i < searchPagerAdapter.getCount(); i++) { if(i==Constants.TAB_SEARCH.SPOT.ordinal()) { SearchSpotFragment searchSpotFragment= (SearchSpotFragment) searchPagerAdapter.getItem(i); searchSpotFragment.resetListVariables(); } else if(i==Constants.TAB_SEARCH.USER.ordinal()) { SearchUserFragment searchUserFragment= (SearchUserFragment) searchPagerAdapter.getItem(i); searchUserFragment.resetListVariables(); } } } } public void setSearchEvent() { edtSearchSpotUser.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { String searchStr=edtSearchSpotUser.getText().toString().trim(); if (searchStr.length() > 0) { setSearchString(searchStr); setSearch(true); Utils.getInstance().hideKeyboard(v,getActivity()); //isSearch=true; callSearchAPI(); } else { //Toast.makeText(getActivity(), getActivity().getString(R.string.searchMessage), Toast.LENGTH_SHORT).show(); ToastHelper.getInstance().showToast(getActivity(),getString(R.string.enterSearchText)); edtSearchSpotUser.requestFocus(); } } return true; } }); } private String getSearchString() { switch (currentTab) { case SPOT: return searchStrSpot; case USER: default: return searchStrUser; } } private void setSearchString(String searchString) { switch (currentTab) { case SPOT: searchStrSpot=searchString; break; case USER: searchStrUser=searchString; break; } } private void setSearch(boolean isSearch) { switch (currentTab) { case SPOT: isSpotSearch=isSearch; break; case USER: isUserSearch=isSearch; break; } } private boolean isSearched() { switch (currentTab) { case SPOT: return isSpotSearch; default: case USER: return isUserSearch; } } /**Return current fragment*/ private Fragment getCurrentFragment() { if(searchPagerAdapter!=null) return searchPagerAdapter.getItem(currentTab.ordinal()); else return null; } /**Set View according selected tab*/ private void setViewAccordingToSelectedTab() { // Set searched text String searchedString=getSearchString(); edtSearchSpotUser.setText(searchedString); //Set cursor at last of string edtSearchSpotUser.setSelection(searchedString.length()); //Initialize clickEventListener Fragment currentFragment=getCurrentFragment(); if(currentFragment!=null) clickEventListener= (ClickEventListener) currentFragment; switch (currentTab) { case SPOT: edtSearchSpotUser.setHint(getString(R.string.hintSearchSpot)); break; case USER: edtSearchSpotUser.setHint(getString(R.string.hintSearchUser)); break; } } /**Call Search API according tab selected*/ private void callSearchAPI() { if(searchPagerAdapter!=null) { switch (currentTab) { case SPOT: // Search Spot SearchSpotFragment searchSpotFragment= (SearchSpotFragment) getCurrentFragment(); if(searchSpotFragment!=null) searchSpotFragment.searchSpot(true,true); break; case USER: // Search User SearchUserFragment searchUserFragment= (SearchUserFragment) getCurrentFragment(); if(searchUserFragment!=null) searchUserFragment.searchUser(true,true); break; } } } @Override public void clickEvent(View v) { switch (v.getId()) { case R.id.actionBarMenu: // Menu button homeActivity.toggleSlidingMenu(); break; case R.id.imgClear: setSearchString(""); edtSearchSpotUser.setText(getSearchString()); if(isSearched()) { // isSearch=false; setSearch(false); callSearchAPI(); } break; default: if(clickEventListener!=null) clickEventListener.clickEvent(v); break; } } @Override public void onBackPressed() { homeActivity.popFragment(); } }19)SearchSpotFragment.java==========================package com.eppico.fragments; import android.os.Bundle;import android.os.Handler;import android.support.v7.widget.DividerItemDecoration;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.TextView; import com.eppico.R;import com.eppico.adapter.AppUserListAdapter;import com.eppico.adapter.SearchSpotAdapter;import com.eppico.api.RestClient;import com.eppico.models.AppUserModel;import com.eppico.models.FollowersListModel;import com.eppico.models.SearchSpotModel;import com.eppico.utility.Constants;import com.eppico.utility.MyLog;import com.eppico.utility.ToastHelper; import java.util.ArrayList; import retrofit2.Call;import retrofit2.Response; public class SearchSpotFragment extends BaseFragment { View mainView; RecyclerView recyclerViewSearchSpot; TextView txtNoRecords; // Pagination related varibles int pastVisiblesItems, visibleItemCount, totalItemCount; int pageNo=Constants.FIRST_PAGE_NO,totalCount; boolean isLoading; ArrayList<SearchSpotModel.SpotList> listSearchedSpot; SearchFragment searchFragment; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); searchFragment= (SearchFragment) getParentFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mainView=inflater.inflate(R.layout.fragment_search_spot, container, false); init(); return mainView; } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser && isResumed()) { //Only manually call onResume if fragment is already visible //Otherwise allow natural fragment lifecycle to call onResume onResume(); } } @Override public void onResume() { super.onResume(); if (!getUserVisibleHint()) { return; } new Handler().postDelayed(new Runnable() { @Override public void run() { if(listSearchedSpot!=null && listSearchedSpot.size()>0) { if(recyclerViewSearchSpot.getAdapter()==null) bindSpotList(listSearchedSpot); } else searchSpot(true,true); } }, getResources().getInteger(android.R.integer.config_mediumAnimTime)); } private void init() { txtNoRecords= (TextView) mainView.findViewById(R.id.txtNoRecords); initNSetRecyclerViewEvents(); } private void initNSetRecyclerViewEvents() { recyclerViewSearchSpot = (RecyclerView) mainView.findViewById(R.id.recyclerViewSearchSpot); recyclerViewSearchSpot.setHasFixedSize(true); final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); recyclerViewSearchSpot.setLayoutManager(layoutManager); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerViewSearchSpot.getContext(), layoutManager.getOrientation()); // dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this,R.drawable.divider)); recyclerViewSearchSpot.addItemDecoration(dividerItemDecoration); recyclerViewSearchSpot.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); visibleItemCount = layoutManager.getChildCount(); totalItemCount = layoutManager.getItemCount(); pastVisiblesItems = layoutManager.findFirstVisibleItemPosition(); if (!isLoading && totalCount > listSearchedSpot.size()) { if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) { /*if(isSearch) searchInviteList(searchStr,pageIndex,false); else getInviteList(searchStr,pageIndex,false);*/ searchSpot(false,false); } } } }); /*recyclerView.addOnItemTouchListener(new RecyclerViewItemClickListener(getActivity(), new RecyclerViewItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Fragment fragment = new InviteSpotDetailFragment(); Bundle mBundle = new Bundle(); mBundle.putInt(getResources().getString(R.string.extraSpotId), alstFollowingSpot.get(position).getSpotId()); fragment.setArguments(mBundle); homeActivity.pushFragments(fragment, true, false, true); } }));*/ } @Override public void clickEvent(View v) { switch (v.getId()) { case R.id.linSearchSpotMain: if(v.getTag()!=null) { SearchSpotModel.SpotList spotList= (SearchSpotModel.SpotList) v.getTag(); InviteSpotDetailFragment fragment = new InviteSpotDetailFragment(); Bundle mBundle = new Bundle(); mBundle.putInt(getResources().getString(R.string.extraSpotId), spotList.getSpotId()); fragment.setArguments(mBundle); homeActivity.pushFragments(fragment, true, false, true); } break; } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if(reqCode==getResources().getInteger(R.integer.reqCodeSearchSpot)) { isLoading=false; pageNo++; SearchSpotModel searchSpotModel= (SearchSpotModel) response.body(); totalCount=searchSpotModel.getTotalCount(); if(listSearchedSpot==null) listSearchedSpot=new ArrayList<SearchSpotModel.SpotList>(); if(searchSpotModel.getSpotList()!=null) listSearchedSpot.addAll(searchSpotModel.getSpotList()); bindSpotList(listSearchedSpot); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { isLoading=false; ToastHelper.getInstance().showToast(getActivity(),object.toString()); } private void bindSpotList(ArrayList<SearchSpotModel.SpotList> listSearchedSpot) { if(listSearchedSpot!=null && listSearchedSpot.size()>0) { /*if(searchStr!=null && searchStr.length()>0 && pageNoSearch==1) recyclerViewInviteSpot.setAdapter(null);*/ recyclerViewSearchSpot.setVisibility(View.VISIBLE); txtNoRecords.setVisibility(View.GONE); SearchSpotAdapter adapter= (SearchSpotAdapter) recyclerViewSearchSpot.getAdapter(); if(adapter!=null && adapter.getItemCount()>0) { adapter.setListItems(listSearchedSpot); /*if(isAllRecordsLoaded) adapter.notifyItemRemoved(listAppUsers.size());*/ } else { adapter=new SearchSpotAdapter(getActivity(),listSearchedSpot,totalCount); recyclerViewSearchSpot.setAdapter(adapter); } } else { recyclerViewSearchSpot.setVisibility(View.GONE); txtNoRecords.setVisibility(View.VISIBLE); } } /**Reset variables before search*/ public void resetListVariables() { isLoading=false; pageNo= Constants.FIRST_PAGE_NO; totalCount=0; visibleItemCount =0; totalItemCount = 0; pastVisiblesItems = 0; listSearchedSpot=new ArrayList<SearchSpotModel.SpotList>(); recyclerViewSearchSpot.setAdapter(null); } public void searchSpot(boolean resetVariables,boolean showDialog) { // loginModel.getUserId(); isLoading = true; if(resetVariables) resetListVariables(); Call<SearchSpotModel> objectCall = RestClient.getApiClient().searchSpot(searchFragment.searchStrSpot,pageNo); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeSearchSpot), showDialog); } @Override public void onBackPressed() { homeActivity.popFragment(); } }20)SearchUserFragment.java===================================package com.eppico.fragments; import android.app.Dialog;import android.content.Context;import android.os.Bundle;import android.os.Handler;import android.support.v7.widget.DividerItemDecoration;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView; import com.bumptech.glide.Glide;import com.eppico.R;import com.eppico.adapter.SearchSpotAdapter;import com.eppico.adapter.SearchUserListAdapter;import com.eppico.api.RestClient;import com.eppico.models.FollowUserModel;import com.eppico.models.FollowersListModel;import com.eppico.models.SearchSpotModel;import com.eppico.models.SearchUserListModel;import com.eppico.utility.Constants;import com.eppico.utility.MyLog;import com.eppico.utility.ToastHelper; import java.util.ArrayList; import retrofit2.Call;import retrofit2.Response; public class SearchUserFragment extends BaseFragment { View mainView; RecyclerView recyclerViewSearchUser; TextView txtNoRecords; // Pagination related varibles int pastVisiblesItems, visibleItemCount, totalItemCount; int pageNo= Constants.FIRST_PAGE_NO,totalCount; boolean isLoading; ArrayList<SearchUserListModel.User> listSearchedUsers; SearchFragment searchFragment; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); searchFragment= (SearchFragment) getParentFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mainView=inflater.inflate(R.layout.fragment_search_user, container, false); init(); return mainView; } @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (isVisibleToUser && isResumed()) { //Only manually call onResume if fragment is already visible //Otherwise allow natural fragment lifecycle to call onResume onResume(); } } @Override public void onResume() { super.onResume(); if (!getUserVisibleHint()) { return; } new Handler().postDelayed(new Runnable() { @Override public void run() { if(listSearchedUsers!=null && listSearchedUsers.size()>0 ) { if(recyclerViewSearchUser.getAdapter()==null) bindUserList(listSearchedUsers); } else searchUser(true,true); } }, getResources().getInteger(android.R.integer.config_mediumAnimTime)); } private void init() { txtNoRecords= (TextView) mainView.findViewById(R.id.txtNoRecords); initNSetRecyclerViewEvents(); } private void initNSetRecyclerViewEvents() { recyclerViewSearchUser = (RecyclerView) mainView.findViewById(R.id.recyclerViewSearchUser); recyclerViewSearchUser.setHasFixedSize(true); final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); recyclerViewSearchUser.setLayoutManager(layoutManager); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerViewSearchUser.getContext(), layoutManager.getOrientation()); // dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this,R.drawable.divider)); recyclerViewSearchUser.addItemDecoration(dividerItemDecoration); recyclerViewSearchUser.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); visibleItemCount = layoutManager.getChildCount(); totalItemCount = layoutManager.getItemCount(); pastVisiblesItems = layoutManager.findFirstVisibleItemPosition(); if (!isLoading && totalCount > listSearchedUsers.size()) { if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) { /*if(isSearch) searchInviteList(searchStr,pageIndex,false); else getInviteList(searchStr,pageIndex,false);*/ searchUser(false,false); } } } }); } @Override public void clickEvent(View v) { switch (v.getId()) { case R.id.txtFollow: if (v.getTag() != null) { SearchUserListModel.User user = (SearchUserListModel.User) v.getTag(); if(user.getUserIsFollowing()==Constants.FOLLOW_STATUS.FOLLOW.ordinal()) showUnFollowDialog(user); else callUserFollowApi(user); } break; case R.id.txtUserName: case R.id.imgUser: if (v.getTag(R.string.tagId) != null) { SearchUserListModel.User user = (SearchUserListModel.User) v.getTag(R.string.tagId); MyProfileFragment fragment = new MyProfileFragment(); Bundle mBundle = new Bundle(); mBundle.putInt(getString(R.string.extraUserId), user.getUserId()); fragment.setArguments(mBundle); homeActivity.pushFragments(fragment, true, false, true); } break; } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if(reqCode==getResources().getInteger(R.integer.reqCodeSearchUser)) { isLoading=false; pageNo++; SearchUserListModel searchUserListModel= (SearchUserListModel) response.body(); totalCount=searchUserListModel.getTotalCount(); if(listSearchedUsers==null) listSearchedUsers=new ArrayList<SearchUserListModel.User>(); if(searchUserListModel.getUser()!=null) listSearchedUsers.addAll(searchUserListModel.getUser()); bindUserList(listSearchedUsers); } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode, int position) { if (reqCode == getResources().getInteger(R.integer.reqCodeFollowUser)) { FollowUserModel followUserModel= (FollowUserModel) response.body(); SearchUserListModel.User user=listSearchedUsers.get(position); user.setUserIsFollowing(followUserModel.getUserIsFollowing()); listSearchedUsers.set(position,user); bindUserList(listSearchedUsers); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { isLoading=false; ToastHelper.getInstance().showToast(getActivity(),object.toString()); } private void bindUserList(ArrayList<SearchUserListModel.User> listSearchedUsers) { if(listSearchedUsers!=null && listSearchedUsers.size()>0) { /*if(searchStr!=null && searchStr.length()>0 && pageNoSearch==1) recyclerViewInviteSpot.setAdapter(null);*/ recyclerViewSearchUser.setVisibility(View.VISIBLE); txtNoRecords.setVisibility(View.GONE); SearchUserListAdapter adapter= (SearchUserListAdapter) recyclerViewSearchUser.getAdapter(); if(adapter!=null && adapter.getItemCount()>0) { adapter.setListItems(listSearchedUsers); /*if(isAllRecordsLoaded) adapter.notifyItemRemoved(listAppUsers.size());*/ } else { adapter=new SearchUserListAdapter(getActivity(),homeActivity.loginModel.getUserId(),listSearchedUsers,totalCount); recyclerViewSearchUser.setAdapter(adapter); } } else { recyclerViewSearchUser.setVisibility(View.GONE); txtNoRecords.setVisibility(View.VISIBLE); } } /**Reset variables before search*/ public void resetListVariables() { isLoading=false; pageNo= Constants.FIRST_PAGE_NO; totalCount=0; visibleItemCount =0; totalItemCount = 0; pastVisiblesItems = 0; listSearchedUsers=new ArrayList<SearchUserListModel.User>(); recyclerViewSearchUser.setAdapter(null); } private void callUserFollowApi(SearchUserListModel.User user) { Constants.FOLLOW_STATUS followStatus; if(user.getUserIsFollowing()==Constants.FOLLOW_STATUS.FOLLOW.ordinal()) followStatus= Constants.FOLLOW_STATUS.UNFOLLOW; else followStatus= Constants.FOLLOW_STATUS.FOLLOW; Call<FollowUserModel> objectCall = RestClient.getApiClient().followUser(/*homeActivity.loginModel.getUserId() + "",*/ user.getUserId() + "", followStatus.ordinal()+""); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeFollowUser),user.getPosition(), true); } /**Show UnFollow User confirmation dialog with spot image and spot name*/ private void showUnFollowDialog(final SearchUserListModel.User user) { try { final Dialog dialog = new Dialog(getActivity(), R.style.DialogTheme); dialog.setCancelable(true); LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.dialog_unfollow, null); ImageView imgUser = (ImageView) view.findViewById(R.id.imgUser); TextView txtUserName = (TextView) view.findViewById(R.id.txtUserName); Button btnCancel = (Button) view.findViewById(R.id.btnCancel); Button btnUnfollow = (Button) view.findViewById(R.id.btnUnfollow); // Set font type btnCancel.setTypeface(homeActivity.appInstance.fontRobotoRegular); btnUnfollow.setTypeface(homeActivity.appInstance.fontRobotoRegular); txtUserName.setText(getString(R.string.btnUnfollow) + " " + user.getFirstName() + " " + user.getLastName() + "?"); Glide.with(getActivity()) .load(user.getUserProfile()) .placeholder(R.mipmap.ic_default_user_list) .error(R.mipmap.ic_default_user_list) .into(imgUser); dialog.setContentView(view); /** Set Dialog width match parent */ dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); btnUnfollow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); callUserFollowApi(user); } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); if (dialog.isShowing()) dialog.dismiss(); dialog.show(); } catch (Exception e) { e.printStackTrace(); } } public void searchUser(boolean resetVariables,boolean showDialog) { // loginModel.getUserId(); isLoading = true; if(resetVariables) resetListVariables(); Call<SearchUserListModel> objectCall = RestClient.getApiClient().searchUser(searchFragment.searchStrUser,pageNo); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeSearchUser), showDialog); } @Override public void onBackPressed() { homeActivity.popFragment(); } }21)SettingsFragment.java===============================package com.eppico.fragments; import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.graphics.Color;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v7.widget.GridLayoutManager;import android.support.v7.widget.RecyclerView;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView; import com.eppico.R;import com.eppico.activity.HomeActivity;import com.eppico.activity.LoginActivity;import com.eppico.api.RestClient;import com.eppico.models.AppUserModel;import com.eppico.models.CheckedInSpotModel;import com.eppico.models.InviteSpotDetailModel;import com.eppico.models.LoginModel;import com.eppico.models.LogoutModel;import com.eppico.utility.Constants;import com.eppico.utility.CustomDialog;import com.eppico.utility.PrefHelper;import com.eppico.utility.ToastHelper;import com.eppico.widgets.EasyDialog;import com.facebook.login.LoginManager; import java.util.ArrayList;import java.util.HashMap; import retrofit2.Call;import retrofit2.Response; /** * Created by manisha on 17/12/16. */ public class SettingsFragment extends BaseFragment { private View mainView; private TextView txtPushNotification,txtPrivacyPolicy,txtContactUs,txtSignOut,txtTermsConditions; private LinearLayout lytPushNotification; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mainView = inflater.inflate(R.layout.fragment_settings, container, false); init(); return mainView; } private void init() { // Set Sliding Menu disable homeActivity.setSlidingMenuEnable(true); // Setup Actionbar ImageView actionBarRightMenu = (ImageView) mainView.findViewById(R.id.actionBarRightMenu); TextView actionBarTitle = (TextView) mainView.findViewById(R.id.actionBarTitle); txtPushNotification = (TextView) mainView.findViewById(R.id.txtPushNotification); txtPrivacyPolicy = (TextView) mainView.findViewById(R.id.actionBarTitle); txtContactUs = (TextView) mainView.findViewById(R.id.txtContactUs); txtSignOut = (TextView) mainView.findViewById(R.id.txtSignOut); txtTermsConditions = (TextView) mainView.findViewById(R.id.txtTermsConditions); actionBarRightMenu.setVisibility(View.INVISIBLE); actionBarTitle.setText(getString(R.string.screenTitleSettings)); } @Override public void clickEvent(View v) { Bundle bundle=null; switch (v.getId()) { case R.id.actionBarMenu: // Back button homeActivity.toggleSlidingMenu(); break; case R.id.txtSignOut: showLogoutAlert(); break; case R.id.txtPushNotification: CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.strComingSoon)); break; case R.id.txtPrivacyPolicy: bundle=new Bundle(); bundle.putInt(getString(R.string.extraCMSPageId), Constants.CMS_PAGE.PRIVACY_POLICY.ordinal()); CMSPageFragment cmsPageFragment=new CMSPageFragment(); cmsPageFragment.setArguments(bundle); homeActivity.pushFragments(cmsPageFragment,true,false,true); break; case R.id.txtTermsConditions: bundle=new Bundle(); bundle.putInt(getString(R.string.extraCMSPageId), Constants.CMS_PAGE.TERMS_CONDITION.ordinal()); CMSPageFragment cmsPageFragment1=new CMSPageFragment(); cmsPageFragment1.setArguments(bundle); homeActivity.pushFragments(cmsPageFragment1,true,false,true); break; case R.id.txtContactUs: CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.strComingSoon)); break; } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if (reqCode == getResources().getInteger(R.integer.reqCodeLogout)) { ArrayList<String> prefShouldNotClear = new ArrayList<String>(); prefShouldNotClear.add(getString(R.string.prefDeviceToken)); //Clear preferences PrefHelper.deletePreferencesExcept(prefShouldNotClear); //Set Auth key to Rest client homeActivity.restClient.setupRestClient(getActivity(),""); //Logout from facebook LoginManager.getInstance().logOut(); Intent intent = new Intent(getActivity(), LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); getActivity().finish(); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { ToastHelper.getInstance().showToast(getActivity(),object.toString()); } //Show Logout alert dialog public void showLogoutAlert() { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); //builder.setTitle(title); builder.setCancelable(true); builder.setMessage(getString(R.string.msgLogoutAlert)); builder.setPositiveButton(getString(R.string.btnYes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); callLogoutAPI(); } }); builder.setNegativeButton(getString(R.string.btnNo), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); // create alert dialog AlertDialog alertDialog = builder.create(); // show it alertDialog.show(); } private void callLogoutAPI() { Call<LogoutModel> objectCall = RestClient.getApiClient().logout(/*homeActivity.loginModel.getUserId()+""*/); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeLogout), true); } @Override public void onBackPressed() { homeActivity.popFragment(); } }
No comments:
Post a Comment