MyApplication.java
======================
*** activity ***package com.testdemo; import android.app.Application;import android.content.SharedPreferences;import android.preference.PreferenceManager;import android.support.multidex.MultiDex; import com.testdemo.api.RestClient;import com.testdemo.database.RealmDbHelper;import io.realm.Realm;import io.realm.RealmConfiguration; /** * Created by Manisha on 16-Jul-18. */ public class MyApplication extends Application { public static SharedPreferences myPref; RestClient restClient; private RealmDbHelper realmDbHelper; public static boolean DISABLE_FRAGMENT_ANIMATION = false; @Override public void onCreate() { super.onCreate(); MultiDex.install(this); // https://stackoverflow.com/questions/4617898/how-can-i-give-an-imageview-click-effect-like-a-button-on-android/4618185// https://www.androidhive.info/2017/12/android-working-with-bottom-sheet/// https://github.com/81813780/AVLoadingIndicatorView/tree/master/app/src/main/java/com/wang/avi/sample myPref = PreferenceManager.getDefaultSharedPreferences(this); Realm.init(this); RealmConfiguration config = new RealmConfiguration.Builder() .name("piitch.realm") .deleteRealmIfMigrationNeeded() .build(); Realm.setDefaultConfiguration(config); realmDbHelper = new RealmDbHelper(this, Realm.getDefaultInstance()); restClient = new RestClient(this, "Bearer CUn9s-F-aTl-V5g1dPGIH8GQt3Wh6QH_"); } public RealmDbHelper getRealmDbInstance() { if (realmDbHelper == null) { realmDbHelper = new RealmDbHelper(this, Realm.getDefaultInstance()); } return realmDbHelper; } public RestClient getRestClient() { return restClient; } }
============
1) BaseActivity.java
===============
package com.testdemo.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.util.Log; 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 com.testdemo.MyApplication;import com.testdemo.R;import com.testdemo.Utility.Constants;import com.testdemo.Utility.CustomDialog;import com.testdemo.Utility.MyLog;import com.testdemo.Utility.PermissionUtil;import com.testdemo.Utility.PrefHelper;import com.testdemo.api.ApiResponseListener;import com.testdemo.api.RestClient;import com.testdemo.database.RealmDbHelper;import com.testdemo.interfaces.LocationUpdateListener;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 LocationRequest mLocationRequest; LocationUpdateListener locationUpdateListener; public RestClient restClient; public MyApplication appInstance; private LocationSettingsRequest.Builder builder; public RealmDbHelper realmDbHelper; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); appInstance = (MyApplication) getApplication(); restClient = appInstance.getRestClient(); realmDbHelper = appInstance.getRealmDbInstance(); } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode, String pos) { } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { } /** * 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()); PrefHelper.setDouble(Constants.LATITUDE, location.getLatitude()); PrefHelper.setDouble(Constants.LONGITUDE, location.getLongitude()); Log.e("LOCATION::",""+location.getLatitude()); Log.e("LOCATION::",""+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(); } } }
2)HomeActivity.java
===================
package com.testdemo.activity; import android.databinding.DataBindingUtil;import android.location.Location;import android.os.Bundle;import android.support.v7.widget.LinearLayoutManager;import android.util.Log;import android.view.View;import com.testdemo.R;import com.testdemo.Utility.Constants;import com.testdemo.Utility.PrefHelper;import com.testdemo.Utility.ToastHelper;import com.testdemo.adapter.HomeAdapter;import com.testdemo.api.RestClient;import com.testdemo.databinding.ActivityHomeBinding;import com.testdemo.interfaces.LocationUpdateListener;import com.testdemo.model.DataModel;import java.util.ArrayList;import java.util.List;import retrofit2.Call;import retrofit2.Response; public class HomeActivity extends BaseActivity { ActivityHomeBinding mBinding;// RealmDbHelper dbHelper;// MyApplication appInstance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding = DataBindingUtil.setContentView(this, R.layout.activity_home); init(); } public void init() { // appInstance = (MyApplication) getApplication(); // restClient = appInstance.getRestClient(); // dbHelper = appInstance.getRealmDbInstance(); getCurrentLocation(new LocationUpdateListener() { @Override public void onLocationUpdate(Location location) { PrefHelper.setDouble(Constants.LATITUDE, location.getLatitude()); PrefHelper.setDouble(Constants.LONGITUDE, location.getLongitude()); Log.e("LOCATION::",""+location.getLatitude()); Log.e("LOCATION::",""+location.getLongitude()); } @Override public void onLocationPermissionDeny() { } @Override public void onGPSRequestDeny() { } }); apiCallgetData(); LinearLayoutManager lytManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); mBinding.recyclerView.setLayoutManager(lytManager); } public void apiCallgetData() { mBinding.lytLoader.setVisibility(View.VISIBLE); mBinding.avi.show(); Call<List<DataModel>> objectCall = RestClient.getApiClient().getMaterial(); restClient.makeApiRequest(HomeActivity.this, objectCall, this, getResources().getInteger(R.integer.reqCodeDataList), false); } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if (reqCode == getResources().getInteger(R.integer.reqCodeDataList)) { mBinding.lytLoader.setVisibility(View.GONE); mBinding.avi.hide(); ArrayList<DataModel> list = (ArrayList<DataModel>) response.body(); if (list != null && list.size() > 0) { realmDbHelper.insertData(list); } ArrayList<DataModel> arrayList = realmDbHelper.getData(); bindSpotList(arrayList); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { mBinding.lytLoader.setVisibility(View.GONE); mBinding.avi.hide(); ToastHelper.getInstance().showToast(this, object.toString()); } private void bindSpotList(ArrayList<DataModel> list) { if (list != null && list.size() > 0) { mBinding.lytNoData.setVisibility(View.GONE); mBinding.recyclerView.setVisibility(View.VISIBLE); HomeAdapter adapter = (HomeAdapter) mBinding.recyclerView.getAdapter(); if (adapter != null && adapter.getItemCount() > 0) { adapter.setData(list); } else { adapter = new HomeAdapter(this, list); mBinding.recyclerView.setAdapter(adapter); } } else { mBinding.lytNoData.setVisibility(View.VISIBLE); mBinding.recyclerView.setVisibility(View.GONE); mBinding.txtNoData.setText(getResources().getString(R.string.no_data_found)); } } }3)MapActivity.java==================package com.testdemo.activity; import android.databinding.DataBindingUtil;import android.graphics.drawable.GradientDrawable;import android.os.Bundle;import android.os.Handler;import android.support.v4.app.FragmentManager;import android.view.View;import android.view.Window;import android.view.WindowManager; 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.LatLng;import com.google.android.gms.maps.model.MarkerOptions;import com.testdemo.R;import com.testdemo.Utility.Constants;import com.testdemo.Utility.PrefHelper;import com.testdemo.databinding.ActivityMapBinding; /** * Created by Manisha on 11/17/2018. */ public class MapActivity extends BaseActivity implements OnMapReadyCallback, View.OnClickListener { private GoogleMap googleMap; double latitude = 0.0, longitude = 0.0; String location = ""; private String start_color, end_color; ActivityMapBinding mBinding; @Override protected void onCreate(Bundle savedInstanceState) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); mBinding = DataBindingUtil.setContentView(this, R.layout.activity_map); mBinding.toolbar.toolbarTitle.setText(getResources().getString(R.string.map)); mBinding.toolbar.imgBack.setOnClickListener(this); initMap(); } private void initMap() { try { if (googleMap != null) { drawMarkerOnMap(); } else { new Handler().postDelayed(new Runnable() { @Override public void run() { FragmentManager fm = getSupportFragmentManager(); SupportMapFragment mapFragment = SupportMapFragment.newInstance(); fm.beginTransaction().replace(R.id.mapContainer, mapFragment).commit(); mapFragment.getMapAsync(MapActivity.this); } }, 400); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onMapReady(GoogleMap googleMap) { this.googleMap = googleMap; drawMarkerOnMap(); } private void drawMarkerOnMap() { try { latitude = 0.0; longitude = 0.0; latitude = PrefHelper.getDouble(Constants.LATITUDE, 0.0); longitude = PrefHelper.getDouble(Constants.LONGITUDE, 0.0); LatLng latLng = new LatLng(latitude, longitude); googleMap.clear(); googleMap.addMarker(new MarkerOptions() .position(latLng) .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher)) // Specifies the anchor to be at a particular point in the marker image. .anchor(0.5f, 1)); googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 7.0f)); } catch (Exception e) { e.printStackTrace(); } } @Override public void onClick(View v) { if (v == mBinding.toolbar.imgBack) { finish(); } } }*** Adapter ***===============4)HomeAdapter.java===================package com.testdemo.adapter; import android.app.Activity;import android.content.Context;import android.content.Intent;import android.databinding.DataBindingUtil;import android.support.annotation.NonNull;import android.support.v7.widget.RecyclerView;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup; import com.testdemo.R;import com.testdemo.Utility.Constants;import com.testdemo.activity.MapActivity;import com.testdemo.databinding.ItemListBinding;import com.testdemo.model.DataModel; import java.util.ArrayList; public class HomeAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context context; private ArrayList<DataModel> alstData; public HomeAdapter(Context context, ArrayList<DataModel> alstData) { this.context = context; this.alstData = alstData; } public void setData(ArrayList<DataModel> alstData) { this.alstData = alstData; notifyDataSetChanged(); } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_list, parent, false); return new CustomViewHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int pos) { if (viewHolder instanceof CustomViewHolder) { final CustomViewHolder customViewHolder = (CustomViewHolder) viewHolder; customViewHolder.mBinding.txt1.setText(alstData.get(pos).getName());// Glide.with(this)// .load(loginModel.getUserImage())// .placeholder(R.mipmap.ic_default_profile)// .into(imageUser); customViewHolder.mBinding.lytMain.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, MapActivity.class); ((Activity) context).startActivity(intent); } }); } } @Override public int getItemCount() { return alstData.size(); } public class CustomViewHolder extends RecyclerView.ViewHolder { ItemListBinding mBinding; public CustomViewHolder(@NonNull View itemView) { super(itemView); mBinding = DataBindingUtil.bind(itemView); } } }*** api ***============5)APIError.java=================package com.testdemo.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; } }6) ApiResponseListener.java=============================package com.testdemo.api; import retrofit2.Call;import retrofit2.Response; /** * Created by Manisha 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);// void onApiResponse(Call<Object> call, Response<Object> response, int reqCode, String pos); /**Call on success API response with request code and passed position*/ void onApiResponse(Call<Object> call, Response<Object> response, int reqCode, String pos); /**Call on error of API with request code */ void onApiError(Call<Object> call, Object object, int reqCode); }7) ErrorUtils.java==================package com.testdemo.api; import java.lang.annotation.Annotation;import okhttp3.ResponseBody;import retrofit2.Converter;import retrofit2.Response; public class ErrorUtils { public static APIError parseError(Response<?> response) { Converter<ResponseBody, APIError> converter = RestClient.retrofit().responseBodyConverter(APIError.class, new Annotation[0]); APIError error=null; try { error = converter.convert(response.errorBody()); } catch (Exception e) { e.printStackTrace(); // return new APIError(); } return error; } }8) RestClient.java==================package com.testdemo.api; import android.app.Activity;import android.content.Context;import android.content.Intent;import android.os.Build;import android.support.v4.app.Fragment; import com.google.gson.Gson;import com.google.gson.GsonBuilder;import com.testdemo.BuildConfig;import com.testdemo.R;import com.testdemo.Utility.CustomDialog;import com.testdemo.Utility.MyLog;import com.testdemo.Utility.ToastHelper;import com.testdemo.Utility.Utils; 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 TestAPI API_CLIENT; static Retrofit retrofit; Context context; String strVersionCode = "", strDeviceId = "", strDeviceModel = "", auth_key = ""; int user_id = 0; private static int TIME_OUT_DURATION = 60; // Seconds public RestClient(Context context, String authKey) { this.context = context; setupRestClient(context, authKey); } public static TestAPI 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); strVersionCode = Utils.getInstance().getVersionName(context); if (Utils.validateString(authKey) && authKey.trim().length() > 0) { builderOkHttp.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder() .addHeader("Content-Type", "application/json") .addHeader("Authorization", "Bearer CUn9s-F-aTl-V5g1dPGIH8GQt3Wh6QH_") .build(); return chain.proceed(request); } }); } OkHttpClient client = builderOkHttp.build(); Gson gson = new GsonBuilder() .setLenient() .setDateFormat("yyyy-MM-dd HH:mm:ss") .create(); retrofit = new Retrofit.Builder() .baseUrl(context.getResources().getString(R.string.baseURL)) .addConverterFactory(GsonConverterFactory.create(gson)) .client(client) .build(); API_CLIENT = retrofit.create(TestAPI.class); } public static Retrofit retrofit() { return retrofit; } 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) { /** 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 { CustomDialog.getInstance().showMessageDialog(activity, activity.getString(R.string.msgInternetConnectionNotAvailable));// 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)); } } public void makeApiRequestContext(final Context activity, Object call, final ApiResponseListener apiResponseListener, final int reqCode, String msg, boolean showProgressDialog) { try { if (Utils.getInstance().checkInternetConnection(activity)) { if (showProgressDialog) CustomDialog.getInstance().show(activity, msg, 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); } 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)); } } 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; } else { return true; } return false; } public String getDeviceName() { String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; String version = Build.getRadioVersion(); if (model.toLowerCase().startsWith(manufacturer.toLowerCase())) { return capitalize(model); } else { return capitalize(manufacturer) + " " + model + " " + version; } } private String capitalize(String s) { if (s == null || s.length() == 0) { return ""; } char first = s.charAt(0); if (Character.isUpperCase(first)) { return s; } else { return Character.toUpperCase(first) + s.substring(1); } } }9)TestAPI.java==============
package com.piitch.api; import com.piitch.models.Agenda;import com.piitch.models.ChangePassword;import com.piitch.models.Country;import com.piitch.models.EditProfileResponse;import com.piitch.models.EntityAttributeValue;import com.piitch.models.EntityAttributeSet;import com.piitch.models.EntityResponse;import com.piitch.models.Event;import com.piitch.models.FAQsResponse;import com.piitch.models.FollowUnfollowResponse;import com.piitch.models.LoginUser;import com.piitch.models.Logout;import com.piitch.models.Meeting;import com.piitch.models.MeetingAccpetRejectResponse;import com.piitch.models.MeetingRequest;import com.piitch.models.MeetingSentReceiveRequest;import com.piitch.models.MenuItemModel;import com.piitch.models.NotificationList;import com.piitch.models.Organization;import com.piitch.models.Person;import com.piitch.models.PhotoGallery;import com.piitch.models.Poll;import com.piitch.models.PollAnswer;import com.piitch.models.PollAnswerRequest;import com.piitch.models.PollResponse;import com.piitch.models.PollResponseRequest;import com.piitch.models.EntityAnswerRequest;import com.piitch.models.RegisterModel;import com.piitch.models.SendNotification;import com.piitch.models.VideoGallery;import com.piitch.notification.Notification; import java.util.HashMap;import java.util.List;import java.util.Map; import okhttp3.MultipartBody;import okhttp3.RequestBody;import retrofit2.Call;import retrofit2.http.Body;import retrofit2.http.DELETE;import retrofit2.http.Field;import retrofit2.http.FormUrlEncoded;import retrofit2.http.GET;import retrofit2.http.Multipart;import retrofit2.http.POST;import retrofit2.http.Part;import retrofit2.http.PartMap; public interface PiitchAPI { @GET("events?expand=appBanners,location.state") Call<List<Event>> getEvent(); // @GET("agendas")// Call<List<Agenda>> getAgendaItems();// location.states,followers,persons,categories@GET("materials") Call<List<DataModel>> getMaterial();@GET("agendas?expand=location,categories,polls") Call<List<Agenda>> getAgendaItems(); @GET("polls?expand=questions.options") Call<List<Poll>> getPolls(); // @GET("person-categories?expand=persons")// Call<List<PersonCategory>> getPersonCategories(); @GET("person?expand=agendas,categories,organizations,user") Call<List<Person>> getPersons(); @GET("organizations?expand=categories,primaryCategory,primaryCategoryItem") Call<List<Organization>> getOrganizations(); @FormUrlEncoded @POST("users/login?expand=person.categories") Call<LoginUser> userLogin(@Field("username") String email, @Field("password") String pwd); @FormUrlEncoded @POST("register") Call<RegisterModel> userRegister(@Field("full_name") String fullname, @Field("email") String email, @Field("mobile_number") String mobile_number, @Field("pwd") String pwd); @DELETE("users/logout") Call<Logout> userLogOut(); @GET("menu-items?menu_identifier=1&expand=icon") Call<List<MenuItemModel>> getMenu(); @FormUrlEncoded @POST("poll-answers") Call<PollAnswer> checkAnswer(@Field("question_id") int question_id, @Field("option_id") int option_id); @POST("poll-answers") Call<PollAnswer> checkMultiAnswer(@Body HashMap<String, List<PollAnswerRequest>> hashMap); @FormUrlEncoded @POST("poll-answers") Call<PollAnswer> checkRateAnswer(@Field("question_id") int question_id, @Field("rating") int rating); @FormUrlEncoded @POST("poll-answers") Call<PollAnswer> checkCommentAnswer(@Field("question_id") int question_id, @Field("answer") String answer); @POST("poll-responses") Call<PollResponse> submitPoll(@Body PollResponseRequest request); @FormUrlEncoded @POST("agenda-followers") Call<FollowUnfollowResponse> follow_unfollow(@Field("user_id") int user_id, @Field("agenda_id") int agenda_id, @Field("is_follow") int is_follow); @POST("fcm/send") Call<Notification> sendChatNotification(@Body HashMap<String, Object> hashmap); @GET("notifications") Call<List<NotificationList>> getNotificationList(); @FormUrlEncoded @POST("notifications") Call<SendNotification> sendNotificationInGroup(@Field("message") String message, @Field("user_id") String user_id); @GET("faq-categories?expand=faqs") Call<FAQsResponse> getFAQs(); @GET("countries?expand=states") Call<List<Country>> getCountry(); @GET("meetingas") Call<List<Meeting>> getMeetings(); @FormUrlEncoded @POST("meetingas") Call<List<MeetingRequest>> getMeetingRequest(@Field("currdate") String currentDate, @Field("fromtime") String fromtime, @Field("totime") String toTime, @Field("state") int state); @FormUrlEncoded @POST("meetingas") Call<List<MeetingSentReceiveRequest>> getMeetingSendReceive(@Field("currdate") String currentDate, @Field("fromtime") String fromtime, @Field("totime") String toTime, @Field("state") int state); @FormUrlEncoded @POST("meetingas/sendRequest") Call<MeetingAccpetRejectResponse> sendMeetingRequest(@Field("receiverid") int receiverId, @Field("currdate") String currentDate, @Field("fromtime") String fromtime, @Field("totime") String toTime); @FormUrlEncoded @POST("meetingas/cancelRequest") Call<MeetingAccpetRejectResponse> cancelMeetingRequest(@Field("meetingid") int meetingId, @Field("reason") String reason); @FormUrlEncoded @POST("meetingas/acceptRequest") Call<MeetingAccpetRejectResponse> acceptMeetingRequest(@Field("meetingid") int meetingId); @FormUrlEncoded @POST("account") Call<ChangePassword> changePassword(@Field("password") String email, @Field("password_repeat") String pwd); @Multipart @POST("person") Call<EditProfileResponse> editProfile(@Part("title") RequestBody title, @Part("given_name") RequestBody given_name, @Part("family_name") RequestBody family_name, @Part("brief") RequestBody brief, @Part("details") RequestBody details, @Part("gender") RequestBody gender, @Part("birthdate") RequestBody birthdate, @Part("mobile") RequestBody mobile, @Part("address") RequestBody address, @Part("city") RequestBody city, @Part("state_id") RequestBody state_id, @Part("country_id") RequestBody country_id, @Part MultipartBody.Part file); @GET("video-categories") Call<List<VideoGallery>> getVideo(); @GET("photo-categories") Call<List<PhotoGallery>> getPhoto(); @GET("entity-attribute-sets") Call<List<EntityAttributeSet>> getEntityAttributeSet(); @FormUrlEncoded @POST("entity-attribute-values") Call<EntityAttributeValue> checkRegisterMultiAnswer(@Body HashMap<String, List<EntityAnswerRequest>> hashMap); // @FormUrlEncoded// @POST("entity-attribute-values")// Call<EntityResponse> submitEntity(@Body EntityResponseRequest request); @Multipart @POST("entity-attribute-values") Call<EntityResponse> submitEntity(@PartMap() Map<String, RequestBody> partMap); @FormUrlEncoded @POST("poll-answers") Call<EntityAttributeValue> checkRegisterAnswer(@Field("question_id") int question_id, @Field("option_id") int option_id); @FormUrlEncoded @POST("entity-attribute-values") Call<EntityAttributeValue> checkRegisterRateAnswer(@Field("question_id") int question_id, @Field("rating") int rating); @FormUrlEncoded @POST("entity-attribute-values") Call<EntityAttributeValue> checkRegisterCommentAnswer(@Field("question_id") int question_id, @Field("answer") String answer); }10) RealmDbHelper.java=======================package com.piitch.database; import android.content.Context;import android.util.Log; import com.piitch.models.Agenda;import com.piitch.models.AgendaCategory;import com.piitch.models.AppBanner;import com.piitch.models.ChatRoom;import com.piitch.models.Country;import com.piitch.models.EntityAttribute;import com.piitch.models.EntityAttributeOption;import com.piitch.models.EntityAttributeSet;import com.piitch.models.Event;import com.piitch.models.FAQs;import com.piitch.models.FAQsItem;import com.piitch.models.FriendListModel;import com.piitch.models.FriendModel;import com.piitch.models.LoginUser;import com.piitch.models.Meeting;import com.piitch.models.MeetingRequest;import com.piitch.models.MenuItemModel;import com.piitch.models.NotificationList;import com.piitch.models.Organization;import com.piitch.models.Person;import com.piitch.models.PersonCategory;import com.piitch.models.PhotoGallery;import com.piitch.models.Poll;import com.piitch.models.PollOption;import com.piitch.models.PollQuestion;import com.piitch.models.State;import com.piitch.models.User;import com.piitch.models.UserDevice;import com.piitch.models.VideoGallery;import com.piitch.utility.Utils; import java.util.ArrayList;import java.util.Date;import java.util.List; import io.realm.Realm;import io.realm.RealmObject;import io.realm.RealmQuery;import io.realm.RealmResults;import io.realm.Sort; public class RealmDbHelper { private Context context; private Realm realm; public RealmDbHelper(Context context, Realm realm) { this.context = context; this.realm = realm; } public Realm getRealm() { return this.realm; }public void insertData(ArrayList<DataModel> items) { realm.beginTransaction(); realm.copyToRealmOrUpdate(items); realm.commitTransaction(); } // public void insert(Iterable items) {// realm.beginTransaction();// realm.copyToRealmOrUpdate(items);// realm.commitTransaction();// } public ArrayList<DataModel> getData() { ArrayList<DataModel> agendaList = new ArrayList<>();// .equalTo("status", 1).sort("lft") RealmResults<DataModel> agenda = realm.where(DataModel.class).findAll(); agendaList.addAll(agenda); return agendaList; }public void insertAgenda(ArrayList<Agenda> items) { realm.beginTransaction(); realm.copyToRealmOrUpdate(items); realm.commitTransaction(); } public void insert(Iterable items) { realm.beginTransaction(); realm.copyToRealmOrUpdate(items); realm.commitTransaction(); } public ArrayList<Agenda> getAgenda() { ArrayList<Agenda> agendaList = new ArrayList<>(); RealmResults<Agenda> agenda = realm.where(Agenda.class).equalTo("status", 1).sort("lft").findAll(); agendaList.addAll(agenda); return agendaList; } public LoginUser getLogin() { LoginUser loginModel = new LoginUser(); RealmResults<LoginUser> login = realm.where(LoginUser.class).findAll(); ArrayList<LoginUser> alstlogin = new ArrayList<>(); alstlogin.addAll(realm.copyFromRealm(login)); if (alstlogin != null && login.size() > 0) loginModel = login.get(0); return loginModel; } public ArrayList<Agenda> getLikeAgenda(int follow) { ArrayList<Agenda> agendaList = new ArrayList<>(); RealmResults<Agenda> agenda = realm.where(Agenda.class) .equalTo("is_follow", follow) .findAll(); agendaList.addAll(realm.copyFromRealm(agenda)); return agendaList; } public void updateAgenda(final int agendaId, final int isFollow) { realm.beginTransaction(); Agenda agenda = realm.where(Agenda.class) .equalTo("id", agendaId).findFirst(); agenda.setFollow(isFollow); realm.commitTransaction(); } public void updateOption(final ArrayList<PollOption> option, final int optionId, PollQuestion questions) { realm.beginTransaction(); if (option != null && option.size() > 0) { for (int i = 0; i < option.size(); i++) { if (option.get(i).getId() == optionId) { PollOption options = realm.where(PollOption.class) .equalTo("id", optionId).findFirst();// options.setChecked(ischecked); options.setVoted(1); } else { PollOption options = realm.where(PollOption.class) .equalTo("id", option.get(i).getId()).findFirst(); options.setVoted(0);// options.setChecked(false); } } } PollQuestion question = realm.where(PollQuestion.class) .equalTo("id", questions.getId()).findFirst(); question.setVoted(1); realm.commitTransaction(); } public void updateEntityOption(final ArrayList<EntityAttributeOption> option, final int optionId, EntityAttribute questions) { realm.beginTransaction(); if (option != null && option.size() > 0) { for (int i = 0; i < option.size(); i++) { if (option.get(i).getId() == optionId) { EntityAttributeOption options = realm.where(EntityAttributeOption.class) .equalTo("id", optionId).findFirst();// options.setChecked(ischecked); options.setVoted(1); } else { EntityAttributeOption options = realm.where(EntityAttributeOption.class) .equalTo("id", option.get(i).getId()).findFirst(); options.setVoted(0);// options.setChecked(false); } } } PollQuestion question = realm.where(PollQuestion.class) .equalTo("id", questions.getId()).findFirst(); question.setVoted(1); realm.commitTransaction(); } public void updateDetail(PollQuestion questions, String answer, int type, int rate) { realm.beginTransaction(); PollQuestion question = realm.where(PollQuestion.class) .equalTo("id", questions.getId()).findFirst(); question.setVoted(1); if (type == 3) question.setAnswer(answer); if (type == 4) question.setRating(rate); realm.commitTransaction(); } public void updateMultipleOption(final ArrayList<PollOption> option, PollQuestion questions) { realm.beginTransaction(); if (option != null && option.size() > 0) { for (int i = 0; i < option.size(); i++) { if (option.get(i).isVoted() == 1) { PollOption options = realm.where(PollOption.class).equalTo("id", option.get(i).getId()).findFirst();// options.setChecked(true); options.setVoted(1); } else { PollOption options = realm.where(PollOption.class).equalTo("id", option.get(i).getId()).findFirst();// options.setChecked(false); options.setVoted(0); } } } PollQuestion question = realm.where(PollQuestion.class) .equalTo("id", questions.getId()).findFirst(); question.setVoted(1); realm.commitTransaction(); } public void updateOptionDetail(final int optionId, final boolean ischecked) { realm.beginTransaction(); PollOption options = realm.where(PollOption.class) .equalTo("id", optionId).findFirst(); options.setVoted(1); realm.commitTransaction(); } public PollOption getOptionById(int id) { PollOption options = new PollOption(); RealmResults<PollOption> option = realm.where(PollOption.class).equalTo("id", id).findAll(); ArrayList<PollOption> alstPoll = new ArrayList<>(); alstPoll.addAll(realm.copyFromRealm(option)); options = option.get(0);// Log.e("", "" + alstPoll.get(0).getTitle()); return options; } public void insertEvent(ArrayList<Event> events) { realm.beginTransaction(); realm.insertOrUpdate(events); realm.commitTransaction(); } public ArrayList<Event> getEventData() { ArrayList<Event> alstEvents = new ArrayList<>(); RealmResults<Event> events = realm.where(Event.class).findAll(); events.load(); alstEvents.addAll(events); for (int i = 0; i < alstEvents.size(); i++) { String title = alstEvents.get(i).getName(); ArrayList<AppBanner> alstAppBanner = new ArrayList<>(); alstAppBanner.addAll(alstEvents.get(i).getAppBanners()); for (int j = 0; j < alstAppBanner.size(); j++) { String url = alstAppBanner.get(j).getImage(); Log.e("DbData:", "URL:::" + url.toString()); } // RealmList<AppBanner> alstBanner = alstEvents.get(i).getAppBanners();// ArrayList<AppBanner> banner = new ArrayList<>();// banner.addAll(alstBanner);// Log.e("", "" + banner); } return alstEvents; } public void insertPerson(ArrayList<Person> person) { realm.beginTransaction(); realm.copyToRealmOrUpdate(person); realm.commitTransaction(); } public void insertPersonCategory(ArrayList<PersonCategory> category) { realm.beginTransaction(); realm.copyToRealmOrUpdate(category); realm.commitTransaction(); } public void insertMenu(ArrayList<MenuItemModel> menuItemModels) { realm.beginTransaction(); realm.copyToRealmOrUpdate(menuItemModels); realm.commitTransaction(); } public void insertPolls(ArrayList<Poll> polls) { realm.beginTransaction(); realm.copyToRealmOrUpdate(polls); realm.commitTransaction(); } public void insertEntityAttribute(ArrayList<EntityAttributeSet> polls) { realm.beginTransaction(); realm.copyToRealmOrUpdate(polls); realm.commitTransaction(); } public void insertOrganizations(ArrayList<Organization> organizations) { realm.beginTransaction(); realm.copyToRealmOrUpdate(organizations); realm.commitTransaction(); } public ArrayList<Poll> getPollData(int agendaId) { ArrayList<Poll> alstPoll = new ArrayList<>(); RealmResults<Poll> pollsRealmResults = realm.where(Poll.class).equalTo("agenda_id", agendaId).findAll(); alstPoll.addAll(realm.copyFromRealm(pollsRealmResults)); return alstPoll; } public ArrayList<EntityAttributeSet> getEntityAttributeData() { ArrayList<EntityAttributeSet> alstPoll = new ArrayList<>(); RealmResults<EntityAttributeSet> pollsRealmResults = realm.where(EntityAttributeSet.class).findAll(); alstPoll.addAll(realm.copyFromRealm(pollsRealmResults)); return alstPoll; } public ArrayList<MenuItemModel> getMenuData() { ArrayList<MenuItemModel> alstMenuItemModels = new ArrayList<>(); RealmResults<MenuItemModel> menuItemModels = realm.where(MenuItemModel.class).findAll(); menuItemModels.load(); alstMenuItemModels.addAll(realm.copyFromRealm(menuItemModels)); return alstMenuItemModels; } // public ArrayList<Poll> getPoll(int id) {// ArrayList<Agenda> agendaList = new ArrayList<>();// RealmResults<Agenda> agenda = realm.where(Agenda.class).equalTo("agendaCategories.id", id).findAll();// agendaList.addAll(realm.copyFromRealm(agenda));// return agendaList;// } public ArrayList<Person> getPersons() { return getPersons(""); } public ArrayList<Person> getPersons(String params) { //if (!Utils.validateString(params)) params = "status=2"; final ArrayList<Person> alstPerson = new ArrayList<>(); final RealmResults<Person> realmListPerson = RealmDbHelper.prepareQueryFromSearchString(params, realm.where(Person.class)).findAll(); alstPerson.addAll(realm.copyFromRealm(realmListPerson)); for (int i = 0; i < alstPerson.size(); i++) { Log.e("", "" + alstPerson.get(i).getGivenName()); } return alstPerson; } public ArrayList<Person> getPersonByCategory(int id) { ArrayList<Person> PersonList = new ArrayList<>(); RealmResults<Person> agenda = realm.where(Person.class).equalTo("personCategories.id", id).equalTo("status", 2).findAll(); PersonList.addAll(realm.copyFromRealm(agenda)); return PersonList; } public ArrayList<Organization> getOrganizations() { return this.getOrganizations(""); } public ArrayList<Organization> getOrganizations(String params) { final ArrayList<Organization> alstOrganization = new ArrayList<>();// final RealmResults<Organization> realmListOrganization = realm.where(Organization.class).findAll(); final RealmResults<Organization> realmListOrganization = RealmDbHelper.prepareQueryFromSearchString(params, realm.where(Organization.class)).findAll(); realmListOrganization.load(); alstOrganization.addAll(realm.copyFromRealm(realmListOrganization)); for (int i = 0; i < alstOrganization.size(); i++) { Log.e("", "Organizations:" + alstOrganization.get(i).getName()); } return alstOrganization; } public ArrayList<Organization> getOrganizationByCategory(int id) { ArrayList<Organization> organizationList = new ArrayList<>(); RealmResults<Organization> organizations = realm.where(Organization.class).equalTo("primary_category_id", id).findAll(); organizationList.addAll(realm.copyFromRealm(organizations)); return organizationList; } public static RealmQuery prepareQueryFromSearchString(String params, RealmQuery query) { if (!Utils.validateString(params)) return query; int i = 1; String[] parts = params.trim().split("(OR)|(AND)"); query.beginGroup(); for (String part : parts) { part = part.replace("ANY", "").trim(); String[] parts2 = part.trim().split("="); query.equalTo(parts2[0].trim(), Integer.parseInt(parts2[1].trim())); if (i != parts.length) { if (params.indexOf("AND") > -1) query.and(); else query.or(); } i++; } query.endGroup(); return query; } // public ArrayList<PersonCategory> getCategory(int id) {// ArrayList<PersonCategory> PersonList = new ArrayList<>();// RealmResults<Person> agenda = realm.where(Person.class).findAll();// PersonList.addAll(realm.copyFromRealm(agenda));// return PersonList;// } public Agenda getAgendaById(int id) { Agenda agendaModel = new Agenda(); RealmResults<Agenda> agenda = realm.where(Agenda.class).equalTo("status", 1).equalTo("id", id).findAll(); ArrayList<Agenda> alstAgenda = new ArrayList<>(); alstAgenda.addAll(realm.copyFromRealm(agenda)); agendaModel = agenda.get(0); Log.e("", "" + alstAgenda.get(0).getTitle()); return agendaModel; } public ArrayList<Agenda> getSubAgenda(int id) { RealmResults<Agenda> agenda = realm.where(Agenda.class).equalTo("status", 1).equalTo("parent_id", id).sort("lft").findAll(); ArrayList<Agenda> alstAgenda = new ArrayList<>(); alstAgenda.addAll(realm.copyFromRealm(agenda)); return alstAgenda; } public ArrayList<Agenda> getAgendaByDate(Date date) { ArrayList<Agenda> agendaList = new ArrayList<>(); String from = Utils.getFormattedDate(date, "yyyy-MM-dd"); String to = from; from += " 00:00:00"; to += " 23:59:59"; Date fromDate = Utils.getDateFromString(from, "yyyy-MM-dd hh:mm:ss"); Date toDate = Utils.getDateFromString(to, "yyyy-MM-dd hh:mm:ss"); // RealmResults<Agenda> agenda = realm.where(Agenda.class).between("startAt", fromDate, toDate).findAll(); RealmResults<Agenda> agenda = Agenda.find().equalTo("status", 1).between("start_at", fromDate, toDate).findAll();// RealmResults<Agenda> agenda = Agenda.find().equalTo("status", 1).between("start_at", fromDate, toDate).findAll(); agendaList.addAll(realm.copyFromRealm(agenda)); return agendaList; } public ArrayList<Agenda> getAgendaByCategory(int id) { ArrayList<Agenda> agendaList = new ArrayList<>(); RealmResults<Agenda> agenda = realm.where(Agenda.class).equalTo("status", 1).equalTo("agendaCategories.id", id).sort("lft").findAll(); agendaList.addAll(realm.copyFromRealm(agenda)); return agendaList; } public Person getPersonById(int id) { Person personModel = new Person(); RealmResults<Person> person = realm.where(Person.class).equalTo("id", id).findAll(); ArrayList<Person> alstPerson = new ArrayList<>(); alstPerson.addAll(realm.copyFromRealm(person)); personModel = alstPerson.get(0); return personModel; } public Person getPersonByUserId(int id) { Person personModel = new Person(); RealmResults<Person> person = realm.where(Person.class).equalTo("user_id", id).findAll(); ArrayList<Person> alstPerson = new ArrayList<>(); alstPerson.addAll(realm.copyFromRealm(person)); if (alstPerson != null) { personModel = alstPerson.get(0); } return personModel; } public String getPersonName(int id) { Person personModel = new Person(); RealmResults<Person> person = realm.where(Person.class).equalTo("id", id).findAll(); ArrayList<Person> alstPerson = new ArrayList<>(); alstPerson.addAll(realm.copyFromRealm(person)); return alstPerson.get(0).getName(); } public Organization getOrganizationById(int id) { Organization organization = new Organization(); RealmResults<Organization> realmResults = realm.where(Organization.class).equalTo("id", id).findAll(); ArrayList<Organization> alstPerson = new ArrayList<>(); alstPerson.addAll(realm.copyFromRealm(realmResults)); organization = realmResults.get(0); Log.e("PERSON", "person name:" + alstPerson.get(0).getName()); return organization; } public void insertUser(LoginUser user) { realm.beginTransaction(); realm.copyToRealmOrUpdate(user); realm.commitTransaction(); } public void deleteUser() { realm.beginTransaction(); realm.where(LoginUser.class).findAll().deleteAllFromRealm(); realm.commitTransaction(); } public int getSubId(String title) { int id = 0; MenuItemModel menuItemModel = new MenuItemModel(); RealmResults<MenuItemModel> menu = realm.where(MenuItemModel.class).equalTo("title", title).findAll(); ArrayList<MenuItemModel> alstMenu = new ArrayList<>(); alstMenu.addAll(realm.copyFromRealm(menu)); Log.e("", "" + alstMenu.get(0).getId()); return alstMenu.get(0).getId(); } public ArrayList<PersonCategory> getPersonCategoryData() { ArrayList<PersonCategory> alstPersonCategory = new ArrayList<>(); RealmResults<PersonCategory> personCategoryItem = realm.where(PersonCategory.class).sort("sortOrder").findAll();// RealmResults<PersonCategory> personCategoryItem = realm.where(PersonCategory.class).sort("given_name", Sort.ASCENDING, "family_name", Sort.ASCENDING).findAll(); personCategoryItem.load(); alstPersonCategory.addAll(realm.copyFromRealm(personCategoryItem)); return alstPersonCategory; } public ArrayList<AgendaCategory> getAgendaCategoryData() { ArrayList<AgendaCategory> alstAgendaCategory = new ArrayList<>(); RealmResults<AgendaCategory> agendaCategoryItem = realm.where(AgendaCategory.class).sort("sort_order").findAll(); agendaCategoryItem.load(); alstAgendaCategory.addAll(realm.copyFromRealm(agendaCategoryItem)); return alstAgendaCategory; } public void insertFriend(FriendModel friend) { realm.beginTransaction(); realm.copyToRealmOrUpdate(friend); realm.commitTransaction(); } public FriendListModel getFriendList() { FriendListModel listFriend = new FriendListModel(); ArrayList<ChatRoom> alstfriend = new ArrayList<>(); RealmResults<ChatRoom> realmFriendList = realm.where(ChatRoom.class).findAll(); realmFriendList.load(); alstfriend.addAll(realm.copyFromRealm(realmFriendList)); listFriend.setAlstFriendList(alstfriend); return listFriend; } public ArrayList<AgendaCategory> getAgendaCategoryById(int agenda_id) { ArrayList<AgendaCategory> alstAgendaCategory = new ArrayList<>(); RealmResults<AgendaCategory> agendaCategoryItem = realm.where(AgendaCategory.class).equalTo("id", agenda_id).sort("sort_order").findAll(); agendaCategoryItem.load(); alstAgendaCategory.addAll(realm.copyFromRealm(agendaCategoryItem)); return alstAgendaCategory; } public void insertChatRoom(ChatRoom chatRoom) { realm.beginTransaction(); realm.copyToRealmOrUpdate(chatRoom); realm.commitTransaction(); } public void insertUserDevices(UserDevice userDevice) { realm.beginTransaction(); realm.copyToRealmOrUpdate(userDevice); realm.commitTransaction(); } public void insertUsers(User user) { realm.beginTransaction(); realm.copyToRealmOrUpdate(user); realm.commitTransaction(); } public void insertNotificationList(ArrayList<NotificationList> notificationList) { realm.beginTransaction(); realm.copyToRealmOrUpdate(notificationList); realm.commitTransaction(); } public void insertCountryList(ArrayList<Country> countryList) { realm.beginTransaction(); realm.copyToRealmOrUpdate(countryList); realm.commitTransaction(); } public void insertNotification(NotificationList notificationList) { realm.beginTransaction(); realm.copyToRealmOrUpdate(notificationList); realm.commitTransaction(); } public ArrayList<NotificationList> getNotificationList() { ArrayList<NotificationList> notificationList = new ArrayList<>(); RealmResults<NotificationList> agenda = realm.where(NotificationList.class).findAll(); notificationList.addAll(agenda); return notificationList; } public void insertFAQs(List<FAQsItem> faqs) { realm.beginTransaction(); realm.copyToRealmOrUpdate(faqs); realm.commitTransaction(); } public ArrayList<FAQs> getFAQs() { ArrayList<FAQs> faqs = new ArrayList<>(); RealmResults<FAQs> realmFAQs = realm.where(FAQs.class).equalTo("status", 1).findAll(); faqs.addAll(realm.copyFromRealm(realmFAQs)); return faqs; } public ArrayList<FAQsItem> getFAQsCategory() { ArrayList<FAQsItem> faqs = new ArrayList<>(); RealmResults<FAQsItem> realmFAQs = realm.where(FAQsItem.class).equalTo("status", 1).findAll(); faqs.addAll(realm.copyFromRealm(realmFAQs)); return faqs; } public ArrayList<FAQs> getFAQsCategoryById(int id) { ArrayList<FAQs> alstFAQsCategory = new ArrayList<>(); RealmResults<FAQs> faqsCategoryItem = realm.where(FAQs.class).equalTo("categoryId", id).findAll(); faqsCategoryItem.load(); alstFAQsCategory.addAll(realm.copyFromRealm(faqsCategoryItem)); return alstFAQsCategory; } public ArrayList<FAQsItem> getFAQsByCategory(int id) { ArrayList<FAQsItem> agendaList = new ArrayList<>(); RealmResults<FAQsItem> agenda = realm.where(FAQsItem.class).equalTo("id", id).findAll(); agendaList.addAll(realm.copyFromRealm(agenda)); return agendaList; } public ArrayList<Country> getCountryList() { ArrayList<Country> list = new ArrayList<>(); RealmResults<Country> country = realm.where(Country.class).findAll(); list.addAll(realm.copyFromRealm(country)); return list; } public String getcountryName(int id) { ArrayList<Country> list = new ArrayList<>(); RealmResults<Country> country = realm.where(Country.class).equalTo("id", id).findAll(); list.addAll(realm.copyFromRealm(country)); return list.get(0).getName(); } public String getStateName(int id) { ArrayList<State> list = new ArrayList<>(); RealmResults<State> state = realm.where(State.class).equalTo("id", id).findAll(); list.addAll(realm.copyFromRealm(state)); return list.get(0).getName(); } public ArrayList<State> getStateById(int id) { ArrayList<State> list = new ArrayList<>(); RealmResults<State> state = realm.where(State.class).equalTo("countryId", id).findAll(); list.addAll(realm.copyFromRealm(state)); return list; } public void insertMeeting(ArrayList<Meeting> meetingList) { realm.beginTransaction(); realm.copyToRealmOrUpdate(meetingList); realm.commitTransaction(); } public ArrayList<Meeting> getMeeting() { ArrayList<Meeting> meetingList = new ArrayList<>(); RealmResults<Meeting> meeting = realm.where(Meeting.class).findAll(); meetingList.addAll(realm.copyFromRealm(meeting)); return meetingList; } public ArrayList<Meeting> getDateWiseMeeting(Date date) { ArrayList<Meeting> meetingList = new ArrayList<>(); RealmResults<Meeting> meeting = realm.where(Meeting.class).sort("meetingDate", Sort.ASCENDING).equalTo("meetingDate", date).findAll(); meetingList.addAll(realm.copyFromRealm(meeting)); return meetingList; } public ArrayList<Meeting> getMeetingSentRequest() { ArrayList<Meeting> meetingList = new ArrayList<>(); RealmResults<Meeting> meeting = realm.where(Meeting.class).equalTo("sent", "").findAll(); meetingList.addAll(realm.copyFromRealm(meeting)); return meetingList; } public void insertMeetingRequest(ArrayList<MeetingRequest> meetingList) { realm.beginTransaction(); realm.copyToRealmOrUpdate(meetingList); realm.commitTransaction(); } public ArrayList<MeetingRequest> getMeetingRequest() { ArrayList<MeetingRequest> meetingList = new ArrayList<>(); RealmResults<MeetingRequest> meeting = realm.where(MeetingRequest.class).findAll(); meetingList.addAll(realm.copyFromRealm(meeting)); return meetingList; } public ArrayList<MeetingRequest> getMeetingRequest(String categoryTitle) { ArrayList<MeetingRequest> meetingList = new ArrayList<>(); RealmResults<MeetingRequest> meeting = realm.where(MeetingRequest.class).sort("personCategoryTitle", Sort.ASCENDING).equalTo("personCategoryTitle", categoryTitle).findAll(); meetingList.addAll(realm.copyFromRealm(meeting)); return meetingList; } public void insertPhoto(ArrayList<PhotoGallery> photo) { realm.beginTransaction(); realm.copyToRealmOrUpdate(photo); realm.commitTransaction(); } public void insertVideo(ArrayList<VideoGallery> video) { realm.beginTransaction(); realm.copyToRealmOrUpdate(video); realm.commitTransaction(); } public ArrayList<PhotoGallery> getPhotoGallery() { ArrayList<PhotoGallery> photoList = new ArrayList<>(); RealmResults<PhotoGallery> photos = realm.where(PhotoGallery.class).findAll(); photoList.addAll(realm.copyFromRealm(photos)); return photoList; } public ArrayList<VideoGallery> getVideoGallery() { ArrayList<VideoGallery> videoList = new ArrayList<>(); RealmResults<VideoGallery> videos = realm.where(VideoGallery.class).findAll(); videoList.addAll(realm.copyFromRealm(videos)); return videoList; } public void updateMultipleEntityOption(final ArrayList<EntityAttributeOption> option, EntityAttribute questions) { realm.beginTransaction(); if (option != null && option.size() > 0) { for (int i = 0; i < option.size(); i++) { if (option.get(i).isVoted() == 1) { EntityAttributeOption options = realm.where(EntityAttributeOption.class).equalTo("id", option.get(i).getId()).findFirst();// options.setChecked(true); options.setVoted(1); } else { EntityAttributeOption options = realm.where(EntityAttributeOption.class).equalTo("id", option.get(i).getId()).findFirst();// options.setChecked(false); options.setVoted(0); } } } PollQuestion question = realm.where(PollQuestion.class).equalTo("id", questions.getId()).findFirst(); question.setVoted(1); realm.commitTransaction(); } public void updateDetail(EntityAttribute questions, String answer, int type, int rate) { realm.beginTransaction(); EntityAttribute question = realm.where(EntityAttribute.class) .equalTo("id", questions.getId()).findFirst(); question.setVoted(1); if (type == 3) question.setAnswer(answer); if (type == 4) question.setRating(String.valueOf(rate)); realm.commitTransaction(); } public void closeDataBase() { if (realm != null && !realm.isClosed()) realm.close(); } }*** Fragment ***=========================11)BaseFragment.java
====================package com.testdemo.fragment; import android.content.res.Resources;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.view.animation.AlphaAnimation;import android.view.animation.Animation;import android.view.animation.AnimationUtils;import com.testdemo.MyApplication;import com.testdemo.R;import com.testdemo.activity.HomeActivity;import com.testdemo.api.ApiResponseListener;import java.lang.reflect.Field;import retrofit2.Call;import retrofit2.Response; /** * Created by Manisha on 16-Jul-18. */ public class BaseFragment extends Fragment implements ApiResponseListener { HomeActivity homeActivity; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); homeActivity = (HomeActivity) getActivity(); } // 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 { Field nextAnimField = Fragment.class.getDeclaredField("mNextAnim"); nextAnimField.setAccessible(true); int nextAnimResource = nextAnimField.getInt(fragment); if (nextAnimResource > 0) { Animation nextAnim = AnimationUtils.loadAnimation(fragment.getActivity(), nextAnimResource); return (nextAnim == null) ? defValue : nextAnim.getDuration(); } else return defValue; } catch (NoSuchFieldException | IllegalAccessException | Resources.NotFoundException ex) { ex.printStackTrace(); return defValue; } } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode, String pos) { } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { } }*** interfaces ***==================12) LocationUpdateListener .java================================package com.testdemo.interfaces;import android.location.Location; public interface LocationUpdateListener { /**Called when got location of user*/ void onLocationUpdate(Location location); /**Called when user deny to request of enable Location permission*/ void onLocationPermissionDeny(); /**Called when user deny to request to enable GPS*/ void onGPSRequestDeny();}*** model ***13)BaseModel.java==================package com.testdemo.model; import com.google.gson.Gson;import com.google.gson.annotations.Expose;import com.google.gson.annotations.SerializedName; /** * Created by Manisha */ public class BaseModel { public static Gson GSON = new Gson(); @SerializedName("is_error") @Expose private boolean isError; @SerializedName("message") @Expose private String message; public boolean isError() { return isError; } public void setError(boolean error) { isError = error; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } /** * Convert Model class to JsonObject */ public String toJson() { try { if (GSON == null) GSON = new Gson(); return GSON.toJson(this); } catch (Exception e) { e.printStackTrace(); } return null; } /** * Convert Model class to JsonObject */ public static String toJson(Object modelClass) { try { if (GSON == null) GSON = new Gson(); return GSON.toJson(modelClass); } catch (Exception e) { e.printStackTrace(); } return null; } /** * Convert JsonObject to Model class */ public static Object toModelClass(String strJson, Class<?> modelClass) { try { if (GSON == null) GSON = new Gson(); if (strJson != null && strJson.length() > 0) return GSON.fromJson(strJson, modelClass); } catch (Exception e) { e.printStackTrace(); } return null; } }13) DataModel.java====================package com.testdemo.model; import com.google.gson.annotations.Expose;import com.google.gson.annotations.SerializedName; import io.realm.RealmObject; public class DataModel extends RealmObject { @SerializedName("id") @Expose private int id; @SerializedName("name") @Expose private String name; @SerializedName("unit") @Expose private String unit; @SerializedName("code") @Expose private int code; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUnit() { return unit; } public void setUnit(String unit) { this.unit = unit; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } }*** Utility ****==================14)Constants.java==================package com.testdemo.Utility;public class Constants { public static final String PACKAGE = "com.piitch"; public static final String TAG = "piitch"; public static final int TYPE_ITEM = 1; public static final int TYPE_FOOTER = 2; // Preference key public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String LOCATION = "location";}15)CustomDialog.java====================package com.testdemo.Utility; import android.app.AlertDialog;import android.app.ProgressDialog;import android.content.Context;import android.content.DialogInterface;import android.support.annotation.NonNull;import com.testdemo.R; /** * Created by Manisha on 16-Jul-18. */ public class CustomDialog { private static CustomDialog customDialog; ProgressDialog progressDialog; public static CustomDialog getInstance() { if (customDialog == null) { customDialog = new CustomDialog(); } return customDialog; } /** * Show progress dialog without message, Before show new dialog it is hide previous showing dialog * * @param context Context of activity. * @param cancelable true: Hide out side touch or back press, false: Can not hide out side touch */ public void show(@NonNull Context context, boolean cancelable) { try { //Before show new dialog hide previous showing dialog hide(); progressDialog = new ProgressDialog(context); progressDialog.setCancelable(cancelable); progressDialog.setMessage(context.getString(R.string.msgLoading)); progressDialog.show(); /*if (progressDialog != null) { if (!progressDialog.isShowing()) { progressDialog.show(); } }*/ } catch (Exception e) { e.printStackTrace(); } } /** * Show progress dialog without message, Before show new dialog it is hide previous showing dialog * * @param context Context of activity. * @param message PollAnswer of dialog. * @param cancelable true: Hide out side touch or back press, false: Can not hide out side touch */ public void show(@NonNull Context context, @NonNull String message, boolean cancelable) { try { //Before show new dialog hide previous showing dialog hide(); //Set default dialog message "Loading" message = (message != null && message.trim().length() > 0) ? message : context.getString(R.string.msgLoading); progressDialog = new ProgressDialog(context); progressDialog.setMessage(message); progressDialog.setCancelable(cancelable); if (!progressDialog.isShowing()) { progressDialog.show(); } /*if (progressDialog != null) { if (!progressDialog.isShowing()) { progressDialog.show(); } }*/ } catch (Exception e) { e.printStackTrace(); } } public void hide() { if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); } } public boolean isDialogShowing() { if (progressDialog != null) return progressDialog.isShowing(); else return false; } // Show alert dialog public void showMessageDialog(Context context, String title, String message) { /* if(title == null && title.equalsIgnoreCase("")){ title = "Eppico"; }*/ if (message != null && message.trim().length() > 0) { AlertDialog.Builder builder = new AlertDialog.Builder(context); //builder.setTitle(title); builder.setCancelable(true); builder.setMessage(message); builder.setPositiveButton(context.getString(R.string.btnOk), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); // create alert dialog AlertDialog alertDialog = builder.create(); // show it alertDialog.show(); } } //Show alert dialog public void showMessageDialog(Context context, String message) { if (message != null && message.trim().length() > 0) { AlertDialog.Builder builder = new AlertDialog.Builder(context); //builder.setTitle(title); builder.setCancelable(true); builder.setMessage(message); builder.setPositiveButton(context.getString(R.string.btnOk), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); // create alert dialog AlertDialog alertDialog = builder.create(); // show it alertDialog.show(); } } public void showMessageDialog(Context context) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(false); builder.setMessage("sdfsd"); builder.setPositiveButton(context.getString(R.string.btnOk), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } }16)PermissionUtil.java======================/** Copyright 2015 The Android Open Source Project** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/ package com.testdemo.Utility; import android.Manifest;import android.app.Activity;import android.content.pm.PackageManager; import java.util.ArrayList; /** * Utility class that wraps access to the runtime permissions API in M and provides basic helper * methods. */public class PermissionUtil { static PermissionUtil permissionUtil; public static PermissionUtil getInstance() { if(permissionUtil==null) permissionUtil=new PermissionUtil(); return permissionUtil; } /** * Check that all given permissions have been granted by verifying that each entry in the * given array is of the value {@link PackageManager#PERMISSION_GRANTED}. * * @see Activity#onRequestPermissionsResult(int, String[], int[]) */ public static boolean verifyPermissions(int[] grantResults) { // At least one result must be checked. if(grantResults.length < 1){ return false; } // Verify that each required permission has been granted, otherwise return false. for (int result : grantResults) { if (result != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } public ArrayList<String> verifyPermissions(String permissions[], int[] grantResults) { // At least one result must be checked. if(permissions!=null && grantResults!=null && permissions.length>0 && grantResults.length>0) { ArrayList<String> listPermissionsNotGranted=new ArrayList<String>(); // Verify that each required permission has been granted, otherwise return false. for (int i=0;i<grantResults.length;i++) { if (grantResults[i] != PackageManager.PERMISSION_GRANTED) { listPermissionsNotGranted.add(permissions[i]); } } return listPermissionsNotGranted; } return null; } public ArrayList<String> getCameraPermissionsList() { ArrayList<String> listPermissionsNeed=new ArrayList<String>(); listPermissionsNeed.add(Manifest.permission.CAMERA); listPermissionsNeed.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); return listPermissionsNeed; } public ArrayList<String> getGalleryPermission() { ArrayList<String> listPermissionsNeed=new ArrayList<String>(); listPermissionsNeed.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); return listPermissionsNeed; } }17)PrefHelper.java==================package com.testdemo.Utility; import android.content.SharedPreferences.Editor;import android.util.Log;import com.testdemo.MyApplication;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;import java.util.Date;import java.util.Map; /** * Created by Manisha on 16-Jul-18. */ public class PrefHelper { private static PrefHelper prefHelper; public static PrefHelper getInstance() { if (prefHelper == null) { prefHelper = new PrefHelper(); } return prefHelper; } public static void setDate(String key, Date value) { final Editor editor = MyApplication.myPref.edit(); editor.putString(key, Utils.getFormattedDate(value, "yyyy-MM-dd hh:mm:ss")); apply(editor); } public static void setString(String key, String value) { final Editor editor = MyApplication.myPref.edit(); editor.putString(key, value); apply(editor); } public static Date getDate(String key, String defaultValue) { Date date = null; String strDate = MyApplication.myPref.getString(key, ""); if(Utils.validateString(strDate)) { date = Utils.getDateFromString(strDate, "yyyy-MM-dd hh:mm:ss"); } return date; } public static String getString(String key, String defaultValue) { return MyApplication.myPref.getString(key, defaultValue); } public static void setBoolean(String key, Boolean value){ final Editor editor = MyApplication.myPref.edit(); editor.putBoolean(key,value); apply(editor); } public static boolean getBoolean(String key, boolean defaultValue) { return MyApplication.myPref.getBoolean(key, defaultValue); } public static void setInt(String key, int value){ final Editor editor = MyApplication.myPref.edit(); editor.putInt(key,value); apply(editor); } public static int getInt(String key, int defaultValue){ return MyApplication.myPref.getInt(key,defaultValue); } public static void setLong(String key, long value){ final Editor editor = MyApplication.myPref.edit(); editor.putLong(key,value); apply(editor); } public static long getLong(String key, long defaultValue){ return MyApplication.myPref.getLong(key,defaultValue); } public static double getDouble(String key, double defaultValue) { // return MyApplication.myPref.getLong(key, defaultValue); return Double.longBitsToDouble(MyApplication.myPref.getLong(key, Double.doubleToLongBits(defaultValue))); } public static void setDouble(String key, double value) { final Editor editor = MyApplication.myPref.edit(); editor.putLong(key, Double.doubleToRawLongBits(value)); apply(editor); } public static void deletePreference(String key) { final Editor editor = MyApplication.myPref.edit(); editor.remove(key); apply(editor); } public static void deletePreferences(String[] keys) { if(keys!=null && keys.length>0) { // Editor editor = null; for(int i=0;i<keys.length;i++) { final Editor editor= MyApplication.myPref.edit(); editor.remove(keys[i]); apply(editor); } } } public static void deleteAllPreferences() { final Editor editor = MyApplication.myPref.edit(); editor.clear(); apply(editor); } /*Delete all preference of app except passed argument*/ public static void deletePreferencesExcept(ArrayList<String> keysNotDelete) { //SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(MyApplication.appInstance); Map<String,?> keys = MyApplication.myPref.getAll(); for(Map.Entry<String,?> entry : keys.entrySet()){ Log.d("map values", entry.getKey() + ": " + entry.getValue().toString()); if(!keysNotDelete.contains(entry.getKey())) { final Editor editor= MyApplication.myPref.edit(); editor.remove(entry.getKey()); apply(editor); } } } // Faster pref saving for high performance private static final Method sApplyMethod = findApplyMethod(); private static Method findApplyMethod() { try { final Class<Editor> cls = Editor.class; return cls.getMethod("apply"); } catch (final NoSuchMethodException unused) { // fall through } return null; } public static void apply(final Editor editor) { if (sApplyMethod != null) { try { sApplyMethod.invoke(editor); return; } catch (final InvocationTargetException unused) { // fall through } catch (final IllegalAccessException unused) { // fall through } } editor.commit(); } }18)ToastHelper.java=====================package com.testdemo.Utility; import android.content.Context;import android.support.annotation.NonNull;import android.widget.Toast; /** * Created by Manisha on 16-Jul-18. */ public class ToastHelper { private static ToastHelper toastHelper; private Toast toast; public static ToastHelper getInstance() { if (toastHelper == null) { toastHelper = new ToastHelper(); } return toastHelper; } public void showToast(@NonNull Context context, String message) { if (toast != null) { toast.cancel(); } toast = Toast.makeText(context, message, Toast.LENGTH_SHORT); toast.show(); } public void showToast(@NonNull Context context, String message, int duration) { if (toast != null) { toast.cancel(); } toast = Toast.makeText(context, message, duration); toast.show(); } }19)Utils.java==============package com.testdemo.Utility; import android.annotation.SuppressLint;import android.annotation.TargetApi;import android.app.Activity;import android.app.ActivityManager;import android.app.AlertDialog;import android.content.ComponentName;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.content.pm.Signature;import android.content.res.ColorStateList;import android.database.Cursor;import android.graphics.Bitmap;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.ColorFilter;import android.graphics.LightingColorFilter;import android.graphics.Paint;import android.graphics.drawable.BitmapDrawable;import android.graphics.drawable.Drawable;import android.graphics.drawable.GradientDrawable;import android.net.ConnectivityManager;import android.net.NetworkInfo;import android.net.Uri;import android.net.wifi.WifiManager;import android.os.Build;import android.os.Environment;import android.provider.MediaStore;import android.support.annotation.Nullable;import android.support.v4.content.ContextCompat;import android.support.v4.graphics.drawable.DrawableCompat;import android.support.v7.widget.AppCompatRadioButton;import android.text.Spannable;import android.text.SpannableStringBuilder;import android.text.TextUtils;import android.text.style.ForegroundColorSpan;import android.util.Base64;import android.util.DisplayMetrics;import android.util.Log;import android.view.View;import android.view.Window;import android.view.WindowManager;import android.view.inputmethod.InputMethodManager;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.Inet4Address;import java.net.InetAddress;import java.net.MalformedURLException;import java.net.NetworkInterface;import java.net.SocketException;import java.net.URL;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.text.DateFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Calendar;import java.util.Date;import java.util.Enumeration;import java.util.List;import java.util.Random;import java.util.regex.Matcher;import java.util.regex.Pattern; /** * Created by Manisha on 16-Jul-18. */ public class Utils { private static Utils utils; public static Utils getInstance() { if (utils == null) { utils = new Utils(); } return utils; } public boolean isEmailValid(String email) { String expression = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; CharSequence inputStr = email; boolean flag = false; Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(inputStr); if (matcher.matches()) { flag = true; } return flag; } public boolean checkInternetConnection(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // test for connection if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected()) { return true; } else { Log.v("", "Internet Connection Not Available"); //Toast.makeText(context, context.getResources().getString(R.string.network_connectivity_not_available), Toast.LENGTH_SHORT).show(); return false; } } public String generateHashKey(Context context) { String hashKey = ""; try { PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES); for (Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); hashKey = Base64.encodeToString(md.digest(), Base64.DEFAULT); MyLog.v("TAG", "Hash Key:" + hashKey); } } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return hashKey; } @SuppressLint("NewApi") public static boolean validateString(String object) { boolean flag = false; if (object != null && !object.equalsIgnoreCase("null") && !object.equalsIgnoreCase("(null)") && !object.isEmpty() && !object.equalsIgnoreCase("(null)")) { flag = true; } return flag; } public int getDeviceWidth(Activity context) { DisplayMetrics displayMetrics = new DisplayMetrics(); context.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); int width = displayMetrics.widthPixels; int height = displayMetrics.heightPixels;// Toast.makeText(context, "Width: " + width +"height: " + height , Toast.LENGTH_LONG).show(); return width; } public int getDeviceHeight(Activity context) { DisplayMetrics displayMetrics = new DisplayMetrics(); context.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); int width = displayMetrics.widthPixels; int height = displayMetrics.heightPixels;// Toast.makeText(context, "\n Height: " + height, Toast.LENGTH_LONG).show(); return height; } public String getFormattedDate(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); //2nd of march 2015 int day = cal.get(Calendar.DATE); switch (day % 10) { case 1: return new SimpleDateFormat("d'st' MMMM").format(date); case 2: return new SimpleDateFormat("d'nd' MMMM").format(date); case 3: return new SimpleDateFormat("d'rd' MMMM").format(date); default: return new SimpleDateFormat("d'th' MMMM").format(date); } } public static Date getDateFromString(String inputDate, String format) { if (!Utils.validateString(format)) format = "dd-MMMM-yyyy hh:mm:ss"; Date date = null; Date outputDate = null; SimpleDateFormat formatter = new SimpleDateFormat(format); try { date = formatter.parse(inputDate); } catch (Exception e) { Log.e("formattedDateFromString", "Exception in formateDateFromstring(): " + e.getMessage()); } return date; } public static String getFormattedDate(Date date, String format) { if (!Utils.validateString(format)) format = "yyyy-MM-dd hh:mm:ss"; SimpleDateFormat timeFormatter = new SimpleDateFormat(format); if (format.indexOf("'s'") >= 0) { Calendar cal = Calendar.getInstance(); cal.setTime(date); int day = cal.get(Calendar.DATE); switch (day % 10) { case 1: timeFormatter = new SimpleDateFormat(format.replace("'s'", "'st'")); case 2: timeFormatter = new SimpleDateFormat(format.replace("'s'", "'nd'")); case 3: timeFormatter = new SimpleDateFormat(format.replace("'s'", "'rd'")); default: timeFormatter = new SimpleDateFormat(format.replace("'s'", "'th'")); } } String displayValue = timeFormatter.format(date); return displayValue; } public static String getFormattedDate(String strDate, String format) { if (!Utils.validateString(format)) format = "yyyy-MM-dd hh:mm:ss"; Date date = null; SimpleDateFormat dateFormatter = new SimpleDateFormat(format); try { date = dateFormatter.parse(strDate); } catch (ParseException e) { e.printStackTrace(); } return getFormattedDate(date, format); } public static String getTime(String strDate) { SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date date = null; try { date = dateFormatter.parse(strDate); } catch (ParseException e) { e.printStackTrace(); } return getTime(date); } public static String getNotificationTime(String strDate) { SimpleDateFormat parseFormat = new SimpleDateFormat("E, dd MMMM yyyy hh:mm a"); Date date = new Date(); String dateString = parseFormat.format(date); return dateString; } /**Return formatted date of passed output format*/ public String getFormattedDate(String date, String input, String output) { try { SimpleDateFormat sdfInput = new SimpleDateFormat(input); SimpleDateFormat sdfOutput = new SimpleDateFormat(output); return sdfOutput.format(sdfInput.parse(date)); } catch (Exception e) { e.printStackTrace(); } return ""; } public static String getTime(Date date) { SimpleDateFormat timeFormatter = new SimpleDateFormat("hh:mm a"); String displayValue = timeFormatter.format(date); return displayValue; } public static String implode(String glue, ArrayList<String> strings) { String str = ""; for (int i = 0; i < strings.size(); i++) str += strings.get(i) + ((i + 1) == strings.size() ? "" : glue); return str; } public static boolean isEmpty(String object) { if (object == null || object.equalsIgnoreCase("null") || object.equalsIgnoreCase("(null)") || object.isEmpty() || object.equalsIgnoreCase("(null)")) { return true; } return false; } public static boolean isEmpty(int item) { if (item == 0) return true; return false; } public static String getFormatedDate(String dateString) { DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd"); Date date1 = null; try { date1 = df1.parse(dateString); } catch (ParseException e) { e.printStackTrace(); } return getFormatedDate(date1); } public static String getFormatedDate(Date date) { SimpleDateFormat ddMMMMyyFormat = new SimpleDateFormat("dd MMMM yyyy"); String date_to_string = ddMMMMyyFormat.format(date); return date_to_string; } public static String getTimeWithDay(String strDate) { SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date date = null; try { date = dateFormatter.parse(strDate); } catch (ParseException e) { e.printStackTrace(); } // Get time from date SimpleDateFormat timeFormatter = new SimpleDateFormat("hh:mm a (EEEE)"); String displayValue = timeFormatter.format(date); return displayValue; } public static String getDay(String strDate) { SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); Date date = null; try { date = dateFormatter.parse(strDate); } catch (ParseException e) { e.printStackTrace(); } // Get time from date SimpleDateFormat timeFormatter = new SimpleDateFormat("EEEE"); String displayValue = timeFormatter.format(date); return displayValue; } public GradientDrawable createRegisterGradientDrawable(String startColor, String endColor) { int[] colors = {Color.parseColor(startColor), Color.parseColor(endColor)}; GradientDrawable gradientdrawable = new GradientDrawable( GradientDrawable.Orientation.LEFT_RIGHT, colors); gradientdrawable.setShape(GradientDrawable.RECTANGLE); gradientdrawable.setColors(colors); gradientdrawable.setCornerRadius(12.0f); gradientdrawable.setState(new int[]{android.R.attr.state_pressed}); return gradientdrawable; } public GradientDrawable createGradientDrawable(String startColor, String endColor) { int[] colors = {Color.parseColor(startColor), Color.parseColor(endColor)}; GradientDrawable gradientdrawable = new GradientDrawable( GradientDrawable.Orientation.LEFT_RIGHT, colors); gradientdrawable.setShape(GradientDrawable.RECTANGLE); gradientdrawable.setColors(colors); gradientdrawable.setState(new int[]{android.R.attr.state_pressed}); return gradientdrawable;// mBinding.actHomeLytDate.setBackground(gradientdrawable); } public GradientDrawable createGradientLineDrawable(String startColor, String endColor) { int[] colors = {Color.parseColor(startColor), Color.parseColor(endColor)}; GradientDrawable gradientdrawable = new GradientDrawable( GradientDrawable.Orientation.TOP_BOTTOM, colors); gradientdrawable.setSize(35, 7); gradientdrawable.setCornerRadius(7.0f); gradientdrawable.setShape(GradientDrawable.RECTANGLE); gradientdrawable.setColors(colors); gradientdrawable.setState(new int[]{android.R.attr.state_pressed}); return gradientdrawable;// mBinding.actHomeLytDate.setBackground(gradientdrawable); } public GradientDrawable createSquareGradientDrawable(String startColor, String endColor) { if (Utils.validateString(startColor) && Utils.validateString(endColor)) { int[] colors = {Color.parseColor(startColor), Color.parseColor(endColor)}; GradientDrawable gradientdrawable = new GradientDrawable( GradientDrawable.Orientation.LEFT_RIGHT, colors); gradientdrawable.setShape(GradientDrawable.RECTANGLE); gradientdrawable.setColors(colors); gradientdrawable.setState(new int[]{android.R.attr.state_pressed}); return gradientdrawable; } return null; } public GradientDrawable createCircularGradientDrawable(String startColor, String endColor) { int[] colors = {Color.parseColor(startColor), Color.parseColor(endColor)}; GradientDrawable gradientdrawable = new GradientDrawable( GradientDrawable.Orientation.LEFT_RIGHT, colors); gradientdrawable.setShape(GradientDrawable.OVAL); gradientdrawable.setColors(colors); gradientdrawable.setState(new int[]{android.R.attr.state_pressed}); return gradientdrawable;// mBinding.actHomeLytDate.setBackground(gradientdrawable); } //============================================ CHANGE ICON COLOR DYNAMICALLY ======================================================= public static Drawable sChangeIconColor(Context context, String strColorCode, int iconId) { Drawable finalDrawable = null; if (strColorCode != null && strColorCode.length() > 0 && strColorCode.length() == 7) { int mColorCode = Color.parseColor(strColorCode); //Get the image to be changed from the drawable, drawable-xhdpi, drawable-hdpi,etc folder. Drawable sourceDrawable = ContextCompat.getDrawable(context, iconId);//context.getResources().getDrawable(R.drawable.android); //Convert drawable in to bitmap Bitmap sourceBitmap = convertDrawableToBitmap(sourceDrawable); //Pass the bitmap and color code to change the icon color dynamically. Bitmap finalBitmap = changeImageColor(sourceBitmap, mColorCode); finalDrawable = new BitmapDrawable(context.getResources(), finalBitmap); /*imgIcon.setImageBitmap(mFinalBitmap);*/ } else { //Toast.makeText(context, "Please enter valid color code with '#' followed by code(Eg : #FFFFFF)",Toast.LENGTH_SHORT).show(); } return finalDrawable; } //============================================ CHANGE ICON COLOR DYNAMICALLY ======================================================= public static Drawable ChangeIconColor(Context context, String strColorCode, Bitmap sourceBitmap) { Drawable finalDrawable = null; if (strColorCode != null && strColorCode.length() > 0 && strColorCode.length() == 7) { int mColorCode = Color.parseColor(strColorCode); //Get the image to be changed from the drawable, drawable-xhdpi, drawable-hdpi,etc folder.// Drawable sourceDrawable = ContextCompat.getDrawable(context, iconId);//context.getResources().getDrawable(R.drawable.android); //Convert drawable in to bitmap// Bitmap sourceBitmap = convertDrawableToBitmap(sourceDrawable); //Pass the bitmap and color code to change the icon color dynamically. Bitmap finalBitmap = changeImageColor(sourceBitmap, mColorCode); finalDrawable = new BitmapDrawable(context.getResources(), finalBitmap); /*imgIcon.setImageBitmap(mFinalBitmap);*/ } else { //Toast.makeText(context, "Please enter valid color code with '#' followed by code(Eg : #FFFFFF)",Toast.LENGTH_SHORT).show(); } return finalDrawable; } public static Bitmap changeImageColor(Bitmap sourceBitmap, int color) { Bitmap resultBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth() - 1, sourceBitmap.getHeight() - 1); Paint p = new Paint(); ColorFilter filter = new LightingColorFilter(color, 1); p.setColorFilter(filter); Canvas canvas = new Canvas(resultBitmap); canvas.drawBitmap(resultBitmap, 0, 0, p); return resultBitmap; } public static Bitmap convertDrawableToBitmap(Drawable drawable) { if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } public static Drawable changeDrawableColor(Drawable drawable, int color) { drawable = DrawableCompat.wrap(drawable); DrawableCompat.setTint(drawable, color); return drawable; } public static String getPathFromURL(String Stringurl) { String filepath = ""; try { URL url = new URL(Stringurl); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.connect(); File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile(); String filename = "downloadedFile.png"; Log.i("Local filename:", "" + filename); File file = new File(SDCardRoot, filename); if (file.createNewFile()) { file.createNewFile(); } // File file = new File(getFilename());// file.createNewFile(); filepath = file.getPath(); FileOutputStream fileOutput = new FileOutputStream(file); InputStream inputStream = urlConnection.getInputStream(); int totalSize = urlConnection.getContentLength(); int downloadedSize = 0; byte[] buffer = new byte[1024]; int bufferLength = 0; while ((bufferLength = inputStream.read(buffer)) > 0) { fileOutput.write(buffer, 0, bufferLength); downloadedSize += bufferLength; Log.i("Progress:", "downloadedSize:" + downloadedSize + "totalSize:" + totalSize); } fileOutput.close(); if (downloadedSize == totalSize) filepath = file.getPath(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { filepath = null; e.printStackTrace(); } Log.i("filepath:", " " + filepath); return filepath; } private static String getFilename() { String filepath = Environment.getExternalStorageDirectory().getPath(); File file = new File(filepath, ".PIITCH"); if (!file.exists()) { file.mkdirs(); } return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".png"); } public static void setRadioColor(String color, AppCompatRadioButton radio) { if (Build.VERSION.SDK_INT >= 21) { ColorStateList colorStateList = new ColorStateList( new int[][]{ new int[]{-android.R.attr.state_enabled}, //disabled new int[]{android.R.attr.state_enabled} //enabled }, new int[]{ Color.DKGRAY//disabled , (Color.parseColor(color)) //enabled } ); radio.setButtonTintList(colorStateList);//set the color tint list radio.invalidate(); //could not be necessary } } public static int getRandomColor() { Random rnd = new Random(); return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)); } public String getVersionCode(Context activity) { String strVersionCode = ""; String strVersionName = ""; try { PackageInfo pInfo = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0);// strVersionName = pInfo.versionName; strVersionCode = String.valueOf(pInfo.versionCode); return strVersionCode; } catch (Exception e) { } return strVersionCode; } public String getVersionName(Context activity) { String strVersionName = ""; try { PackageInfo pInfo = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0);// strVersionName = pInfo.versionName; strVersionName = String.valueOf(pInfo.versionName); return strVersionName; } catch (Exception e) { } return strVersionName; } // public static String getDeviceIPAddress(Context context) {// String actualConnectedToNetwork = null;// ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);// if (connManager != null) {// NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);// if (mWifi.isConnected()) {// actualConnectedToNetwork = getWifiIp(context);// }// }// if (TextUtils.isEmpty(actualConnectedToNetwork)) {// actualConnectedToNetwork = getNetworkInterfaceIpAddress();// }// if (TextUtils.isEmpty(actualConnectedToNetwork)) {// actualConnectedToNetwork = "127.0.0.1";// }// return actualConnectedToNetwork;// } // @Nullable// public static String getWifiIp(Context context) {// final WifiManager mWifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);// if (mWifiManager != null && mWifiManager.isWifiEnabled()) {// int ip = mWifiManager.getConnectionInfo().getIpAddress();// return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "."// + ((ip >> 24) & 0xFF);// }// return null;// } @Nullable public static String getNetworkInterfaceIpAddress() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) { NetworkInterface networkInterface = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { String host = inetAddress.getHostAddress(); if (!TextUtils.isEmpty(host)) { return host; } } } } } catch (Exception ex) { Log.e("IP Address", "getLocalIpAddress", ex); } return null; } public void convertMilisecondToDate(long currentDateTime) { // long currentDateTime = System.currentTimeMillis(); //creating Date from millisecond Date currentDate = new Date(currentDateTime); //printing value of Date System.out.println("current Date: " + currentDate); DateFormat df = new SimpleDateFormat("dd:MM:yy:HH:mm:ss"); //formatted value of current Date System.out.println("Milliseconds to Date: " + df.format(currentDate)); //Converting milliseconds to Date using Calendar Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(currentDateTime); System.out.println("Milliseconds to Date using Calendar:" + df.format(cal.getTime())); //copying one Date's value into another Date in Java Date now = new Date(); Date copiedDate = new Date(now.getTime()); System.out.println("original Date: " + df.format(now)); System.out.println("copied Date: " + df.format(copiedDate)); } // public static void showLoginMessageDialog(final Context context, String message) {// AlertDialog.Builder builder = new AlertDialog.Builder(context);// builder.setCancelable(false);// builder.setMessage(message);// builder.setPositiveButton(context.getString(R.string.btnOk), new DialogInterface.OnClickListener() {// @Override// public void onClick(DialogInterface dialog, int which) {// dialog.dismiss();// Intent mIntent = new Intent(context, LoginActivity.class);// ((Activity) context).startActivity(mIntent);// ((Activity) context).finish();// }// });//// builder.setNegativeButton(context.getString(R.string.btnCancel), new DialogInterface.OnClickListener() {// @Override// public void onClick(DialogInterface dialog, int which) {// dialog.dismiss();// }// });//// AlertDialog alertDialog = builder.create();// alertDialog.show();// } public void hideKeyboard(View v, Context context) { InputMethodManager mgr = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); mgr.hideSoftInputFromWindow(v.getWindowToken(), 0); } public void showKeyboard(View v, Context context) {/* * InputMethodManager mgr = * (InputMethodManager)context.getSystemService(* Context.INPUT_METHOD_SERVICE); mgr.showSoftInput(v, 0); */ InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.toggleSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0); } /**Return image path of given URI*/ public String getRealPathFromURI(Context context, Uri contentURI) { // Cursor cursor = getActivity().getContentResolver().query(contentURI, null, null, null, null); String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = context.getContentResolver().query(contentURI, projection, null, null, null); //Some of gallery application is return null if (cursor == null) { return contentURI.getPath(); } else { cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(projection[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); return picturePath; } } public static SpannableStringBuilder setSpannedText(String question) { String simple = question; String colored = "*"; SpannableStringBuilder builder = new SpannableStringBuilder(simple + colored); builder.setSpan(new ForegroundColorSpan(Color.RED), simple.length(), builder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); return builder; } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public static void setStatusBarGradiant(Activity activity, String start_color, String end_color) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Window window = activity.getWindow(); GradientDrawable gradientDrawable = Utils.getInstance().createGradientDrawable(start_color, end_color);// Drawable background = activity.getResources().getDrawable(R.drawable.gradient_theme); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.setStatusBarColor(activity.getResources().getColor(android.R.color.transparent)); window.setNavigationBarColor(activity.getResources().getColor(android.R.color.transparent));// window.setBackgroundDrawable(background); window.setBackgroundDrawable(gradientDrawable); } } }20) MainActivity.java
========================
package com.webinfinium.vmukti.activity; import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.databinding.DataBindingUtil;import android.os.Bundle;import android.os.Handler;import android.os.Looper;import android.preference.Preference;import android.support.annotation.NonNull;import android.support.annotation.Nullable;import android.support.design.widget.BottomNavigationView;import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentTransaction;import android.util.Log;import android.view.MenuItem;import android.widget.Toast; import com.google.firebase.iid.FirebaseInstanceId;import com.webinfinium.vmukti.R;import com.webinfinium.vmukti.api.RestClient;import com.webinfinium.vmukti.databinding.ActivityHomeBinding;import com.webinfinium.vmukti.fragment.ExpenseFragment;import com.webinfinium.vmukti.fragment.HomeFragment;import com.webinfinium.vmukti.fragment.PendingRequestFragment;import com.webinfinium.vmukti.fragment.ReturnMobileFragment;import com.webinfinium.vmukti.fragment.TransferMobileFragment; import com.webinfinium.vmukti.interfaces.BackPressedEventListener;import com.webinfinium.vmukti.interfaces.OnUpdateMenuListner;import com.webinfinium.vmukti.models.Logout;import com.webinfinium.vmukti.utility.Constants;import com.webinfinium.vmukti.utility.CustomDialog;import com.webinfinium.vmukti.utility.PrefHelper;import com.webinfinium.vmukti.widget.BottomNavigationViewHelper; import java.io.IOException; import retrofit2.Call;import retrofit2.Response; public class HomeActivity extends BaseActivity implements OnUpdateMenuListner { ActivityHomeBinding mBinding; FragmentManager fragmentManager; private Fragment currentFragment; BackPressedEventListener backPressedEventListener; private String is_from, moduleId = ""; private int rollId = 0; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding = DataBindingUtil.setContentView(this, R.layout.activity_home); init(); setupBottomNavigation(); } public void init() { fragmentManager = getSupportFragmentManager(); rollId = PrefHelper.getInt(Constants.ROLL_ID, 0); if (getIntent() != null && getIntent().getExtras() != null) { if (getIntent().getStringExtra(Constants.IS_FROM) != null) { is_from = getIntent().getStringExtra(Constants.IS_FROM); if (is_from.equals(Constants.NOTIFICATION)) { if (getIntent().getExtras().getString(Constants.INTENT_MODULE_ID) != null) { moduleId = getIntent().getExtras().getString(Constants.INTENT_MODULE_ID); if (moduleId != null) { if (moduleId.equalsIgnoreCase("1")) { // Transfer = 1 (open Pending Screen) PendingRequestFragment fragment = PendingRequestFragment.newInstance(); setMenuSelected(3); mReplaceFragment(fragment, null); } else { HomeFragment homeFragment = HomeFragment.newInstance(); setMenuSelected(0); mReplaceFragment(homeFragment, null); } } } } else if (is_from.equalsIgnoreCase(Constants.CREATE_USER)) { String mobileNo = ""; TransferMobileFragment fragment = TransferMobileFragment.newInstance(); if (getIntent().getExtras().getString(Constants.MOBILE_NO) != null) { mobileNo = getIntent().getExtras().getString(Constants.MOBILE_NO); } Bundle bundle = new Bundle(); bundle.putString(Constants.IS_FROM, Constants.CREATE_USER); bundle.putString(Constants.MOBILE_NO, mobileNo); fragment.setArguments(bundle); setMenuSelected(1); // mReplaceFragment(fragment, null); pushFragments(fragment, true, true, false); } } } else { HomeFragment homeFragment = HomeFragment.newInstance(); mReplaceFragment(homeFragment, null); } } @Override protected void onResume() { super.onResume(); } @Override protected void onStart() { super.onStart(); // EventBus.getDefault().register(this); } @Override protected void onStop() { super.onStop(); // EventBus.getDefault().unregister(this); } public Fragment myFragment; private void setupBottomNavigation() { removeAllFragment(); BottomNavigationViewHelper.disableShiftMode(mBinding.bottomNavigation); BottomNavigationViewHelper.removeShiftMode(mBinding.bottomNavigation); if (rollId == 4) { mBinding.bottomNavigation.getMenu().findItem(R.id.navigation_expense).setIcon(R.mipmap.icn_logout_active); mBinding.bottomNavigation.getMenu().findItem(R.id.navigation_expense).setTitle(getResources().getString(R.string.logout)); } else { mBinding.bottomNavigation.getMenu().findItem(R.id.navigation_expense).setIcon(R.mipmap.icn_expense_active); mBinding.bottomNavigation.getMenu().findItem(R.id.navigation_expense).setTitle(getResources().getString(R.string.expense)); } mBinding.bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.navigation_dashboard: myFragment = HomeFragment.newInstance(); pushFragments(myFragment, false, false, true); return true; case R.id.navigation_transfer: // Constants.TO_WAREHOUSE_ID = 0;// myFragment = WarehouseFragment.newInstance();// pushFragments(myFragment, false, false, true); myFragment = TransferMobileFragment.newInstance(); pushFragments(myFragment, false, false, true); return true; case R.id.navigation_return: myFragment = ReturnMobileFragment.newInstance(); pushFragments(myFragment, false, false, true); return true; case R.id.navigation_pending: myFragment = PendingRequestFragment.newInstance(); pushFragments(myFragment, false, false, true); return true; case R.id.navigation_expense: if (rollId == 4) { showLogoutAlert(); } else { myFragment = ExpenseFragment.newInstance(); pushFragments(myFragment, false, false, true); } return true; } return false; } }); } public void pushFragments(Fragment fragment, boolean shouldAnimate, boolean isReverse, boolean shouldAddBackStack) { try { 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.act_home_frag_container, fragment, fragmentTag); if (shouldAddBackStack) ft.addToBackStack(fragmentTag); ft.commit(); } catch (Exception e) { e.printStackTrace(); } } public void addFragments(Fragment fragment, boolean shouldAnimate, boolean isReverse, boolean shouldAddBackStack) { try { 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.add(R.id.act_home_frag_container, fragment, fragmentTag); if (shouldAddBackStack) ft.addToBackStack(fragmentTag); ft.commit(); } catch (Exception e) { e.printStackTrace(); } } private void mReplaceFragment(Fragment fragment, Bundle b) { // currentFragment = fragment; FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); if (b != null) fragment.setArguments(b); transaction.replace(R.id.act_home_frag_container, fragment);// transaction.addToBackStack(null); transaction.commit(); } /*Remove all fragments from back stack*/ public void removeAllFragment() { int fragmentsCount = fragmentManager.getBackStackEntryCount(); Log.e("fragmentsCount:", "fragmentsCount::" + fragmentsCount); if (fragmentsCount > 0) { FragmentTransaction ft = fragmentManager.beginTransaction(); fragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE); ft.commit(); } } 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(); } } private void callLogoutAPI() { String authKey = PrefHelper.getString(getResources().getString(R.string.prefAuthKey), ""); restClient.setupRestClient(this, authKey); Call<Logout> objectCall = RestClient.getApiClient().logout(); this.restClient.makeApiRequest(this, objectCall, this, this.getResources().getInteger(R.integer.reqCodeLogout), true); } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { super.onApiResponse(call, response, reqCode); try { if (reqCode == getResources().getInteger(R.integer.reqCodeLogout)) { if (response != null) { Logout logout = (Logout) response.body(); // PrefHelper.setBoolean(Constants.IS_FROM_LOGOUT, false); if (!logout.isError()) { PrefHelper.setBoolean(Constants.IS_LOGIN, false); PrefHelper.setString(Constants.FCM_TOKEN, ""); int userId = PrefHelper.getInt(Constants.USER_ID, 0); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { try { FirebaseInstanceId.getInstance().deleteInstanceId(); } catch (IOException e) { e.printStackTrace(); } } }); PrefHelper.setInt(Constants.USER_ID, 0); PrefHelper.setString(getString(R.string.prefAuthKey), ""); PrefHelper.setInt(Constants.USER_ROLE_ID, 0); String authKey = PrefHelper.getString(getResources().getString(R.string.prefAuthKey), ""); restClient.setupRestClient(this, authKey);// Toast.makeText(this, "Logout Successfully", Toast.LENGTH_LONG).show(); Intent intent = new Intent(this, RequestVarificationActivity.class); startActivity(intent); finish(); } else { CustomDialog.getInstance().showMessageDialog(this, getResources().getString(R.string.something_went_wrong_please_try_again)); } } } } catch (Exception e) { e.printStackTrace();// Toast.makeText(this, getResources().getString(R.string.fail_to_logout), Toast.LENGTH_LONG).show(); } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { super.onApiError(call, object, reqCode); Log.e("", ""); } @Override public void onBackPressed() { showMessageDialog(this, getResources().getString(R.string.do_you_want_to_exit)); } //Show Logout alert dialog public void showLogoutAlert() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.logout_title)); builder.setCancelable(true); builder.setMessage(getString(R.string.msgLogoutAlert)); builder.setPositiveButton(getString(R.string.btnYes), (dialog, id) -> { dialog.dismiss(); callLogoutAPI(); }); builder.setNegativeButton(getString(R.string.btnNo), (dialog, id) -> dialog.dismiss()); // create alert dialog AlertDialog alertDialog = builder.create(); // show it alertDialog.show(); } public void showMessageDialog(final Context context, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(false); builder.setMessage(message); builder.setPositiveButton(context.getString(R.string.btnOk), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } }); builder.setNegativeButton(context.getString(R.string.btnCancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } public void setMenuSelected(int menuItemId) { MenuItem menuItem = mBinding.bottomNavigation.getMenu().getItem(menuItemId); menuItem.setChecked(true); } @Override public void onUpdateMenu(int menuItemId) { Log.e("menuItemID", "menuItemID:::" + menuItemId); setMenuSelected(menuItemId); } }21)TransferFragment.java
=============================
package com.webinfinium.vmukti.fragment;import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.databinding.DataBindingUtil;import android.os.Bundle;import android.support.annotation.NonNull;import android.support.annotation.Nullable;import android.support.v4.app.Fragment;import android.support.v7.widget.LinearLayoutManager;import android.support.v7.widget.SearchView;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup; import com.webinfinium.vmukti.R;import com.webinfinium.vmukti.activity.NotificationActivity;import com.webinfinium.vmukti.adapter.TransferAdapter;import com.webinfinium.vmukti.api.RestClient;import com.webinfinium.vmukti.databinding.FragmentTransferBinding;import com.webinfinium.vmukti.interfaces.OnUpdateMenuListner;import com.webinfinium.vmukti.interfaces.SelectedItemListner;import com.webinfinium.vmukti.models.InventoryResponse;import com.webinfinium.vmukti.models.Product;import com.webinfinium.vmukti.models.WareHouse;import com.webinfinium.vmukti.utility.Constants;import com.webinfinium.vmukti.utility.CustomDialog;import com.webinfinium.vmukti.utility.PrefHelper;import com.webinfinium.vmukti.utility.ToastHelper;import com.webinfinium.vmukti.utility.Utils; import java.util.ArrayList;import java.util.HashMap;import java.util.List; import okhttp3.MediaType;import okhttp3.RequestBody;import retrofit2.Call;import retrofit2.Response; public class TransferFragment extends BaseFragment implements View.OnClickListener, SelectedItemListner { FragmentTransferBinding mBinding; boolean isLoading; ArrayList<Product> alstSelectedItem = new ArrayList<>(); OnUpdateMenuListner onUpdateMenuListner; private ArrayList<String> alstWareHouseName = new ArrayList<>(); private ArrayList<Integer> alstWareHouseId = new ArrayList<>(); private int selectedUserId = 0; TransferAdapter adapter; @Override public void onAttach(Context context) { super.onAttach(context); try { onUpdateMenuListner = (OnUpdateMenuListner) getActivity(); } catch (ClassCastException e) { } } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getArguments(); if (bundle != null && (ArrayList<Product>) bundle.getSerializable(Constants.SELECTED_LIST) != null) { // selectedUserId = bundle.getInt(Constants.SELECTED_USER_ID); alstSelectedItem = (ArrayList<Product>) getArguments().getSerializable(Constants.SELECTED_LIST); } apiCallWareHouse(); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_transfer, container, false); View view = mBinding.getRoot(); mBinding.lytTransfer.setOnClickListener(this); mBinding.toolbar.toolbarTitle.setText(getResources().getString(R.string.transfer)); mBinding.toolbar.imgBack.setVisibility(View.VISIBLE); mBinding.toolbar.imgBack.setOnClickListener(this); mBinding.toolbar.imgNotification.setVisibility(View.VISIBLE); mBinding.toolbar.imgNotification.setOnClickListener(this); initNSetRecyclerViewEvents(); mBinding.searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { adapter.getFilter().filter(newText); return false; } }); return view; } public static TransferFragment newInstance() { return new TransferFragment(); } private void initNSetRecyclerViewEvents() { mBinding.recyclerView.setHasFixedSize(true); final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false); mBinding.recyclerView.setLayoutManager(layoutManager); } @Override public void onApiResponse(Call<Object> call, Response<Object> response, int reqCode) { if (reqCode == getResources().getInteger(R.integer.reqCodeSubmitInventory)) { mBinding.lytLoader.setVisibility(View.GONE); mBinding.avi.hide(); if (response != null) { InventoryResponse inventoryResponse = (InventoryResponse) response.body(); if (!inventoryResponse.isError()) { // CustomDialog.getInstance().showMessageDialog(getActivity(), inventoryResponse.getMessage()); showMessageDialog(getActivity(),inventoryResponse.getMessage()); } } } else if (reqCode == getResources().getInteger(R.integer.reqCodeWarehouse)) { ArrayList<WareHouse> alstWareHouse = (ArrayList<WareHouse>) response.body(); alstWareHouseName.add(getResources().getString(R.string.select_warehouse)); alstWareHouseId.add(0); for (int i = 0; i < alstWareHouse.size(); i++) { alstWareHouseName.add(alstWareHouse.get(i).getName()); alstWareHouseId.add(alstWareHouse.get(i).getId()); } if (alstSelectedItem != null && alstSelectedItem.size() > 0) { bindRecyclerView(alstSelectedItem, alstWareHouseId, alstWareHouseName); } } } @Override public void onApiError(Call<Object> call, Object object, int reqCode) { isLoading = false; mBinding.lytLoader.setVisibility(View.GONE); mBinding.avi.hide(); ToastHelper.getInstance().showToast(getActivity(), object.toString()); } private void bindRecyclerView(ArrayList<Product> listSearch, ArrayList<Integer> alstWarehouseId, ArrayList<String> alstWarehouseName) { if (listSearch != null && listSearch.size() > 0) { /*if(searchStr!=null && searchStr.length()>0 && pageNoSearch==1) recyclerViewInviteSpot.setAdapter(null);*/ mBinding.recyclerView.setVisibility(View.VISIBLE); mBinding.lytNoData.setVisibility(View.GONE); adapter = (TransferAdapter) mBinding.recyclerView.getAdapter(); if (adapter != null && adapter.getItemCount() > 0) { adapter.setListItems(listSearch); /*if(isAllRecordsLoaded) adapter.notifyItemRemoved(listAppUsers.size());*/ } else { adapter = new TransferAdapter(getActivity(), listSearch, alstWarehouseId, alstWarehouseName);//totalCount, adapter.setAdapterCallBack(this); mBinding.recyclerView.setAdapter(adapter); } } else { mBinding.recyclerView.setVisibility(View.GONE); mBinding.lytNoData.setVisibility(View.VISIBLE); } } public void apiCallSubmitInventory(boolean resetVariables, boolean showDialog, HashMap<String, RequestBody> request) { if (Utils.getInstance().checkInternetConnection(getActivity())) { mBinding.lytLoader.setVisibility(View.VISIBLE); mBinding.avi.show(); Call<InventoryResponse> objectCall = RestClient.getApiClient().submitInventory(request); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, this.getResources().getInteger(R.integer.reqCodeSubmitInventory), true); } else { CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getString(R.string.msgInternetConnectionNotAvailable)); } } public void apiCallWareHouse() { if (Utils.getInstance().checkInternetConnection(getActivity())) { // mBinding.lytLoader.setVisibility(View.VISIBLE);// mBinding.avi.show(); Call<List<WareHouse>> objectCall = RestClient.getApiClient().warehouse(); homeActivity.restClient.makeApiRequest(getActivity(), objectCall, this, getActivity().getResources().getInteger(R.integer.reqCodeWarehouse), false); } else { CustomDialog.getInstance().showMessageDialog(getActivity(), getActivity().getString(R.string.msgInternetConnectionNotAvailable)); } } @Override public void onBackPressed() { homeActivity.popFragment(); } @Override public void onClick(View v) { if (v == mBinding.lytTransfer) { selectedUserId = PrefHelper.getInt(Constants.SELECTED_USER_ID, 0); if (fieldValidation(alstSelectedItem)) { HashMap<String, RequestBody> hashMap = new HashMap<>(); hashMap.put("user_id", RequestBody.create(MediaType.parse("text/plain"), String.valueOf(selectedUserId))); for (int i = 0; i < alstSelectedItem.size(); i++) { hashMap.put("InventoryTransaction[" + i + "][to_warehouse_id]", RequestBody.create(MediaType.parse("text/plain"), String.valueOf(alstSelectedItem.get(i).getWarehouse_id()))); hashMap.put("InventoryTransaction[" + i + "][product_id]", RequestBody.create(MediaType.parse("text/plain"), String.valueOf(alstSelectedItem.get(i).getProductId()))); hashMap.put("InventoryTransaction[" + i + "][serial_no]", RequestBody.create(MediaType.parse("text/plain"), String.valueOf(alstSelectedItem.get(i).getSerialNo()))); hashMap.put("InventoryTransaction[" + i + "][qty]", RequestBody.create(MediaType.parse("text/plain"), String.valueOf(alstSelectedItem.get(i).getTempQty()))); hashMap.put("InventoryTransaction[" + i + "][is_bundle]", RequestBody.create(MediaType.parse("text/plain"), String.valueOf(alstSelectedItem.get(i).isBundle()))); hashMap.put("InventoryTransaction[" + i + "][has_serial_no]", RequestBody.create(MediaType.parse("text/plain"), String.valueOf(alstSelectedItem.get(i).hasSerialNo()))); } Log.e("", "" + hashMap); apiCallSubmitInventory(false, false, hashMap); } } else if (v == mBinding.toolbar.imgBack) { homeActivity.popFragment(); } else if (v == mBinding.toolbar.imgNotification) { Intent mIntent = new Intent(getActivity(), NotificationActivity.class); startActivity(mIntent); } } public boolean fieldValidation(ArrayList<Product> alstSelectedItem) { boolean flag = true; if (selectedUserId == 0) { flag = false; CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.please_select_a_user)); } else { for (int i = 0; i < alstSelectedItem.size(); i++) { if (alstSelectedItem.get(i).getWarehouse_id() == 0) { flag = false; CustomDialog.getInstance().showMessageDialog(getActivity(), getResources().getString(R.string.please_select_warehouse_of) + " " + alstSelectedItem.get(i).getProductName().toLowerCase()); break; } } } return flag; } @Override public void onSelection(Product product) { int pos = alstSelectedItem.indexOf(product); alstSelectedItem.set(pos, product); } @Override public void onQtyUpdate(Product product) { } public void showMessageDialog(final Context context, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(false); builder.setMessage(message); builder.setPositiveButton(context.getString(R.string.btnOk), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (onUpdateMenuListner != null) { onUpdateMenuListner.onUpdateMenu(0); } Fragment myFragment = HomeFragment.newInstance(); homeActivity.pushFragments(myFragment, false, false, true); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } }22)TransferAdapter .java
=========================
package com.webinfinium.vmukti.adapter;import android.app.Activity;import android.content.Context;import android.databinding.DataBindingUtil;import android.support.v7.widget.RecyclerView;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.Filter;import android.widget.Filterable;import android.widget.LinearLayout;import android.widget.Spinner;import android.widget.TextView; import com.webinfinium.vmukti.R;import com.webinfinium.vmukti.databinding.ItemTransferBinding;import com.webinfinium.vmukti.interfaces.SelectedItemListner;import com.webinfinium.vmukti.models.Product;import com.webinfinium.vmukti.utility.Constants;import com.webinfinium.vmukti.utility.Utils; import java.util.ArrayList;import java.util.List; public class TransferAdapter extends RecyclerView.Adapter<TransferAdapter.CustomViewHolder> implements Filterable { Activity mContext; int totalCount = 0; private ArrayList<Product> alstProduct; private int lastCheckedPosition = -1; private ArrayAdapter<String> aadpTeam = null; private ArrayList<String> alstWarehouseName; ArrayList<Integer> alstWarehouseId; private SelectedItemListner mCallback; List<Product> mFilterList; ValueFilter valueFilter; public TransferAdapter(Activity mContext, ArrayList<Product> alstProduct, ArrayList<Integer> alstWarehouseId, ArrayList<String> alstWarehouseName) { this.mContext = mContext; this.alstProduct = alstProduct; this.alstWarehouseName = alstWarehouseName; this.alstWarehouseId = alstWarehouseId; this.mFilterList = alstProduct; } public void setListItems(ArrayList<Product> listSearchSpot) { this.alstProduct = listSearchSpot; notifyDataSetChanged(); } public void setAdapterCallBack(SelectedItemListner callBack) { this.mCallback = callBack; } @Override public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = null; CustomViewHolder viewHolder = null; switch (viewType) { case Constants.TYPE_ITEM: view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_transfer, parent, false); viewHolder = new CustomViewHolder(view); break; case Constants.TYPE_FOOTER: view = LayoutInflater.from(parent.getContext()).inflate(R.layout.load_more_layout, parent, false); viewHolder = new CustomViewHolder(view); break; } return viewHolder; } @Override public void onBindViewHolder(CustomViewHolder holder, final int position) { if (getItemViewType(position) == Constants.TYPE_ITEM) { holder.mBinding.txtProductName.setText(alstProduct.get(position).getProductName()); if (Utils.validateString(alstProduct.get(position).getSerialNo())) { holder.mBinding.txtSerialNo.setVisibility(View.VISIBLE); holder.mBinding.txtSerialNo.setText(String.valueOf(alstProduct.get(position).getSerialNo())); } else { holder.mBinding.txtSerialNo.setVisibility(View.GONE); } holder.mBinding.spnWarehouse.setSelection(alstProduct.get(position).getSppinerPosition()); fillSpinner(alstWarehouseName, holder.mBinding.spnWarehouse); if (alstProduct.get(position).getWarehouse_id() > 0) { holder.mBinding.spnWarehouse.setSelection(alstProduct.get(position).getSppinerPosition()); } holder.mBinding.spnWarehouse.setTag(position); holder.mBinding.spnWarehouse.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { if (holder.mBinding.spnWarehouse.getSelectedItemPosition() < 0) { } else { Product product = alstProduct.get(position); if (product != null) { int warehouseId = alstWarehouseId.get(pos); if (warehouseId > 0) { product.setWarehouse_id(warehouseId); product.setSppinerPosition(pos); alstProduct.set(position, product); mCallback.onSelection(product);// notifyDataSetChanged(); } } } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); holder.mBinding.txtQty.setText(String.valueOf(alstProduct.get(position).getTempQty())); // holder.mBinding.spnWarehouse.setTag(alstProduct.get(position));// holder.mBinding.spnWarehouse.setOnClickListener(new View.OnClickListener() {// @Override// public void onClick(View v) {// Product product = (Product) v.getTag();// ArrayList<String> alstWarehouse = new ArrayList<>();// alstWarehouse.addAll(alstWarehouseName);// fillSpinner(alstWarehouse, holder.mBinding.spnWarehouse);//// }// }); holder.mBinding.imgDelete.setTag(alstProduct.get(position)); holder.mBinding.imgDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Product product = (Product) v.getTag(); int pos = alstProduct.indexOf(product); alstProduct.remove(pos); notifyDataSetChanged(); } }); } } public void fillSpinner(ArrayList<String> alstWarehouseName, Spinner spinner) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); aadpTeam = new ArrayAdapter<String>(mContext, R.layout.spinner_item, alstWarehouseName) { @Override public View getView(int position, View convertView, ViewGroup parent) { convertView = inflater.inflate(R.layout.spinner_bg, null); TextView textView = (TextView) convertView.findViewById(R.id.spinnerItem); textView.setText(alstWarehouseName.get(position)); return convertView; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { convertView = inflater.inflate(R.layout.spinner_item, null); TextView textView = (TextView) convertView.findViewById(R.id.txtItem); textView.setText(alstWarehouseName.get(position).toString()); return convertView; } }; spinner.setAdapter(aadpTeam); } @Override public int getItemCount() { return alstProduct.size(); } @Override public int getItemViewType(int position) { // if ((totalCount) > position && position == alstProduct.size()) {// return Constants.TYPE_FOOTER;// } else { return Constants.TYPE_ITEM;// } } @Override public Filter getFilter() { if (valueFilter == null) { valueFilter = new ValueFilter(); } return valueFilter; } private class ValueFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults results = new FilterResults(); if (constraint != null && constraint.length() > 0) { List<Product> filterList = new ArrayList<>(); for (int i = 0; i < mFilterList.size(); i++) { if ((mFilterList.get(i).getProductName().toUpperCase()).contains(constraint.toString().toUpperCase())) { filterList.add(mFilterList.get(i)); } } results.count = filterList.size(); results.values = filterList; } else { results.count = mFilterList.size(); results.values = mFilterList; } return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { alstProduct = (ArrayList<Product>) results.values; notifyDataSetChanged(); } } public class CustomViewHolder extends RecyclerView.ViewHolder { ItemTransferBinding mBinding; public CustomViewHolder(View itemView) { super(itemView); mBinding = DataBindingUtil.bind(itemView); } } class FooterHolder extends RecyclerView.ViewHolder { LinearLayout rlLoadMore; public FooterHolder(View itemView) { super(itemView); rlLoadMore = (LinearLayout) itemView.findViewById(R.id.load_more_rl); } } }20) MapFragment.java===================package com.piitch.fragments; import android.databinding.DataBindingUtil; import android.graphics.Point; import android.graphics.drawable.GradientDrawable; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; 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.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.piitch.R; import com.piitch.databinding.FragmentMapBinding; import com.piitch.utility.Constants; import com.piitch.utility.PrefHelper; import com.piitch.utility.Utils; public class MapFragment extends BaseFragment implements OnMapReadyCallback, View.OnClickListener { private GoogleMap googleMap; double latitude = 0.0, longitude = 0.0; String location = ""; private String start_color, end_color; FragmentMapBinding mBinding; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_map, container, false); View view = mBinding.getRoot(); return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); start_color = PrefHelper.getString(Constants.START_COLOR, ""); end_color = PrefHelper.getString(Constants.END_COLOR, ""); GradientDrawable gradientDrawable = Utils.getInstance().createGradientDrawable(start_color, end_color); mBinding.fragMapLytToolbar.setBackground(gradientDrawable); mBinding.fragMapImgBack.setOnClickListener(this); initMap(); } private void initMap() { try { if (googleMap != null) { drawMarkerOnMap(); } 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(MapFragment.this); } } }, 400); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onMapReady(GoogleMap googleMap) { this.googleMap = googleMap; drawMarkerOnMap(); } private void drawMarkerOnMap() { try { latitude = 0.0; longitude = 0.0; if (Utils.validateString(PrefHelper.getString(Constants.LOCATION, ""))) { location = PrefHelper.getString(Constants.LOCATION, ""); } if (Utils.validateString(PrefHelper.getString(Constants.LATITUDE, ""))) { latitude = Double.parseDouble(PrefHelper.getString(Constants.LATITUDE, "0.0")); } if (Utils.validateString(PrefHelper.getString(Constants.LONGITUDE, ""))) { longitude = Double.parseDouble(PrefHelper.getString(Constants.LONGITUDE, "0.0")); } LatLng latLng = new LatLng(latitude, longitude); googleMap.clear(); googleMap.addMarker(new MarkerOptions() .position(latLng) .icon(BitmapDescriptorFactory.fromResource(R.mipmap.icn_get_direction)) // Specifies the anchor to be at a particular point in the marker image. .anchor(0.5f, 1)); googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 12.0f)); // changeOffsetCenter(latitude, longitude);// googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {// @Override// public boolean onMarkerClick(Marker marker) {// homeActivity.pushFragments(mMapFragment, true, true, false);// return true;// }// }); } catch (Exception e) { e.printStackTrace(); } } public void changeOffsetCenter(double latitude,double longitude) { Point mappoint = googleMap.getProjection().toScreenLocation(new LatLng(latitude, longitude)); mappoint.set(mappoint.x, mappoint.y-100); // change these values as you need , just hard coded a value if you want you can give it based on a ratio like using DisplayMetrics as well googleMap.animateCamera(CameraUpdateFactory.newLatLng(googleMap.getProjection().fromScreenLocation(mappoint))); } // public void changeOffsetCenter(double latitude, double longitude) {// Point mappoint = googleMap.getProjection().toScreenLocation(new LatLng(latitude, longitude));// mappoint.set(mappoint.x, mappoint.y - 100); // change these values as you need , just hard coded a value if you want you can give it based on a ratio like using DisplayMetrics as well// googleMap.animateCamera(CameraUpdateFactory.newLatLng(googleMap.getProjection().fromScreenLocation(mappoint)));// } @Override public void onClick(View v) { if (v == mBinding.fragMapImgBack) { getActivity().onBackPressed(); } } }
No comments:
Post a Comment