pacakges: activity/api
1) BaseActivity.java
======================
package com.eppico.activity;
import android.Manifest;import android.app.Activity;import android.content.Intent;import android.content.IntentSender;import android.content.pm.PackageManager;import android.location.Location;import android.os.Bundle; import android.support.annotation.NonNull;import android.support.annotation.Nullable;import android.support.v4.app.ActivityCompat;import android.support.v7.app.AppCompatActivity;import android.widget.Toast; import com.eppico.MyApplication;import com.eppico.R;import com.eppico.api.ApiResponseListener;import com.eppico.api.RestClient;import com.eppico.interfaces.LocationUpdateListener;import com.eppico.utility.CustomDialog;import com.eppico.utility.MyLog;import com.eppico.utility.PermissionUtil;import com.eppico.utility.PrefHelper;import com.eppico.utility.ToastHelper;import com.google.android.gms.common.ConnectionResult;import com.google.android.gms.common.GoogleApiAvailability;import com.google.android.gms.common.api.GoogleApiClient;import com.google.android.gms.common.api.PendingResult;import com.google.android.gms.common.api.ResultCallback;import com.google.android.gms.common.api.Status;import com.google.android.gms.location.LocationListener;import com.google.android.gms.location.LocationRequest;import com.google.android.gms.location.LocationServices;import com.google.android.gms.location.LocationSettingsRequest;import com.google.android.gms.location.LocationSettingsResult;import com.google.android.gms.location.LocationSettingsStates;import com.google.android.gms.location.LocationSettingsStatusCodes; import retrofit2.Call;import retrofit2.Response; /** * Created by manisha on 12/12/16. */ public class BaseActivity extends AppCompatActivity implements ApiResponseListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { //Location get Related variables private static final int REQUEST_CODE_RECOVER_PLAY_SERVICES = 2000; private static final int REQUEST_CHECK_SETTINGS = 2001; private static final int REQ_PERMISSION_LOCATION = 1001; private GoogleApiClient mGoogleApiClient; //private Location mLastLocation; private LocationRequest mLocationRequest; LocationUpdateListener locationUpdateListener; public RestClient restClient; public MyApplication appInstance; private LocationSettingsRequest.Builder builder; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); appInstance = (MyApplication) getApplication(); restClient = appInstance.getRestClient(); } /** * Get current location using FusedLocationProviderApi. * on location found it will called onLocationChanged() of current activity * * @param locationUpdateListener */ public void getCurrentLocation(LocationUpdateListener locationUpdateListener) { this.locationUpdateListener = locationUpdateListener; if (checkLocationPermission()) { //Connect Google API client if (checkGooglePlayServices()) { /**Note: This dialog is hide at onLocationChanged() and onAcitvityResult(When user cancel request of enable GPS)*/ //customDialog.show(getActivity(),getString(R.string.txtLoadingFindingLocation),false); CustomDialog.getInstance().show(this, getString(R.string.msgGettingLocation), false); buildGoogleApiClient(); //prepare connection request createLocationRequest(); } } } /** * Initialize Google API Client */ protected synchronized void buildGoogleApiClient() { if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { onConnected(new Bundle()); } else { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } } /*Maker location update request*/ protected void startLocationUpdates() { if (checkLocationPermission()) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); } } /** * Initialize location request */ protected void createLocationRequest() { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(20000); mLocationRequest.setFastestInterval(5000); mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); settingsRequest(); } private boolean checkLocationPermission() { // Check if the Location permission is already available. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Location permission has not been granted. requestLocationPermission(); } else { // Location permissions is already available, show the camera preview. return true; } return false; } /** * Requests the Location permission. * If the permission has been denied previously, a SnackBar will prompt the user to grant the * permission, otherwise it is requested directly. */ private void requestLocationPermission() { /* if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION)) { // Provide an additional rationale to the user if the permission was not granted // and the user would benefit from additional context for the use of the permission. // For example if the user has previously denied the permission. ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQ_PERMISSION_LOCATION); } else { // Location permission has not been granted yet. Request it directly. ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQ_PERMISSION_LOCATION); }*/ ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQ_PERMISSION_LOCATION); } /** * GPS is disable show setting dialog to enabled */ private void settingsRequest() { builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest); builder.setAlwaysShow(true); //this is the key ingredient PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build()); result.setResultCallback(new ResultCallback<LocationSettingsResult>() { @Override public void onResult(LocationSettingsResult result) { final Status status = result.getStatus(); final LocationSettingsStates state = result.getLocationSettingsStates(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: // All location settings are satisfied. The client can initialize location // requests here. break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: // Location settings are not satisfied. But could be fixed by showing the user // a dialog. try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). status.startResolutionForResult(BaseActivity.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { // Ignore the error. } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: // Location settings are not satisfied. However, we have no way to fix the // settings so we won't show the dialog. break; } } }); } /** * Stop Location update listener */ private void stopLocationUpdates() { if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); } } @Override public void onConnected(@Nullable Bundle bundle) { if(checkLocationPermission()) { /*Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); //Make Location request only when last location is null if (mLastLocation != null) { MyLog.v("LocationManager", "onConnected(): Latitude:" + mLastLocation.getLatitude() + " Longitude: " + mLastLocation.getLongitude()); updateLocation(mLastLocation); return; }*/ startLocationUpdates(); } //startLocationUpdates(); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } @Override public void onLocationChanged(Location location) { // stopLocationUpdates(); MyLog.v("LocationManager", "onLocationChanged(): Latitude:" + location.getLatitude() + "Longitude: " + location.getLongitude()); // ToastHelper.getInstance().showToast(BaseActivity.this, "Latitude: " + location.getLatitude() + "\nLongitude: " + location.getLongitude()); //ToastHelper.getInstance().showToast(BaseActivity.this, "ACCURACY : " + location.getAccuracy(), Toast.LENGTH_LONG); /*Location startPoint=new Location("locationA"); startPoint.setLatitude(17.372102); startPoint.setLongitude(78.484196);*/ //TODO Temporary store lat-lng into preference double latitude = PrefHelper.getDouble(getString(R.string.prefUserLatitude), 0); double longitude = PrefHelper.getDouble(getString(R.string.prefUserLongitude), 0); if (latitude > 0 && longitude > 0) { Location endPoint = new Location("locationA"); endPoint.setLatitude(latitude); endPoint.setLongitude(longitude); double distance = location.distanceTo(endPoint); MyLog.v("LocationManager", "Prev lat-lng and current Distance(In Meter): " + distance); } PrefHelper.setDouble(getString(R.string.prefUserLatitude), location.getLatitude()); PrefHelper.setDouble(getString(R.string.prefUserLongitude), location.getLongitude()); updateLocation(location); stopLocationUpdates(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_CODE_RECOVER_PLAY_SERVICES: /*if (resultCode == RESULT_OK) { // Make sure the app is not already connected or attempting to connect if (!mGoogleApiClient.isConnecting() && !mGoogleApiClient.isConnected()) { mGoogleApiClient.connect(); } } else if (resultCode == RESULT_CANCELED) { }*/ break; // Check for the integer request code originally supplied to startResolutionForResult(). case REQUEST_CHECK_SETTINGS: switch (resultCode) { case Activity.RESULT_OK: startLocationUpdates(); break; case Activity.RESULT_CANCELED: // User cancel enable GPS CustomDialog.getInstance().hide(); if (locationUpdateListener != null) locationUpdateListener.onGPSRequestDeny(); break; } break; } } /** * Callback received when a permissions request has been completed. */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == REQ_PERMISSION_LOCATION) { // BEGIN_INCLUDE(permission_result) // Check if the only required permission has been granted// if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (PermissionUtil.verifyPermissions(grantResults)) { // startLocationUpdates(); //Connect Google API client if (checkGooglePlayServices()) { buildGoogleApiClient(); //prepare connection request createLocationRequest(); } } else { // Permission deny if (locationUpdateListener != null) locationUpdateListener.onLocationPermissionDeny(); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } private boolean checkGooglePlayServices() { GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance(); int result = googleAPI.isGooglePlayServicesAvailable(this); if (result != ConnectionResult.SUCCESS) { if (googleAPI.isUserResolvableError(result)) { googleAPI.getErrorDialog(this, result, REQUEST_CODE_RECOVER_PLAY_SERVICES).show(); } return false; } return true; } private void updateLocation(Location location) { // Hide Dialog which is show on getCurrentLocation() CustomDialog.getInstance().hide(); if (locationUpdateListener != null) locationUpdateListener.onLocationUpdate(location); } @Override public void onPause() { super.onPause(); stopLocationUpdates(); } @Override public void onStop() { super.onStop(); if (mGoogleApiClient != null) { mGoogleApiClient.disconnect(); } } @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)FullScreenViewActivity.java
=========================================
package com.eppico.activity;package com.eppico.activity; /** * Created by manisha on 27/12/16. */ import android.app.Activity;import android.content.Context;import android.content.Intent;import android.os.Build;import android.os.Bundle;import android.support.v4.view.ViewPager;import android.view.View;import android.view.Window;import android.view.WindowManager;import android.widget.ImageView;import java.util.ArrayList;import android.app.Activity;import android.content.Context;import android.content.Intent;import android.os.Build;import android.os.Bundle;import android.support.v4.view.ViewPager;import android.view.View;import android.view.View.OnClickListener;import android.view.Window;import android.view.WindowManager;import android.widget.ImageView; import com.bumptech.glide.Glide;import com.eppico.R;import com.eppico.utility.Utils; import java.util.ArrayList; public class FullScreenViewActivity extends Activity implements View.OnClickListener { private ImageView imgClose,imgBig; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); FullScreencall(); setContentView(R.layout.activity_fullscreen_view);// int width = this.getResources().getDisplayMetrics().widthPixels;// int height = this.getResources().getDisplayMetrics().heightPixels;// height = height-150;//// WindowManager.LayoutParams params = getWindow().getAttributes();// params.x = -20;// params.height = width;// params.width = width;// params.y = -10;// this.getWindow().setAttributes(params); imgClose = (ImageView) findViewById(R.id.imgClose); imgClose.setOnClickListener(this); imgBig = (ImageView)findViewById(R.id.imgBig); if(getIntent() != null) { if (getIntent().getExtras() != null) { String strUrl = getIntent().getExtras().getString(getResources().getString(R.string.extraBigImage)); if (Utils.validateString(strUrl)) { Glide.with(this) .load(strUrl) .placeholder(R.mipmap.spot_default_img) .error(R.mipmap.spot_default_img) // TODO: Later change this default placeholder .into(imgBig); } } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); getWindow().setStatusBarColor(getResources().getColor(R.color.colorAccent)); } } @Override protected void onResume() { super.onResume(); FullScreencall(); } public void FullScreencall() { if (Build.VERSION.SDK_INT < 19) { View v = this.getWindow().getDecorView(); v.setSystemUiVisibility(View.GONE); } else { View decorView = getWindow().getDecorView(); int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; decorView.setSystemUiVisibility(uiOptions); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.imgClose: finish(); break; default: break; } } }3)HomeActivity.java============================
import android.app.Dialog;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.res.TypedArray;import android.os.Bundle;import android.os.Handler;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.support.v4.view.GravityCompat;import android.support.v4.widget.DrawerLayout;import android.support.v7.app.ActionBarDrawerToggle;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.RecyclerView;import android.util.Log;import android.view.Gravity;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.FrameLayout;import android.widget.ImageView;import android.widget.TextView; import com.bumptech.glide.Glide;import com.eppico.MyApplication;import com.eppico.R;import com.eppico.adapter.CheckInUserAdapter;import com.eppico.adapter.InviteSpotDetailAdapter;import com.eppico.adapter.SlidingMenuAdapter;import com.eppico.fragments.CheckInUserFragment;import com.eppico.fragments.CreateNewSpotFragment;import com.eppico.fragments.FollowersListFragment;import com.eppico.fragments.FollowingSpotFragment;import com.eppico.fragments.HomeFragment;import com.eppico.fragments.InviteSpotDetailFragment;import com.eppico.fragments.InvitedSpotFragment;import com.eppico.fragments.MyProfileFragment;import com.eppico.fragments.SearchFragment;import com.eppico.fragments.SettingsFragment;import com.eppico.interfaces.BackPressedEventListener;import com.eppico.interfaces.ClickEventListener; import com.eppico.interfaces.RecyclerViewItemClickListener;import com.eppico.models.FollowersListModel;import com.eppico.models.LoginModel;import com.eppico.utility.Constants;import com.eppico.utility.CustomDialog;import com.eppico.utility.PrefHelper;import com.eppico.utility.Utils;import com.eppico.widgets.ShapedImageView; public class HomeActivity extends BaseActivity /*implements View.OnClickListener*/ { // XML Components DrawerLayout drawerLayout; RecyclerView recyclerViewSlidingMenu; public FragmentManager fragmentManager; public Fragment currentFragment; private ImageView imageUser; public LoginModel loginModel; BackPressedEventListener backPressedEventListener; ClickEventListener clickEventListener; SlidingMenuAdapter slidingMenuAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); init(); } private void init() { try { fragmentManager = getSupportFragmentManager(); String loginUserData = PrefHelper.getString(getString(R.string.prefLoginUserData), ""); if (loginUserData.trim().length() > 0) { loginModel = (LoginModel) LoginModel.toModelClass(loginUserData, LoginModel.class); } imageUser = (ImageView) findViewById(R.id.imageUser); //imageUser.setOnClickListener(this); initSlidingMenu(); setupSlidingMenuData(loginModel); pushFragments(new HomeFragment(), false, false, true); } catch (Exception e) { e.printStackTrace(); } } private void initSlidingMenu() { drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); final FrameLayout container = (FrameLayout) findViewById(R.id.container); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close) { public void onDrawerClosed(View view) { supportInvalidateOptionsMenu(); } public void onDrawerOpened(View drawerView) { supportInvalidateOptionsMenu(); } @Override public void onDrawerSlide(View drawerView, float slideOffset) { super.onDrawerSlide(drawerView, slideOffset); /*if (drawerLayout.isDrawerVisible(GravityCompat.END) || drawerLayout.isDrawerVisible(Gravity.RIGHT)) { linlayScreen.setTranslationX(-(slideOffset * drawerView.getWidth())); drawerLayout.bringChildToFront(drawerView); drawerLayout.requestLayout(); } else */ if (drawerLayout.isDrawerVisible(GravityCompat.START) || drawerLayout.isDrawerVisible(Gravity.LEFT)) { container.setTranslationX((slideOffset * drawerView.getWidth())); drawerLayout.bringChildToFront(drawerView); drawerLayout.requestLayout(); } } }; //drawerLayout.setBackground(new ColorDrawable(ContextCompat.getColor(this, android.R.color.transparent))); drawerLayout.addDrawerListener(toggle); toggle.syncState(); toggle.setDrawerIndicatorEnabled(false); } public void setupSlidingMenuData(LoginModel loginModel) { //Set Logged in user data if (loginModel != null) { ShapedImageView imageUser = (ShapedImageView) findViewById(R.id.imageUser); TextView txtUserName = (TextView) findViewById(R.id.txtUserName); txtUserName.setText(Utils.getInstance().unescapeJava(loginModel.getFirstName() + " " + loginModel.getLastName())); Glide.with(this) .load(loginModel.getUserimage()) .placeholder(R.mipmap.ic_default_profile) .into(imageUser); } recyclerViewSlidingMenu = (RecyclerView) findViewById(R.id.recyclerViewSlidingMenu); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); recyclerViewSlidingMenu.setLayoutManager(layoutManager); String arrayMenuItems[] = getResources().getStringArray(R.array.menu_items); TypedArray arrayIcons = getResources().obtainTypedArray(R.array.menu_icons); slidingMenuAdapter = new SlidingMenuAdapter(this, arrayMenuItems, arrayIcons, 0); recyclerViewSlidingMenu.setAdapter(slidingMenuAdapter); recyclerViewSlidingMenu.addOnItemTouchListener( new RecyclerViewItemClickListener(HomeActivity.this, new RecyclerViewItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, final int position) { setSelectedPositionInSlidingMenu(position); /*new Handler().postDelayed(new Runnable() { @Override public void run() { switch (position) { case 0: // Home toggleSlidingMenu(); if(!(currentFragment instanceof HomeFragment)) { removeAllFragment(); pushFragments(new HomeFragment(),false,false,true); } break; case 1: // Search CustomDialog.getInstance().showMessageDialog(HomeActivity.this, getResources().getString(R.string.strComingSoon)); break; case 2: // Create new spot// mReplaceFragment(new CreateNewSpotFragment(), null); toggleSlidingMenu(); if(!(currentFragment instanceof CreateNewSpotFragment)) { removeAllFragment(); pushFragments(new CreateNewSpotFragment(),false,false,true); } break; case 3: // Invited Spots// mReplaceFragment(new InvitedSpotFragment(), null); toggleSlidingMenu(); if(!(currentFragment instanceof InvitedSpotFragment)) { removeAllFragment(); pushFragments(new InvitedSpotFragment(),false,false,true); } break; case 4: // My Spots CustomDialog.getInstance().showMessageDialog(HomeActivity.this, getResources().getString(R.string.strComingSoon)); //toggleSlidingMenu();// mReplaceFragment(new PostDetailFragment(), null); //pushFragments(new PostDetailFragment(),false,false,true); break; case 5: // Following Spots CustomDialog.getInstance().showMessageDialog(HomeActivity.this, getResources().getString(R.string.strComingSoon));// if(!(currentFragment instanceof CheckInUserFragment))// {// removeAllFragment();// pushFragments(new CheckInUserFragment(),false,false,true);// } break; case 6: // Popular Spots CustomDialog.getInstance().showMessageDialog(HomeActivity.this, getResources().getString(R.string.strComingSoon)); break; case 7: // Notifications CustomDialog.getInstance().showMessageDialog(HomeActivity.this, getResources().getString(R.string.strComingSoon)); break; case 8: // Settings // Following Spots toggleSlidingMenu(); if(!(currentFragment instanceof SettingsFragment)) { removeAllFragment(); pushFragments(new SettingsFragment(),false,false,true); } break; } } },getResources().getInteger(R.integer.drawerAnimationDuration));*/ switch (position) { case 0: // Home toggleSlidingMenu(); new Handler().postDelayed(new Runnable() { @Override public void run() { removeAllFragment(); pushFragments(new HomeFragment(), false, false, true); } }, getResources().getInteger(R.integer.drawerAnimationDuration)); break; case 1: // Search // CustomDialog.getInstance().showMessageDialog(HomeActivity.this, getResources().getString(R.string.strComingSoon)); toggleSlidingMenu(); new Handler().postDelayed(new Runnable() { @Override public void run() { removeAllFragment(); pushFragments(new SearchFragment(), false, false, true); } }, getResources().getInteger(R.integer.drawerAnimationDuration)); break; case 2: // Create new spot// mReplaceFragment(new CreateNewSpotFragment(), null); toggleSlidingMenu(); new Handler().postDelayed(new Runnable() { @Override public void run() { removeAllFragment(); pushFragments(new CreateNewSpotFragment(), false, false, true); } }, getResources().getInteger(R.integer.drawerAnimationDuration)); break; case 3: // Invited Spots// mReplaceFragment(new InvitedSpotFragment(), null); toggleSlidingMenu(); new Handler().postDelayed(new Runnable() { @Override public void run() { removeAllFragment(); Bundle bundle = new Bundle(); bundle.putInt(getString(R.string.extraSpotListType), Constants.SPOT_LIST_TYPE.INVITED_SPOT.ordinal()); InvitedSpotFragment invitedSpotFragment = new InvitedSpotFragment(); invitedSpotFragment.setArguments(bundle); pushFragments(invitedSpotFragment, false, false, true); } }, getResources().getInteger(R.integer.drawerAnimationDuration)); break; case 4: // My Spots toggleSlidingMenu(); new Handler().postDelayed(new Runnable() { @Override public void run() { removeAllFragment(); Bundle bundle = new Bundle(); bundle.putInt(getString(R.string.extraSpotListType), Constants.SPOT_LIST_TYPE.MY_SPOT.ordinal()); InvitedSpotFragment invitedSpotFragment = new InvitedSpotFragment(); invitedSpotFragment.setArguments(bundle); pushFragments(invitedSpotFragment, false, false, true); } }, getResources().getInteger(R.integer.drawerAnimationDuration)); break; case 5: // Following Spots toggleSlidingMenu(); new Handler().postDelayed(new Runnable() { @Override public void run() { removeAllFragment(); pushFragments(new FollowingSpotFragment(), false, false, true); } }, getResources().getInteger(R.integer.drawerAnimationDuration)); break; case 6: // Popular Spots CustomDialog.getInstance().showMessageDialog(HomeActivity.this, getResources().getString(R.string.strComingSoon)); break; case 7: // Notifications CustomDialog.getInstance().showMessageDialog(HomeActivity.this, getResources().getString(R.string.strComingSoon)); break; case 8: // Settings // Following Spots toggleSlidingMenu(); new Handler().postDelayed(new Runnable() { @Override public void run() { removeAllFragment(); pushFragments(new SettingsFragment(), false, false, true); } }, getResources().getInteger(R.integer.drawerAnimationDuration)); break; } } }) ); } /*public void setSlidingMenuSelectedItem(int position) { SlidingMenuAdapter slidingMenuAdapter= (SlidingMenuAdapter) recyclerViewSlidingMenu.getAdapter(); if(slidingMenuAdapter!=null && slidingMenuAdapter.getItemCount()>0) slidingMenuAdapter.setItemSelected(position); }*/ /*private void mReplaceFragment(Fragment fragment, Bundle b) { currentFragment = fragment; FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); if (b != null) fragment.setArguments(b); transaction.replace(R.id.container, fragment);// transaction.addToBackStack(null); transaction.commit(); }*/ public void clickEvent(View view) { switch (view.getId()) { case R.id.linProfile: toggleSlidingMenu(); new Handler().postDelayed(new Runnable() { @Override public void run() { // if (!(currentFragment instanceof MyProfileFragment)) { MyProfileFragment myProfileFragment = new MyProfileFragment(); Bundle bundle = new Bundle(); bundle.putInt(getResources().getString(R.string.extraUserId), loginModel.getUserId()); bundle.putInt(getString(R.string.extraFromScreen),Constants.FROM_SCREEN.MENU.ordinal()); myProfileFragment.setArguments(bundle); pushFragments(myProfileFragment, false, false, true);// } } }, getResources().getInteger(R.integer.drawerAnimationDuration)); break; /* case R.id.linProfile: toggleSlidingMenu(); MyProfileFragment myProfileFragment = new MyProfileFragment(); pushFragments(myProfileFragment, false, false, true); break;*/ default: if (clickEventListener != null) clickEventListener.clickEvent(view); break; } } /** * Toggle sliding menu */ public void toggleSlidingMenu() { if (isSlidingMenuOpen()) { drawerLayout.closeDrawer(GravityCompat.START); } else { drawerLayout.openDrawer(GravityCompat.START); } } /** * Return true if sliding menu is open otherwise return false */ public boolean isSlidingMenuOpen() { if (drawerLayout != null && drawerLayout.isDrawerOpen(GravityCompat.START)) return true; return false; } public void setSlidingMenuEnable(boolean enable) { if (enable) drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); else drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); } public void setSelectedPositionInSlidingMenu(int position) { if (slidingMenuAdapter != null) slidingMenuAdapter.setItemSelected(position); } /** * Replace fragment */ public void pushFragments(Fragment fragment, boolean shouldAnimate, boolean isReverse, boolean shouldAddBackStack) { try { // backApiResponse = (OnBackApiResponse) fragment; clickEventListener = (ClickEventListener) fragment; backPressedEventListener = (BackPressedEventListener) fragment; FragmentTransaction ft = fragmentManager.beginTransaction(); currentFragment = fragment; if (shouldAnimate) { if (!isReverse) { ft.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left, R.anim.slide_in_left, R.anim.slide_out_right);// ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_left, R.anim.slide_in_right, R.anim.slide_out_right); } else ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right, R.anim.slide_in_left, R.anim.slide_out_right); //ft.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right, R.anim.slide_in_right, R.anim.slide_out_left); } //Create Unique Fragment tag name String fragmentTag = fragment.getClass().getName() + System.currentTimeMillis(); ft.replace(R.id.container, fragment, fragmentTag); if (shouldAddBackStack) ft.addToBackStack(fragmentTag); ft.commit(); } catch (Exception e) { e.printStackTrace(); } } public void popFragment() { try { int backStackCount = fragmentManager.getBackStackEntryCount(); if (backStackCount > 1) { FragmentManager.BackStackEntry backEntry = fragmentManager.getBackStackEntryAt(backStackCount - 2); String str = backEntry.getName(); Fragment fragment = fragmentManager.findFragmentByTag(str); backPressedEventListener = (BackPressedEventListener) fragment; clickEventListener = (ClickEventListener) fragment; currentFragment = fragment; fragmentManager.popBackStack(); } else { if (currentFragment instanceof HomeFragment) finish(); else pushFragments(new HomeFragment(), true, true, false); } } catch (Exception e) { e.printStackTrace(); } } /*Remove all fragments from back stack*/ public void removeAllFragment() { int fragmentsCount = fragmentManager.getBackStackEntryCount(); if (fragmentsCount > 0) { MyApplication.DISABLE_FRAGMENT_ANIMATION = true; FragmentTransaction ft = fragmentManager.beginTransaction(); //manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); fragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); ft.commit(); MyApplication.DISABLE_FRAGMENT_ANIMATION = false; //fragmentManager.popBackStack("myfancyname", FragmentManager.POP_BACK_STACK_INCLUSIVE); } //removeFragmentUntil(DrinkListFragment); } /*Remove Fragments until provided Fragment class*/ public void removeFragmentUntil(Class<?> fragmentClass) { try { int backStackCountMain = fragmentManager.getBackStackEntryCount(); if (backStackCountMain > 1) { MyApplication.DISABLE_FRAGMENT_ANIMATION = true; int backStackCount = backStackCountMain; for (int i = 0; i < backStackCountMain; i++) { FragmentManager.BackStackEntry backEntry = fragmentManager.getBackStackEntryAt(backStackCount - 1); String str = backEntry.getName(); Fragment fragment = fragmentManager.findFragmentByTag(str); if (fragment.getClass().getCanonicalName().equals(fragmentClass.getCanonicalName())) { break; } else fragmentManager.popBackStack(); backStackCount--; } new Handler().postDelayed(new Runnable() { @Override public void run() { MyApplication.DISABLE_FRAGMENT_ANIMATION = false; } }, 300); } else finish(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onBackPressed() { //super.onBackPressed(); if (drawerLayout.isDrawerOpen(GravityCompat.START)) { toggleSlidingMenu(); return; } if (backPressedEventListener != null) backPressedEventListener.onBackPressed(); } BroadcastReceiver broadcastReceiver=new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { } };}
4)ImageCropActivity.java
==============================
package com.eppico.activity; import android.content.Intent;import android.graphics.Bitmap;import android.graphics.Color;import android.graphics.drawable.GradientDrawable;import android.net.Uri;import android.os.Bundle;import android.os.Handler;import android.support.design.widget.Snackbar;import android.support.v7.app.ActionBar;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.KeyEvent;import android.view.View;import android.view.WindowManager;import android.widget.Button;import android.widget.FrameLayout;import android.widget.ImageView;import android.widget.TextView;import android.widget.Toast; //import com.credencys.goscoop.R;//import com.credencys.goscoop.customfunctions.CropImageView;//import com.credencys.goscoop.customfunctions.CustomizeViews;//import com.credencys.goscoop.utils.AppPrefs;//import com.credencys.goscoop.utils.StaticUtils;import com.eppico.R;import com.eppico.utility.Constants;import com.eppico.utility.FileUtils;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils;import com.eppico.widgets.CropImageView; import java.io.File; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. */public class ImageCropActivity extends AppCompatActivity implements CropImageView.OnSetImageUriCompleteListener, CropImageView.OnGetCroppedImageCompleteListener { //private static final int DEFAULT_ASPECT_RATIO_VALUES = 20; private int mAspectRatioX;//DEFAULT_ASPECT_RATIO_VALUES; private int mAspectRatioY;//DEFAULT_ASPECT_RATIO_VALUES; private static final String ASPECT_RATIO_X = "ASPECT_RATIO_X"; private static final String ASPECT_RATIO_Y = "ASPECT_RATIO_Y"; private CropImageView mIvCropView; private FrameLayout mImgCropScreenView; // Saves the state upon rotating the screen/restarting the activity private Uri imageUri; public static String EXTRA_IMAGE_PATH="imagePath",EXTRA_X_RATIO="xratio",EXTRA_Y_RATIO="yratio"; @Override protected void onSaveInstanceState(@SuppressWarnings("NullableProblems") Bundle bundle) { super.onSaveInstanceState(bundle); bundle.putInt(ASPECT_RATIO_X, mAspectRatioX); bundle.putInt(ASPECT_RATIO_Y, mAspectRatioY); } // Restores the state upon rotating the screen/restarting the activity @Override protected void onRestoreInstanceState(@SuppressWarnings("NullableProblems") Bundle bundle) { super.onRestoreInstanceState(bundle); mAspectRatioX = bundle.getInt(ASPECT_RATIO_X); mAspectRatioY = bundle.getInt(ASPECT_RATIO_Y); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_image_crop); // ActionBar actionBar = getSupportActionBar();// if (actionBar != null) {// actionBar.hide();// } mImgCropScreenView = (FrameLayout) findViewById(R.id.xImgCropView); Intent i = getIntent(); Bundle bundle=i.getExtras(); if(bundle!=null) { mAspectRatioX = bundle.getInt(EXTRA_X_RATIO, 16); mAspectRatioY = bundle.getInt(EXTRA_Y_RATIO, 26); if(bundle.containsKey(EXTRA_IMAGE_PATH)) imageUri= Uri.fromFile(new File(bundle.getString(EXTRA_IMAGE_PATH))); } /*if (getIntent().hasExtra("uri")) { Constants.IMAGE_URI = Uri.parse(getIntent().getStringExtra("uri")); }*/ mIvCropView = (CropImageView) findViewById(R.id.xIvCropView); mIvCropView.setCropShape(CropImageView.CropShape.RECTANGLE); mIvCropView.setFixedAspectRatio(true); mIvCropView.setAspectRatio(mAspectRatioX, mAspectRatioY);//(DEFAULT_ASPECT_RATIO_VALUES, DEFAULT_ASPECT_RATIO_VALUES); mIvCropView.setGuidelines(2); mIvCropView.setScaleType(ImageView.ScaleType.FIT_CENTER); //StaticUtils.printErr("Image URI Image crop on create: " + StaticUtils.IMAGE_URI); /*if (Constants.IMAGE_URI != null) mIvCropView.setImageUriAsync(Constants.IMAGE_URI); else ToastHelper.getInstance().showToast(this,getString(R.string.msgFailedToLoadImage))*/; if (imageUri != null) mIvCropView.setImageUriAsync(imageUri); else ToastHelper.getInstance().showToast(this,getString(R.string.msgFailedToLoadImage)); TextView btnCancel = (TextView) findViewById(R.id.xBtnCropCancel); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); TextView btnDone = (TextView) findViewById(R.id.xBtnCropOk); btnDone.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Constants.BTN_OK_CLICKED = true; mIvCropView.getCroppedImageAsync(mIvCropView.getCropShape(), 0, 0); /*new Handler().postDelayed(new Runnable() { public void run() { if (Constants.CROPPED_BITMAP == null) { Toast.makeText(ImageCropActivity.this, "error in crop", Toast.LENGTH_LONG).show(); } ImageCropActivity.this.finish(); } }, 2000);*/ } }); } @Override protected void onStart() { super.onStart(); mIvCropView.setOnSetImageUriCompleteListener(this); mIvCropView.setOnGetCroppedImageCompleteListener(this); } @Override protected void onStop() { super.onStop(); mIvCropView.setOnSetImageUriCompleteListener(null); mIvCropView.setOnGetCroppedImageCompleteListener(null); } @Override public void onSetImageUriComplete(CropImageView view, Uri uri, Exception error) { if (error == null) { Log.e("IMAGE CROP", "IMAGE uri: : " + uri + " PATH : " + uri.getPath()); } else { // StaticUtils.mShowToast(mImgCropScreenView, "Failed to load image!", Snackbar.LENGTH_SHORT); ToastHelper.getInstance().showToast(this,getString(R.string.msgFailedToLoadImage)); } } @Override public void onGetCroppedImageComplete(CropImageView view, Bitmap bitmap, Exception error) { if (error == null) { // Constants.CROPPED_BITMAP = bitmap; String croppedImagePath=FileUtils.getInstance().saveBitmapWithPath(bitmap,imageUri.getPath()); Intent intent=new Intent(); intent.putExtra(EXTRA_IMAGE_PATH,croppedImagePath); setResult(RESULT_OK,intent); finish(); } else { ToastHelper.getInstance().showToast(this,getString(R.string.msgImageCropFailed));// StaticUtils.mShowToast(mImgCropScreenView, "Image crop failed: " + error.getMessage(), Snackbar.LENGTH_SHORT); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { onBackPressed(); return true; } return super.onKeyDown(keyCode, event); } @Override public void onBackPressed() { Constants.BTN_OK_CLICKED = false; ImageCropActivity.this.finish(); } }5)LoginActivity.java=======================package com.eppico.activity; import android.Manifest;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageManager;import android.content.res.Configuration;import android.content.res.Resources;import android.graphics.Bitmap;import android.graphics.PorterDuff;import android.graphics.drawable.Drawable;import android.location.Location;import android.os.Bundle;import android.support.annotation.NonNull;import android.support.v4.app.ActivityCompat;import android.util.DisplayMetrics;import android.util.Log;import android.view.View;import android.view.WindowManager;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast; import com.bumptech.glide.Glide;import com.bumptech.glide.request.animation.GlideAnimation;import com.bumptech.glide.request.target.SimpleTarget;import com.eppico.MyApplication;import com.eppico.activity.BaseActivity;import com.eppico.R;import com.eppico.api.ApiResponseListener;import com.eppico.api.RestClient;import com.eppico.interfaces.LocationUpdateListener;import com.eppico.models.LoginModel;import com.eppico.models.RadiusModel;import com.eppico.models.SpotModel;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.facebook.AccessToken;import com.facebook.CallbackManager;import com.facebook.FacebookCallback;import com.facebook.FacebookException;import com.facebook.FacebookSdk;import com.facebook.GraphRequest;import com.facebook.GraphResponse;import com.facebook.login.LoginManager;import com.facebook.login.LoginResult;import com.facebook.login.widget.ProfilePictureView;import com.facebook.share.model.GameRequestContent;import com.facebook.share.widget.GameRequestDialog; import org.json.JSONException;import org.json.JSONObject; import java.io.File;import java.util.Arrays;import java.util.Collections;import java.util.List;import java.util.Locale;import java.util.Random; import okhttp3.MediaType;import okhttp3.MultipartBody;import okhttp3.RequestBody;import retrofit2.Call;import retrofit2.Response; /** * Created by manisha on 12/12/16. */public class LoginActivity extends BaseActivity { //Facebook variables private CallbackManager mCallbackManager; LoginModel loginModel; private static final int REQ_PERMISSION_WRITE_STORAGE = 1002; private static final int REQ_PERMISSION_WRITE_STORAGE_FROM_DIALOG = 1003; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); initFacebook(); setContentView(R.layout.activity_login); init(); //initGameRequest(); } private void init() { /*MyApplication myApplication = (MyApplication) getApplication(); restClient = myApplication.getRestClient();*/ } /** * Initialize Facebook SDK and required variables */ private void initFacebook() { // Initialize the SDK before executing any other operations. //FacebookSdk.sdkInitialize(this.getApplicationContext()); mCallbackManager = CallbackManager.Factory.create(); LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(final LoginResult loginResult) { if (loginResult.getAccessToken() == null) { LoginManager.getInstance().logOut(); return; } getFacebookUserInfo(loginResult.getAccessToken()); //Show progress dialog while fetching user data from facebook /*CustomDialog.getInstance().show(LoginActivity.this,false); // Make request for get User data GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject userObject, GraphResponse response) { try { //CustomDialog.getInstance().hide(); String userID = userObject.optString("id"); String profileImageURL = String.format(getString(R.string.profileImageUrlFB), userID); loginModel = new LoginModel(); loginModel.setFacebookId(userObject.optString("id")); loginModel.setFirstName(userObject.optString("first_name")); loginModel.setLastName(userObject.optString("last_name")); loginModel.setEmail(userObject.optString("email")); loginModel.setUserimage(profileImageURL); loadUserImage(profileImageURL); } catch (Exception e) { e.printStackTrace(); } } } ); Bundle parameters = new Bundle(); parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location"); // For picture "picture.type(large)" request.setParameters(parameters); request.executeAsync();*/ } @Override public void onCancel() { CustomDialog.getInstance().hide(); } @Override public void onError(FacebookException exception) { exception.printStackTrace(); CustomDialog.getInstance().hide(); } }); } private void getFacebookUserInfo(AccessToken accessToken) { if(accessToken!=null) { CustomDialog.getInstance().show(LoginActivity.this,false); // Make request for get User data GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject userObject, GraphResponse response) { try { //CustomDialog.getInstance().hide(); String userID = userObject.optString("id"); /*String firstName = userObject.optString("first_name"); String lastName = userObject.optString("last_name"); String email = userObject.optString("email");// String profileImageURL="https://graph.facebook.com/" + userID + "/picture?type=large";*/ String profileImageURL = String.format(getString(R.string.profileImageUrlFB), userID); loginModel = new LoginModel(); loginModel.setFacebookId(userObject.optString("id")); loginModel.setFirstName(userObject.optString("first_name")); loginModel.setLastName(userObject.optString("last_name")); loginModel.setEmail(userObject.optString("email")); loginModel.setUserimage(profileImageURL); MyLog.v("LoginActivity","getFacebookUserInfo(): " + userObject.toString()); loadUserImage(profileImageURL); } catch (Exception e) { e.printStackTrace(); } } } ); Bundle parameters = new Bundle(); parameters.putString("fields", "id, first_name, last_name, email,gender, birthday, location"); // For picture "picture.type(large)" request.setParameters(parameters); request.executeAsync(); } } /** * Create target with strong reference otherwise Garbage Collector remove object from memory */ private SimpleTarget simpleTarget = new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap bitmap, GlideAnimation glideAnimation) { // Save image String imagePath = FileUtils.getInstance().saveBitmap(LoginActivity.this, bitmap, getString(R.string.dirSettings)); MyLog.v("imagePath", "imagePath: " + imagePath); loginModel.setUserImageLocal(imagePath); CustomDialog.getInstance().hide(); callLoginAPI(); } @Override public void onLoadFailed(Exception e, Drawable errorDrawable) { super.onLoadFailed(e, errorDrawable); } }; /** * Download user image from URL */ private void loadUserImage(String imageUrl) { if (imageUrl != null && imageUrl.length() > 0) { Glide.with(this) .load(imageUrl) .asBitmap() .into(simpleTarget); } } private boolean checkStoragePermission(int reqCode) { // Check if the Location permission is already available. if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { // Write Storage permission has not been granted. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, reqCode); } else { // Write Storage permissions is already available, show the camera preview. return true; } return false; } /** * Callback received when a permissions request has been completed. */ @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case REQ_PERMISSION_WRITE_STORAGE: if (PermissionUtil.verifyPermissions(grantResults)) { handleFacebookClickEvent(); } else { showEnableStoragePermissionDialog(); } break; /*If user deny storage permission then show enable storage dialog (showEnableStoragePermissionDialog()). If user press ok the again open store Permission Request dialog(Default) then user grant permission call loginWithFacebook() * */ case REQ_PERMISSION_WRITE_STORAGE_FROM_DIALOG: if (PermissionUtil.verifyPermissions(grantResults)) { loginWithFacebook(); } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } private void loginWithFacebook() { /*Note: If current access token is not null means use is logged in. So no need to logged in again*/ if(AccessToken.getCurrentAccessToken()==null) { //LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email")); LoginManager.getInstance().logInWithPublishPermissions(this, Collections.singletonList("publish_actions")); } else { getFacebookUserInfo(AccessToken.getCurrentAccessToken()); } } /** * Handle Activity click events */ public void clickEvent(View view) { switch (view.getId()) { case R.id.txtSignInWithFacebook: if (Utils.getInstance().checkInternetConnection(this)) { if(checkStoragePermission(REQ_PERMISSION_WRITE_STORAGE)) { /**Note: User can't not Login without current location*/ /*if (PrefHelper.getDouble(getString(R.string.prefUserLatitude), 0) > 0 && PrefHelper.getDouble(getString(R.string.prefUserLongitude), 0) > 0) { loginWithFacebook(); } else showLocationEnableDialog();*/ handleFacebookClickEvent(); } } else ToastHelper.getInstance().showToast(this, getString(R.string.msgInternetConnectionNotAvailable)); //onClickRequestButton(); break; } } /*GameRequestDialog requestDialog; CallbackManager callbackManagerGame; private void initGameRequest() { 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)); } public void onCancel() { MyLog.v("initGameRequest","onCancel: "); } public void onError(FacebookException error) { MyLog.v("initGameRequest","onError: " + error.getMessage()); } } ); }*/ private void onClickRequestButton() { 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); mCallbackManager.onActivityResult(requestCode, resultCode, data); /*if (mCallbackManager.onActivityResult(requestCode, resultCode, data)) { return; }*/ /*if (callbackManagerGame.onActivityResult(requestCode, resultCode, data)) { return; }*/ } private void handleFacebookClickEvent() { /**Note: User can't not Login without current location*/ if (PrefHelper.getDouble(getString(R.string.prefUserLatitude), 0) > 0 && PrefHelper.getDouble(getString(R.string.prefUserLongitude), 0) > 0) { loginWithFacebook(); } else getLocation();// showLocationEnableDialog(); } /** * Call Login API with all facebook data */ private void callLoginAPI() { try { if (loginModel != null) { File file = new File(loginModel.getUserImageLocal()); // 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("userImage", file.getName(), requestFile); // add another part within the multipart request RequestBody facebookId = RequestBody.create(MediaType.parse("multipart/form-data"), loginModel.getFacebookId()); RequestBody firstName = RequestBody.create(MediaType.parse("multipart/form-data"), loginModel.getFirstName()); RequestBody lastName = RequestBody.create(MediaType.parse("multipart/form-data"), loginModel.getLastName()); RequestBody email = RequestBody.create(MediaType.parse("multipart/form-data"), loginModel.getEmail()); RequestBody curLat = RequestBody.create(MediaType.parse("multipart/form-data"), PrefHelper.getDouble(getString(R.string.prefUserLatitude), 0) + ""); RequestBody curLong = RequestBody.create(MediaType.parse("multipart/form-data"), PrefHelper.getDouble(getString(R.string.prefUserLongitude), 0) + ""); RequestBody deviceToken = RequestBody.create(MediaType.parse("multipart/form-data"), PrefHelper.getString(getString(R.string.prefDeviceToken), "")); RequestBody userType = RequestBody.create(MediaType.parse("multipart/form-data"), getResources().getInteger(R.integer.userType) + ""); RequestBody deviceType = RequestBody.create(MediaType.parse("multipart/form-data"), getResources().getInteger(R.integer.deviceType) + ""); Call<LoginModel> objectCall = RestClient.getApiClient().loginUser(facebookId, firstName, lastName, email, curLat, curLong, deviceToken, userType, deviceType, body); restClient.makeApiRequest(this, objectCall, this, getResources().getInteger(R.integer.reqCodeLogin), true); } } catch (Exception e) { e.printStackTrace(); } } private void getSpotRadius() { Call<List<RadiusModel>> objectCall = RestClient.getApiClient().getSpotRadius(); restClient.makeApiRequest(this, objectCall, this, 10, true); } private void updateRadius() { Call<RadiusModel> objectCall = RestClient.getApiClient().updateRadius("Bhavesh"); restClient.makeApiRequest(this, objectCall, this, 10, true); } private void getSpot() { Call<List<SpotModel>> objectCall = RestClient.getApiClient().getSpotList(); restClient.makeApiRequest(this, objectCall, this, 10, true); } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { try { if (reqCode == getResources().getInteger(R.integer.reqCodeLogin)) { if (response != null) { LoginModel loginModel = (LoginModel) response.body(); // Save Logged in user data to preference PrefHelper.setString(getString(R.string.prefLoginUserData), loginModel.toJson().toString()); //Store Auth key to preference to use in rest all API calling PrefHelper.setString(getString(R.string.prefAuthKey),loginModel.getAuthorization()); //Set Auth key to Rest client restClient.setupRestClient(this,loginModel.getAuthorization()); nextScreen(); } } } catch (Exception e) { e.printStackTrace(); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { if (object != null) ToastHelper.getInstance().showToast(this, object.toString(), Toast.LENGTH_LONG); } /** * Redirect to next screen */ private void nextScreen() { Intent intent = new Intent(this, HomeActivity.class); startActivity(intent); finish(); } private void showLocationEnableDialog() { new AlertDialog.Builder(this) .setMessage(getString(R.string.msgNotLoginWithoutLocation)) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //TODO: Later this scenario will check MyLog.v("showLocationEnableDialog", "yes clicked"); /*getCurrentLocation(new LocationUpdateListener() { @Override public void onLocationUpdate(Location location) { if (loginModel != null) callLoginAPI(); else loginWithFacebook(); } @Override public void onLocationPermissionDeny() { //showLocationEnableDialog(); } @Override public void onGPSRequestDeny() { // showLocationEnableDialog(); } });*/ getLocation(); } }).show(); } private void getLocation() { getCurrentLocation(new LocationUpdateListener() { @Override public void onLocationUpdate(Location location) { if (loginModel != null) callLoginAPI(); else loginWithFacebook(); } @Override public void onLocationPermissionDeny() { //showLocationEnableDialog(); } @Override public void onGPSRequestDeny() { // showLocationEnableDialog(); } }); } private void showEnableStoragePermissionDialog() { new AlertDialog.Builder(this) .setMessage(getString(R.string.msgEnableStoragePermission)) .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { checkStoragePermission(REQ_PERMISSION_WRITE_STORAGE_FROM_DIALOG); } }).show(); } }6)SplashActivity.java========================**********com.app.api*****************package com.eppico.activity; import android.content.Intent;import android.location.Location;import android.os.Bundle;import android.os.Handler;import android.util.Log;import android.view.View;import android.view.Window;import android.view.WindowManager; import com.eppico.R;import com.eppico.interfaces.LocationUpdateListener;import com.eppico.utility.MyLog;import com.eppico.utility.PrefHelper; public class SplashActivity extends BaseActivity { public boolean is_login = false; private boolean isApiCall = true; public String latitude = "", longitude = ""; @Override protected void onCreate(Bundle savedInstanceState) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); Log.v("Splash","UserData: " + PrefHelper.getString(getString(R.string.prefLoginUserData),"")); getCurrentLocation(new LocationUpdateListener() { @Override public void onLocationUpdate(Location location) { // MyLog.v("SplashScreen","onLocationUpdate: location: "+ location.getLatitude() + " : " + location.getLatitude()); //Store user current lat-long into preference PrefHelper.setDouble(getString(R.string.prefUserLatitude),location.getLatitude()); PrefHelper.setDouble(getString(R.string.prefUserLongitude),location.getLongitude()); nextScreen(); } @Override public void onLocationPermissionDeny() { //MyLog.v("SplashScreen","onLocationPermissionDeny"); nextScreen(); } @Override public void onGPSRequestDeny() { // MyLog.v("SplashScreen","onGPSRequestDeny"); nextScreen(); } }); } /**start Next Screen according to user login*/ private void nextScreen() { Intent intent =null; if(PrefHelper.getString(getString(R.string.prefLoginUserData),"").length()>0) intent = new Intent(SplashActivity.this, HomeActivity.class); else intent = new Intent(SplashActivity.this, LoginActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } }1)APIError.java======================package com.eppico.api; public class APIError { private int statusCode; private String message; private String title; public APIError() { } public int status() { return statusCode; } public String message() { return message; } public String getTitle() { return title; } }2)ApiResponseListener.java============================package com.eppico.api; import retrofit2.Call;import retrofit2.Response; /** * Created by rushil on 13/12/16. */ public interface ApiResponseListener { /**Call on success API response with request code*/ void onApiResponse(Call<Object> call, Response<Object> response, int reqCode); /**Call on success API response with request code and passed position*/ void onApiResponse(Call<Object> call, Response<Object> response, int reqCode, int position); /**Call on error of API with request code */ void onApiError(Call<Object> call, Object object, int reqCode);}3)EppicoAPI.java=================package com.eppico.api; import com.eppico.models.AddPostModel;import com.eppico.models.AppUserModel;import com.eppico.models.CategoryModel;import com.eppico.models.CheckInUserModel;import com.eppico.models.CheckedInSpotModel;import com.eppico.models.CommentListModel;import com.eppico.models.EditProfileModel;import com.eppico.models.DeletePostModel;import com.eppico.models.EditSpotModel;import com.eppico.models.FollowSpotModel;import com.eppico.models.FollowUserModel;import com.eppico.models.FollowersListModel;import com.eppico.models.FollowingListModel;import com.eppico.models.InviteFriendModel;import com.eppico.models.CreateSpotModel;import com.eppico.models.InviteSpotDetailModel;import com.eppico.models.InviteSpotListModel;import com.eppico.models.LeadershipBoardModel;import com.eppico.models.LikeModel;import com.eppico.models.LoginModel;import com.eppico.models.LogoutModel;import com.eppico.models.PostDetailModel;import com.eppico.models.ProfileDetailModel;import com.eppico.models.RadiusModel;import com.eppico.models.ReportAbuseModel;import com.eppico.models.SearchSpotModel;import com.eppico.models.SearchUserListModel;import com.eppico.models.SpotModel;import com.eppico.models.UserLeaderShipListModel;import com.eppico.models.deleteCommentModel; import org.json.JSONArray; import java.util.List;import okhttp3.MultipartBody;import okhttp3.RequestBody;import retrofit2.Call;import retrofit2.http.Field;import retrofit2.http.FormUrlEncoded;import retrofit2.http.GET;import retrofit2.http.Multipart;import retrofit2.http.POST;import retrofit2.http.PUT;import retrofit2.http.Part;import retrofit2.http.Query; public interface EppicoAPI { @Multipart @POST("user/login") Call<LoginModel> loginUser(@Part("facebookId") RequestBody facebookId,@Part("firstName") RequestBody firstName,@Part("lastName") RequestBody lastName,@Part("email") RequestBody email, @Part("curLat") RequestBody curLat,@Part("curLong") RequestBody curLong,@Part("deviceToken") RequestBody deviceToken, @Part("userType") RequestBody userType,@Part("deviceType") RequestBody deviceType, @Part MultipartBody.Part file); @GET("spotradius") Call<List<RadiusModel>> getSpotRadius(); @GET("spot") Call<List<SpotModel>> getSpotList(); @FormUrlEncoded @PUT("spotradius/1") Call<RadiusModel> updateRadius(@Field("desc") String desc); @GET("category") Call<List<CategoryModel>> getCategory(); /*@Multipart @POST("spot") Call<LoginModel> createSpot(@Part("catId") RequestBody catId,@Part("userId") RequestBody userId, @Part("radiusId") RequestBody radiusId,@Part("spotName") RequestBody spotName, @Part("spotDetailDesc") RequestBody spotDetailDesc, @Part("spotLocation") RequestBody spotLocation, @Part("spotLatLong") RequestBody spotLatLong, @Part MultipartBody.Part file);*/ @GET("user") Call<AppUserModel> getAppUserList(@Query("page") int page,@Query("userId") int userId,@Query("spotId") int spotId); @FormUrlEncoded @POST("user/user-search") Call<AppUserModel> searchAppUser(@Field("search") String search,@Field("page") String page,@Field("spotId") int spotId); @FormUrlEncoded @POST("spotinvitation") // Call<List<InviteFriendModel>> inviteFriends(@Field("userId") String usersJsonArray); Call<List<InviteFriendModel>> inviteFriends(@Field("spotId") String spotId,/*@Field("userId") String userId,*/@Field("invitationType") String invitationType, @Field("spInviteType") String spInviteType,@Field("intivite") String intiviteJsonArray); @Multipart @POST("spot") Call<CreateSpotModel> createSpot(@Part("catId") RequestBody catId, /*@Part("userId") RequestBody userId,*/ @Part("radiusId") RequestBody radiusId, @Part("spotName") RequestBody spotName, @Part("spotDetailDesc") RequestBody spotDetailDesc, @Part("spotLocation") RequestBody spotLocation, @Part("spotLatLong") RequestBody spotLatLong, @Part MultipartBody.Part file); @FormUrlEncoded @POST("spotinvitation/spot-invite-list") Call<InviteSpotListModel> inviteSpotList(/*@Field("userId") String userId,*/@Field("search") String search, @Field("page") String page); @FormUrlEncoded @POST("spot/my-spot-list") Call<InviteSpotListModel> mySpotList(/*@Field("userId") String userId,*/ @Field("search") String search, @Field("page") String page); @FormUrlEncoded @POST("spot/spot-edit") // Call<EditSpotModel> editSpot(@Field("spotId") String spotId, @Field(value = "spotName", encoded = true) String spotName, @Field("spotDetailDesc") String spotDetailDesc, @Field("isActive") String isActive); Call<EditSpotModel> editSpot(@Field("spotId") String spotId, @Field("spotName") String spotName, @Field("spotDetailDesc") String spotDetailDesc, @Field("isActive") String isActive); @FormUrlEncoded @POST("spot/spot-details") Call<InviteSpotDetailModel> inviteSpotDetail(/*@Field("userId") String userId,*/@Field("spotId") String spotId,@Field("page") String page); @FormUrlEncoded @POST("checkin/checkin-user-list") Call<CheckInUserModel> checkInUserList(@Field("spotId") String spotId, @Field("page") String page,@Field("search") String search); @FormUrlEncoded @POST("spot-followers/spot-followers-list") Call<FollowersListModel> getSpotFollowersList(/*@Field("userId") String userId,*/@Field("spotId") String spotId, @Field("page") String page, @Field("search") String search); @FormUrlEncoded @POST("user-followers/user-followers-list") Call<FollowersListModel> getUserFollowersList(@Field("userId") String userId,@Field("page") String page, @Field("search") String search, @Field("type") String type); @Multipart @POST("post") Call<AddPostModel> addPost(@Part("spotId") RequestBody spotId, /*@Part("userId") RequestBody userId,*/ @Part("postDesc") RequestBody postDesc, @Part("mediaType") RequestBody mediaType, @Part MultipartBody.Part file); @FormUrlEncoded @POST("spot/spot-check-in") Call<CheckedInSpotModel> checkedInSpot(@Field("spotId") String spotId, /*@Field("userId") String userId,*/ @Field("currentLat") String currentLat, @Field("currentLong") String currentLong); //@FormUrlEncoded @POST("user/logout") Call<LogoutModel> logout(/*@Field("userId") String userId*/); @FormUrlEncoded @POST("post/post-details") Call<PostDetailModel> postDetail(@Field("postId") String postId, @Field("page") String page); @FormUrlEncoded @POST("post/post-delete") Call<DeletePostModel> deletePost(/*@Field("userId") int userId,*/ @Field("spotId") int spotId, @Field("postId") int postId,@Field("mediaId") int mediaId); @FormUrlEncoded @POST("reportabuse") Call<ReportAbuseModel> reportAbuse(@Field("userId") String userId, @Field("spotId") String spotId, @Field("postId") String postId,@Field("mediaid") String mediaid, @Field("desc") String desc); @FormUrlEncoded @POST("user/profile-view") Call<ProfileDetailModel> getProfileDetail(@Field("userId") String userId, @Field("page") String page); @FormUrlEncoded @POST("comment") Call<PostDetailModel.PostComments> writeComment(/*@Field("userId") String userId,*/ @Field("spotId") String spotId, @Field("postId") String postId, @Field("commentDesc") String desc); @Multipart @POST("user/edit-profile") Call<EditProfileModel> editProfile(/*@Part("userId") RequestBody userId,*/ @Part("firstName") RequestBody firstName, @Part("lastName") RequestBody lastName,@Part MultipartBody.Part file); @FormUrlEncoded @POST("comment/comment-list") Call<CommentListModel> commentList(@Field("postId") String postId, @Field("page") String page); @FormUrlEncoded @POST("spot-followers") Call<FollowSpotModel> followSpot(@Field("spotId") String spotId, /*@Field("userId") String userId,*/@Field("spotFollowerId") String spotFollowerId, @Field("spotIsFollowing") String spotIsFollowing); @FormUrlEncoded @POST("spot-followers/follow-unfollow-user") Call<FollowUserModel> followUser(/*@Field("userId") String userId,*/ @Field("userFollowerId") String userFollowerId, @Field("userIsFollowing") String userIsFollowing); @FormUrlEncoded @POST("comment/comment-delete") Call<deleteCommentModel> deleteComment(@Field("postId") String postId, @Field("commentId") String commentId); @FormUrlEncoded @POST("spot-followers/spot-following-list") Call<FollowingListModel> followingSpotList(/*@Field("userId") String userId, */@Field("search") String search, @Field("page") String page); @FormUrlEncoded @POST("post/like-post") Call<LikeModel> likeComment(@Field("spotId") String spotId, @Field("postId") String postId, @Field("mediaID") String mediaID); @FormUrlEncoded @POST("post/leadership-board") Call<List<LeadershipBoardModel>> leadershipBoard(@Field("spotId") String spotId); @POST("post/view-leadership-board") Call<List<UserLeaderShipListModel>> userLeadershipBoard(); @FormUrlEncoded @POST("spot/spot-search") Call<SearchSpotModel> searchSpot(@Field("search") String search,@Field("page") int page); @FormUrlEncoded @POST("user/user-global-search") Call<SearchUserListModel> searchUser(@Field("search") String search, @Field("page") int page); }4)ErrorUtils.java=======================package com.eppico.api; import java.io.IOException;import java.lang.annotation.Annotation; import okhttp3.ResponseBody;import retrofit2.Converter;import retrofit2.Response; public class ErrorUtils { public static APIError parseError(Response<?> response) { Converter<ResponseBody, APIError> converter = RestClient.retrofit().responseBodyConverter(APIError.class, new Annotation[0]); APIError error=null; try { error = converter.convert(response.errorBody()); } catch (Exception e) { e.printStackTrace(); //return new APIError(); } return error; } }5)RestClient.java=======================package com.eppico.api; import android.app.Activity;import android.content.Context;import android.support.v4.app.Fragment;import android.util.Log; import com.eppico.BuildConfig;import com.eppico.R;import com.eppico.utility.CustomDialog;import com.eppico.utility.MyLog;import com.eppico.utility.ToastHelper;import com.eppico.utility.Utils;import com.google.gson.Gson;import com.google.gson.GsonBuilder; import java.io.IOException;import java.net.ConnectException;import java.net.SocketTimeoutException;import java.util.concurrent.TimeUnit; import okhttp3.Interceptor;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response;import okhttp3.logging.HttpLoggingInterceptor;import retrofit2.Call;import retrofit2.Callback;import retrofit2.Retrofit;import retrofit2.converter.gson.GsonConverterFactory; public class RestClient { private static String TAG=RestClient.class.getName(); private static EppicoAPI API_CLIENT; static Retrofit retrofit; Context context; private static int TIME_OUT_DURATION=60; // Seconds public RestClient(Context context,String authKey) { this.context = context; setupRestClient(context,authKey); } public static EppicoAPI getApiClient() { return API_CLIENT; } public void setupRestClient(final Context context,final String authKey) { OkHttpClient.Builder builderOkHttp = new OkHttpClient.Builder(); builderOkHttp.connectTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS); builderOkHttp.readTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS); HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builderOkHttp.networkInterceptors().add(httpLoggingInterceptor);// builderOkHttp.hostnameVerifier(getHostNameVerifier()); if(authKey!=null && authKey.trim().length()>0) { builderOkHttp.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("authorization", "Bearer " + authKey) .addHeader("Content-Type", "application/json") .build(); return chain.proceed(request); } }); } else { builderOkHttp.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Content-Type", "application/json") .build(); return chain.proceed(request); } }); } OkHttpClient client = builderOkHttp.build(); Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .create(); retrofit = new Retrofit.Builder() .baseUrl(context.getString(R.string.baseURL)) .addConverterFactory(GsonConverterFactory.create(gson)) .client(client) .build(); API_CLIENT = retrofit.create(EppicoAPI.class); } /*public void setupRestClient(final Context context) { OkHttpClient.Builder builderOkHttp = new OkHttpClient.Builder(); builderOkHttp.connectTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS); builderOkHttp.readTimeout(TIME_OUT_DURATION, TimeUnit.SECONDS); HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builderOkHttp.networkInterceptors().add(httpLoggingInterceptor);// builderOkHttp.hostnameVerifier(getHostNameVerifier()); builderOkHttp.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException {// PrintLog.e("REST CLIENT", "MY TOKEN :: " + AppPrefs.getInstance(context).getToken());// PrintLog.e("REST CLIENT", "UUID:: " + String.valueOf(deviceUuidFactory.getDeviceUuid())); Request request = chain.request().newBuilder()// .addHeader("Token", AppPrefs.getInstance(context).getToken())// .addHeader("sourceSystemId", AppPrefs.getInstance(context).getSourceSystemId())// .addHeader("buId", AppPrefs.getInstance(context).getBuId()) .addHeader("Content-Type", "application/json")// .addHeader("macId", String.valueOf(deviceUuidFactory.getDeviceUuid())) .build(); return chain.proceed(request); } }); OkHttpClient client = builderOkHttp.build(); Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") .create(); retrofit = new Retrofit.Builder() .baseUrl(context.getString(R.string.baseURL)) .addConverterFactory(GsonConverterFactory.create(gson)) .client(client) .build(); API_CLIENT = retrofit.create(EppicoAPI.class); }*/ public static Retrofit retrofit() { return retrofit; } @SuppressWarnings("unchecked") public void makeApiRequest(final Activity activity, Object call, final ApiResponseListener apiResponseListener, final int reqCode,boolean showProgressDialog) { try { if(Utils.getInstance().checkInternetConnection(activity)) { if(showProgressDialog) CustomDialog.getInstance().show(activity,false); final Call<Object> objectCall = (Call<Object>) call; objectCall.enqueue(new Callback<Object>() { @Override public void onResponse(Call<Object> call, retrofit2.Response<Object> response) { CustomDialog.getInstance().hide(); /** Returns true if code() is in the range [200..300). */ if(response.isSuccessful()) { MyLog.v(TAG, "onResponse - Success : " + response.body()); if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiResponse(call, response, reqCode); /* if(apiResponseListener instanceof Fragment) { Fragment fragment = (Fragment) apiResponseListener; if(fragment.isAdded()){ apiResponseListener.onApiResponse(call, response, reqCode); } }*/ } else { if(response.message()!=null && shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, response.message(), reqCode); /*Note: This error log is only for developer. Where developer identify exact API error*/ if (BuildConfig.DEBUG) { APIError error = ErrorUtils.parseError(response); if(error!=null) MyLog.e(TAG, "error message: "+error.message()); } } } @Override public void onFailure(Call<Object> call, Throwable t) { //there is more than just a failing request (like: no internet connection) MyLog.e(TAG, "onFailure - Fail : " + t.getMessage()); CustomDialog.getInstance().hide(); if (t instanceof ConnectException || t instanceof SocketTimeoutException){ //Displaying no network connection error if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, activity.getString(R.string.msgInternetConnectionNotAvailable), reqCode); } else { if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, activity.getString(R.string.msgProblemWithRequest), reqCode); } } }); } else { ToastHelper.getInstance().showToast(activity,activity.getString(R.string.msgInternetConnectionNotAvailable)); } }catch (Exception e) { CustomDialog.getInstance().hide(); e.printStackTrace(); ToastHelper.getInstance().showToast(activity,activity.getString(R.string.msgProblemWithRequest)); } } @SuppressWarnings("unchecked") public void makeApiRequest(final Activity activity,Object call, final ApiResponseListener apiResponseListener, final int reqCode,final int position,boolean showProgressDialog) { try { if(Utils.getInstance().checkInternetConnection(activity)) { if(showProgressDialog) CustomDialog.getInstance().show(activity,false); final Call<Object> objectCall = (Call<Object>) call; objectCall.enqueue(new Callback<Object>() { @Override public void onResponse(Call<Object> call, retrofit2.Response<Object> response) { CustomDialog.getInstance().hide(); /** Returns true if code() is in the range [200..300).*/ if(response.isSuccessful()) { MyLog.v(TAG, "onResponse - Success : " + response.body()); if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiResponse(call,response,reqCode,position); /* if(apiResponseListener instanceof Fragment ) { Fragment fragment = (Fragment) apiResponseListener; if(fragment.isAdded()){ apiResponseListener.onApiResponse(call, response, reqCode); } }*/ } else { if(response.message()!=null && shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, response.message(), reqCode); /*Note: This error log is only for developer. Where developer identify exact API error*/ if (BuildConfig.DEBUG) { APIError error = ErrorUtils.parseError(response); if(error!=null) MyLog.e(TAG, "error message: "+error.message()); } } } @Override public void onFailure(Call<Object> call, Throwable t) { //there is more than just a failing request (like: no internet connection) MyLog.e(TAG, "onFailure - Fail : " + t.getMessage()); CustomDialog.getInstance().hide(); if (t instanceof ConnectException){ //Displaying no network connection error if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, activity.getString(R.string.msgInternetConnectionNotAvailable), reqCode); } else { if(shouldCallCallback(apiResponseListener)) apiResponseListener.onApiError(call, activity.getString(R.string.msgProblemWithRequest), reqCode); } } }); } else { ToastHelper.getInstance().showToast(activity,activity.getString(R.string.msgInternetConnectionNotAvailable)); } }catch (Exception e) { CustomDialog.getInstance().hide(); e.printStackTrace(); ToastHelper.getInstance().showToast(activity,activity.getString(R.string.msgProblemWithRequest)); } } private boolean shouldCallCallback(ApiResponseListener apiResponseListener) { if(apiResponseListener instanceof Fragment) { Fragment fragment= (Fragment) apiResponseListener; if(fragment.isAdded()) return true; } else if(apiResponseListener instanceof Activity) { Activity activity= (Activity) apiResponseListener; if(!activity.isFinishing()) return true; } return false; } }
No comments:
Post a Comment