Skip to content

Instantly share code, notes, and snippets.

@ebnrdwan
Created May 1, 2018 13:34
Show Gist options
  • Save ebnrdwan/f04ef0fdaae19e8e3a03a8f6ede16645 to your computer and use it in GitHub Desktop.
Save ebnrdwan/f04ef0fdaae19e8e3a03a8f6ede16645 to your computer and use it in GitHub Desktop.
package ebnrdwan.app.android.BaghdadOfficer.AddRequestOfficer;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
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.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.airbnb.lottie.LottieAnimationView;
import com.flipboard.bottomsheet.BottomSheetLayout;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
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.places.Place;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.jota.autocompletelocation.AutoCompleteLocation;
import com.nguyenhoanglam.imagepicker.model.Config;
import com.nguyenhoanglam.imagepicker.model.Image;
import com.nguyenhoanglam.imagepicker.ui.imagepicker.ImagePicker;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import ebnrdwan.app.android.BaghdadOfficer.AccountSessions.welcom.Splash;
import ebnrdwan.app.android.BaghdadOfficer.MainScreen.MainScreen;
import ebnrdwan.app.android.BaghdadOfficer.OfficerUpdateLocation.AddRoadRequestModel;
import ebnrdwan.app.android.BaghdadOfficer.OfficerUpdateLocation.EditTaskAdapter;
import ebnrdwan.app.android.BaghdadOfficer.OfficerUpdateLocation.GetEmployee;
import ebnrdwan.app.android.BaghdadOfficer.OrderFollowUp.OrderFollowUpActivity;
import ebnrdwan.app.android.BaghdadOfficer.OrderFollowUp.SupportSpinnerAdapter;
import ebnrdwan.app.android.BaghdadOfficer.R;
import ebnrdwan.app.android.BaghdadOfficer.Reprository.Models.BaseResponse;
import ebnrdwan.app.android.BaghdadOfficer.Reprository.Models.RoadServiceModel;
import ebnrdwan.app.android.BaghdadOfficer.Reprository.RetroUtilies.ApiClient;
import ebnrdwan.app.android.BaghdadOfficer.Reprository.RetroUtilies.RetroApiInterface;
import ebnrdwan.app.android.BaghdadOfficer.Reprository.Models.ServiceModel;
import ebnrdwan.app.android.BaghdadOfficer.utility.Constants;
import ebnrdwan.app.android.BaghdadOfficer.utility.GPSTracker;
import ebnrdwan.app.android.BaghdadOfficer.utility.GeneralUtilities;
import ebnrdwan.app.android.BaghdadOfficer.utility.ItemclickforRecycler;
import ebnrdwan.app.android.BaghdadOfficer.utility.SessionManager;
import es.dmoral.toasty.Toasty;
import io.nlopez.smartlocation.OnLocationUpdatedListener;
import io.nlopez.smartlocation.SmartLocation;
import io.nlopez.smartlocation.location.config.LocationAccuracy;
import io.nlopez.smartlocation.location.config.LocationParams;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class AddRequestOfficerActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener
, LocationListener, OnMapReadyCallback, ItemclickforRecycler.OnItemClickListener, AutoCompleteLocation.AutoCompleteLocationListener {
private static final int MY_PERMISSIONS_REQUEST_LOCATION = 100;
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 7172;
private static final long UPDATE_INTERVAL = 1000;
private static final long FATEST_INTERVAL = 100;
private static final float DISPLACEMENT = 10;
GoogleApiClient googleApiClient;
LocationRequest mLocationRequest;
Location locationService;
MapFragment mapfragment;
GoogleMap googleMap;
Dialog dialog;
Button request;
Button ok;
LatLng location;
Button cancel;
RetroApiInterface apiInterface;
RetroApiInterface apiInterfaceInterceptor;
RoadAssistAdapter assistAdapter;
ArrayList<RoadServiceModel.Services> getRoadResultList;
RecyclerView rvRoad;
private String RoadTAG = "ROADACTIVITY";
List<GetEmployee.Employees> employeesArrayList;
LottieAnimationView animationView;
EditText editTextRoadActivity;
private AutoCompleteLocation autoCompleteLocation;
private RecyclerView imagesRecyclerView;
BottomSheetLayout bottomSheet;
String myImage;
Button request_btn;
Button goRequestButton;
EditText workShopEditText;
LinearLayout upload;
int serviceId;
int supportId;
int empId;
String userName;
String userMobile;
String address;
String image;
String supportText;
double lat;
double lng;
EditText userMobileEt;
EditText userNameEt;
private Spinner spinner;
private RadioGroup radioGroupOptions;
private EditText supportDetails;
private boolean askForSupport;
ArrayList<Image> images;
private String encodedImage;
@Override
protected void onResume() {
super.onResume();
if (isLocationPermitted()) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
checkPlayServices();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_road_services2);
initializeViews();
initializeRetroCall();
apiInterfaceInterceptor = ApiClient.getRetrofitInterceptorInstance
(ApiClient.addingInterceptor(Constants.empHeader, SessionManager.getInstance().getUserData().getApi_key()))
.create(RetroApiInterface.class);
if (isLocationPermitted()) {
initializeGoogleAPiClinet();
createLocationRequest();
}
LatLng origin;
GPSTracker gpsTracker = new GPSTracker(this);
if (gpsTracker.canGetLocation()) {
} else {
gpsTracker.showSettingsAlert();
}
}
private void addNewRequest(int serviceid, int supportId, int empId, String supportText, String myImage,
String userMobile, String userName, String address, double lat, double lng) {
Call<BaseResponse> call = apiInterfaceInterceptor.addnewRequestOfficer(serviceid, supportId, empId, supportText,
userName, userMobile, address, myImage, lat, lng);
call.enqueue(new Callback<BaseResponse>() {
@Override
public void onResponse(Call<BaseResponse> call, Response<BaseResponse> response) {
Boolean error = response.body().getError();
if (error == false) {
bottomSheet.dismissSheet();
Toasty.success(AddRequestOfficerActivity.this, "requested Successfully", Toast.LENGTH_SHORT).show();
startActivity(new Intent(AddRequestOfficerActivity.this, MainScreen.class));
} else {
Toasty.error(AddRequestOfficerActivity.this, "check your network", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<BaseResponse> call, Throwable t) {
Toasty.error(AddRequestOfficerActivity.this, "check your network", Toast.LENGTH_SHORT).show();
}
});
}
// initialize your Api Component
private synchronized void initializeGoogleAPiClinet() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
//Fix first time run app if permission doesn't grant yet so can't get anything
googleApiClient.connect();
}
// Initialize Location Request
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FATEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
}
private void initializeViews() {
bottomSheet = (BottomSheetLayout) findViewById(R.id.bottomsheet);
autoCompleteLocation = (AutoCompleteLocation) findViewById(R.id.autocomplete_location);
autoCompleteLocation.setAutoCompleteTextListener(this);
rvRoad = (RecyclerView) findViewById(R.id.roadServieRecycler);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
getRoadResultList = new ArrayList<RoadServiceModel.Services>();
rvRoad.setLayoutManager(linearLayoutManager);
assistAdapter = new RoadAssistAdapter(AddRequestOfficerActivity.this, (ArrayList<RoadServiceModel.Services>) SessionManager.getInstance().getServicesList());
rvRoad.setAdapter(assistAdapter);
request = (Button) findViewById(R.id.road_request_btn);
request.setOnClickListener(this);
mapfragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFrag);
mapfragment.getMapAsync(this);
dialog = new Dialog(AddRequestOfficerActivity.this);
apiInterface = ApiClient.getApiClientInstance().create(RetroApiInterface.class);
apiInterfaceInterceptor = ApiClient.getRetrofitInterceptorInstance(ApiClient.addingInterceptor(Constants.header, SessionManager.getInstance().getUserData().getApi_key())).create(RetroApiInterface.class);
dialog.setContentView(R.layout.road_dialog);
ok = (Button) dialog.findViewById(R.id.dialog_ok);
cancel = (Button) dialog.findViewById(R.id.dialog_cancel);
animationView = (LottieAnimationView) dialog.findViewById(R.id.animation_view);
animationView.setAnimation("anims/checkb.json");
editTextRoadActivity = (EditText) dialog.findViewById(R.id.editTextRoadActivity);
ok.setOnClickListener(AddRequestOfficerActivity.this);
cancel.setOnClickListener(AddRequestOfficerActivity.this);
}
private void initializeRetroCall() {
Call<ServiceModel> call = apiInterface.getServiceLockup();
call.enqueue(new Callback<ServiceModel>() {
@Override
public void onResponse(Call<ServiceModel> call, Response<ServiceModel> response) {
if (!response.body().getError()) {
SessionManager.getInstance().saveServiceList(response.body().getServiceModel());
for (int i = 0; i < response.body().getServiceModel().size(); i++) {
Boolean error = response.body().getError();
if (error == false) {
getRoadResultList.add(response.body().getServiceModel().get(i));
} else {
Toast.makeText(AddRequestOfficerActivity.this, "can't load services error", Toast.LENGTH_SHORT).show();
}
}
if (getRoadResultList.size() > 0) {
assistAdapter = new RoadAssistAdapter(AddRequestOfficerActivity.this, getRoadResultList);
rvRoad.setAdapter(assistAdapter);
}
}
}
@Override
public void onFailure(Call<ServiceModel> call, Throwable t) {
Log.d(RoadTAG, t.toString());
Toast.makeText(AddRequestOfficerActivity.this, "can't load services error" + t.toString(), Toast.LENGTH_SHORT).show();
}
});
}
private boolean isLocationPermitted() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(this)
.setTitle(R.string.alertTitle)
.setMessage(R.string.alertMessage)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(AddRequestOfficerActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create().show();
} else {
ActivityCompat.requestPermissions(AddRequestOfficerActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(), "This device is not supported", Toast.LENGTH_LONG).show();
finish();
}
return false;
}
return true;
}
private void flyTo(GoogleMap map, CameraPosition position, int milliSeconds) {
map.animateCamera(CameraUpdateFactory.newCameraPosition(position), milliSeconds, null);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (isLocationPermitted()) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION:
if (googleApiClient == null) {
initializeGoogleAPiClinet();
if (!googleApiClient.isConnected()) googleApiClient.connect();
}
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
//Request location updates:
if (!googleApiClient.isConnected()) googleApiClient.connect();
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, this);
//Request location updates:
}
}
}
}
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.road_request_btn:
bottomSheet.showWithSheetView(LayoutInflater.from(AddRequestOfficerActivity.this).inflate(R.layout.new_request_sheet_layout, bottomSheet, false));
goRequestButton = (Button) bottomSheet.findViewById(R.id.request_care);
userMobileEt = bottomSheet.findViewById(R.id.tv_user_mobile);
userNameEt = bottomSheet.findViewById(R.id.tv_user_name);
spinner = bottomSheet.findViewById(R.id.spinner_support);
supportDetails = bottomSheet.findViewById(R.id.tv_sub_details);
radioGroupOptions = bottomSheet.findViewById(R.id.radio_group);
radioGroupOptions.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (i) {
case R.id.radio_comp:
askForSupport = false;
spinner.setVisibility(View.GONE);
supportDetails.setVisibility(View.GONE);
break;
case R.id.radio_support:
askForSupport = true;
spinner.setVisibility(View.VISIBLE);
supportDetails.setVisibility(View.VISIBLE);
break;
}
}
});
final SupportSpinnerAdapter adapter = new SupportSpinnerAdapter(this, android.R.layout.simple_spinner_dropdown_item,
SessionManager.getInstance().getSupportList());
upload = bottomSheet.findViewById(R.id.upload_view);
upload.setOnClickListener(this);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
supportDetails.setVisibility(View.VISIBLE);
supportId = adapter.getItem(i).getId();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
supportDetails.setVisibility(View.GONE);
}
});
goRequestButton.setOnClickListener(this);
imagesRecyclerView = findViewById(R.id.recycler_image);
upload = (LinearLayout) bottomSheet.findViewById(R.id.upload_view);
upload.setOnClickListener(this);
break;
case R.id.upload_view:
picImages();
break;
case R.id.request_care:
if (images!=null&&images.size()>0){
Bitmap bm = BitmapFactory.decodeFile(images.get(0).getPath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
}else {
encodedImage="ssdaf";
}
if (location != null) {
if (TextUtils.isEmpty(userMobileEt.getText().toString())|| TextUtils.isEmpty(userNameEt.getText().toString())){
Toasty.error(AddRequestOfficerActivity.this, "please insert all data", Toast.LENGTH_SHORT).show();
}
else {
addNewRequest(serviceId, supportId, SessionManager.getInstance().getUserData().getId(), supportText, encodedImage, userMobileEt.getText().toString(),
userNameEt.getText().toString(),
GeneralUtilities.getCompleteAddressString(AddRequestOfficerActivity.this, location.latitude, location.longitude),
location.latitude, location.longitude);
}
} else {
Toasty.error(AddRequestOfficerActivity.this, "Can't Get Your Location", Toast.LENGTH_SHORT).show();
}
break;
case R.id.dialog_cancel:
dialog.dismiss();
break;
case R.id.dialog_ok:
addNewRequest(serviceId, supportId, empId, supportText, image, userMobile, userName, address, lat, lng);
break;
}
}
public void picImages() {
ArrayList<Image> images = new ArrayList<>();
ImagePicker.with(this) // Initialize ImagePicker with activity or fragment context
.setToolbarColor("#212121") // Toolbar color
.setStatusBarColor("#000000") // StatusBar color (works with SDK >= 21 )
.setToolbarTextColor("#FFFFFF") // Toolbar text color (Title and Done button)
.setToolbarIconColor("#FFFFFF") // Toolbar icon color (Back and Camera button)
.setProgressBarColor("#4CAF50") // ProgressBar color
.setBackgroundColor("#212121") // Background color
.setCameraOnly(false) // Camera mode
.setMultipleMode(true) // Select multiple images or single image
.setFolderMode(false) // Folder mode
.setShowCamera(true) // Show camera button
.setFolderTitle("Albums") // Folder title (works with FolderMode = true)
.setImageTitle("Galleries") // Image title (works with FolderMode = false)
.setDoneTitle("Done") // Done button title
.setLimitMessage("You have reached selection limit") // Selection limit message
.setMaxSize(4) // Max images can be selected
.setSavePath("ImagePicker") // Image capture folder name
.setSelectedImages(images) // Selected images
.setKeepScreenOn(true) // Keep screen on when selecting images
.start();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Config.RC_PICK_IMAGES && resultCode == RESULT_OK && data != null) {
images = data.getParcelableArrayListExtra(Config.EXTRA_IMAGES);
EditTaskAdapter adapter = new EditTaskAdapter(this, images);
imagesRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
imagesRecyclerView.setAdapter(adapter);
}
super.onActivityResult(requestCode, resultCode, data); // THIS METHOD SHOULD BE HERE so that ImagePicker works with fragment
}
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationService = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (locationService != null) {
location = new LatLng(locationService.getLatitude(), locationService.getLongitude());
CameraPosition currentLocation = CameraPosition.builder().target(location).zoom(15).tilt(30.4f).build();
googleMap.setMyLocationEnabled(true);
flyTo(googleMap, currentLocation, 1000);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
}
@Override
protected void onStop() {
super.onStop();
if (googleApiClient.isConnected())
googleApiClient.disconnect();
}
@Override
protected void onStart() {
super.onStart();
}
@Override
public void onMapReady(GoogleMap googleMap) {
this.googleMap = googleMap;
}
@Override
public void onItemClicked(RecyclerView recyclerView, int position, View v) {
serviceId = getRoadResultList.get(position).getId();
}
@Override
public void onTextClear() {
}
@Override
public void onItemSelected(Place selectedPlace) {
CameraPosition currentLocation = CameraPosition.builder().target(selectedPlace.getLatLng()).zoom(15).tilt(30.4f).build();
flyTo(googleMap, currentLocation, 1000);
googleMap.addMarker(new MarkerOptions().position(selectedPlace.getLatLng()).draggable(true));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment