Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.dss.invitup.vc.homePage;
- import android.Manifest;
- import android.content.ActivityNotFoundException;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.content.Intent;
- import android.content.pm.PackageManager;
- import android.graphics.Bitmap;
- import android.graphics.Typeface;
- import android.net.Uri;
- import android.os.Build;
- import android.os.Bundle;
- import android.os.Environment;
- import android.provider.MediaStore;
- import android.support.v4.app.ActivityCompat;
- import android.support.v4.app.Fragment;
- import android.support.v7.app.AlertDialog;
- import android.util.Log;
- import android.view.LayoutInflater;
- import android.view.MotionEvent;
- import android.view.View;
- import android.view.ViewGroup;
- import android.view.inputmethod.InputMethodManager;
- import android.widget.Button;
- import android.widget.ImageButton;
- import android.widget.LinearLayout;
- import android.widget.Toast;
- import com.bumptech.glide.Glide;
- import com.bumptech.glide.load.resource.drawable.GlideDrawable;
- import com.bumptech.glide.request.RequestListener;
- import com.bumptech.glide.request.target.Target;
- import com.dss.invitup.R;
- import com.dss.invitup.events.AddPicturePermissionEvent;
- import com.dss.invitup.events.GetUpdateUserFinishedEvent;
- import com.dss.invitup.events.HomePageBackButtonTapped;
- import com.dss.invitup.events.SignOutFinishedEvent;
- import com.dss.invitup.models.User;
- import com.dss.invitup.singleton.InterfaceManager;
- import com.dss.invitup.singleton.ServerManager;
- import com.dss.invitup.singleton.SettingsManager;
- import com.dss.invitup.singleton.UploadManager;
- import com.dss.invitup.vc.login.LoginMainPageActivity;
- import com.dss.invitup.view.RobotoBoldTextView;
- import com.dss.invitup.view.RobotoLightEditText;
- import com.dss.invitup.view.RobotoLightTextView;
- import com.facebook.login.LoginManager;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import de.greenrobot.event.EventBus;
- import de.hdodenhof.circleimageview.CircleImageView;
- import static android.app.Activity.RESULT_OK;
- /**
- * Copyright © 2016 Dihardja Software Solutions. All rights reserved.
- */
- public class ProfileFragment extends Fragment{
- ImageButton backButton;
- Button logoutButton;
- CircleImageView profilePicture, profilePictureLoading;
- RobotoLightTextView profileEmail;
- RobotoLightEditText profileName;
- RobotoBoldTextView profileHostingCount, profileAttendingCount;
- String imageUrlFromS3;
- static final int CAMERA_PHOTO = 0;
- static final int GALLERY_PHOTO = 1;
- static final int REMOVE_PHOTO = 2;
- File photoFile = null;
- File croppedPhotoFile = null;
- String mCurrentPhotoPath;
- Uri attachmentUri;
- LinearLayout profileFragmentLinearLayout;
- InputMethodManager inputMethodManager;
- User user;
- boolean isEligibleToTakePicture = false;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.fragment_profile, container, false);
- backButton = (ImageButton)view.findViewById(R.id.profileFragment_backButton);
- logoutButton = (Button) view.findViewById(R.id.profileFragment_logoutButton);
- profilePicture = (CircleImageView) view.findViewById(R.id.profileFragment_profilePicture);
- profilePictureLoading = (CircleImageView) view.findViewById(R.id.profileFragment_profilePictureLoading);
- profileName = (RobotoLightEditText) view.findViewById(R.id.profileFragment_profileName);
- profileEmail = (RobotoLightTextView) view.findViewById(R.id.profileFragment_profileEmail);
- profileHostingCount = (RobotoBoldTextView) view.findViewById(R.id.profileFragment_hostingCount);
- profileAttendingCount = (RobotoBoldTextView) view.findViewById(R.id.profileFragment_attendingCount);
- profileFragmentLinearLayout = (LinearLayout) view.findViewById(R.id.profileFragmentLinearLayout);
- inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
- return view;
- }
- @Override
- public void onViewCreated(View view, Bundle savedInstanceState) {
- super.onViewCreated(view, savedInstanceState);
- if(!EventBus.getDefault().isRegistered(this)){
- EventBus.getDefault().register(this);
- }
- if(SettingsManager.getInstance().getCurrentUser()!=null){
- user = SettingsManager.getInstance().getCurrentUser();
- }
- profileFragmentLinearLayout.setOnTouchListener(new View.OnTouchListener() {
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- profileName.clearFocus();
- inputMethodManager.hideSoftInputFromWindow(profileFragmentLinearLayout.getWindowToken(), 0);
- return false;
- }
- });
- String firstName = "";
- String lastName = "";
- if(user.getFirstName()!= null){
- if(!user.getFirstName().equals("")){
- firstName = InterfaceManager.sharedInstance().getFirstLetterCapitalized(user.getFirstName());
- }
- }
- if(user.getLastName()!= null){
- if(!user.getLastName().equals("")){
- lastName = " " + InterfaceManager.sharedInstance().getFirstLetterCapitalized(user.getLastName());
- }
- }
- profileName.setText(firstName + lastName);
- String email = "";
- if(user.getEmail()!=null){
- email = user.getEmail();
- }
- profileEmail.setText(email);
- int attendingCount = 0;
- int hostingCount = 0;
- if(SettingsManager.getInstance().getCurrentUserOccasionResponse()!=null) {
- if (SettingsManager.getInstance().getCurrentUserOccasionResponse().getJoinedOccasions().size() != 0) {
- attendingCount = SettingsManager.getInstance().getCurrentUserOccasionResponse().getJoinedOccasions().size();
- }
- if (SettingsManager.getInstance().getCurrentUserOccasionResponse().getManagedOccasions().size() != 0) {
- hostingCount = SettingsManager.getInstance().getCurrentUserOccasionResponse().getManagedOccasions().size();
- }
- }
- profileHostingCount.setText(String.valueOf(hostingCount));
- profileAttendingCount.setText(String.valueOf(attendingCount));
- Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Light.otf");
- logoutButton.setTypeface(font);
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- logoutButton.setLetterSpacing(0.07f);
- }
- profilePicture.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.profile));
- if(user.getImageURL()!=null){
- if(!user.getImageURL().equals("")){
- imageUrlFromS3 = user.getImageURL();
- profilePictureLoading.setVisibility(View.VISIBLE);
- Glide.with(getActivity()).load(user.getImageURL()).listener(new RequestListener<String, GlideDrawable>() {
- @Override
- public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
- return false;
- }
- @Override
- public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
- profilePictureLoading.setVisibility(View.GONE);
- return false;
- }
- }).into(profilePicture);
- }
- }
- profileName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
- @Override
- public void onFocusChange(View v, boolean hasFocus) {
- if(!hasFocus){
- ServerManager.getInstance().updateProfile(profileName.getText().toString(), imageUrlFromS3);
- }
- }
- });
- profilePicture.setOnClickListener(profilePictureListener);
- logoutButton.setOnClickListener(logoutButtonListener);
- backButton.setOnClickListener(backButtonListener);
- }
- ImageButton.OnClickListener backButtonListener = new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- EventBus.getDefault().post(new HomePageBackButtonTapped());
- }
- };
- CircleImageView.OnClickListener profilePictureListener = new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
- final CharSequence options[] = new CharSequence[]{getActivity().getResources().getString(R.string.builder_take_picture),
- getActivity().getResources().getString(R.string.builder_choose_picture), getActivity().getResources().getString(R.string.builder_remove_picture)};
- builder.setTitle(getActivity().getResources().getString(R.string.builder_set_profile_picture));
- builder.setItems(options, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- photoFile = null;
- try{
- photoFile = createImageFile();
- }catch (IOException ex){
- Log.e("err",ex.toString());
- }
- takePhoto(which);
- }
- });
- builder.show();
- if(profileName.hasFocus()){
- profileName.clearFocus();
- inputMethodManager.hideSoftInputFromWindow(profileFragmentLinearLayout.getWindowToken(), 0);
- }
- }
- };
- Button.OnClickListener logoutButtonListener = new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- if(SettingsManager.getInstance().getCurrentUser().getLoginWithFacebook()){
- LoginManager.getInstance().logOut();
- }
- ServerManager.getInstance().logout();
- }
- };
- void takePhoto(int which){
- switch (which){
- case 0:
- if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
- if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(getActivity(),
- new String[]{Manifest.permission.CAMERA,
- Manifest.permission.WRITE_EXTERNAL_STORAGE},
- 0);
- return;
- } else {
- ActivityCompat.requestPermissions(getActivity(),
- new String[]{Manifest.permission.CAMERA},
- 0);
- return;
- }
- } else {
- if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(getActivity(),
- new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
- 0);
- return;
- }else{
- isEligibleToTakePicture = true;
- }
- }
- if(isEligibleToTakePicture){
- Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- if (photoFile != null) {
- cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
- startActivityForResult(cameraIntent, CAMERA_PHOTO);
- }
- }
- break;
- case 1:
- if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
- ActivityCompat.requestPermissions(getActivity(),
- new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
- 1);
- return;
- }else{
- isEligibleToTakePicture = true;
- }
- if(isEligibleToTakePicture){
- Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
- startActivityForResult(galleryIntent, GALLERY_PHOTO);
- }
- break;
- case 2:
- imageUrlFromS3 = "";
- profilePicture.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.profile));
- ServerManager.getInstance().updateProfile(profileName.getText().toString(), imageUrlFromS3);
- break;
- }
- }
- @Override
- public void onRequestPermissionsResult(int requestCode,
- String permissions[], int[] grantResults) {
- switch (requestCode) {
- case GALLERY_PHOTO: {
- if (grantResults.length > 0
- && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- takePhoto(GALLERY_PHOTO);
- } else {
- }
- return;
- }
- case CAMERA_PHOTO:{
- if (grantResults.length > 0
- && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- takePhoto(CAMERA_PHOTO);
- } else {
- }
- return;
- }
- }
- }
- @Override
- public void onActivityResult(final int requestCode, final int resultCode,final Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- final int CAMERA_PHOTO = 0;
- final int GALLERY_PHOTO = 1;
- final int CROP_PHOTO = 4;
- final android.os.Handler handler = new android.os.Handler();
- handler.postDelayed(new Runnable() {
- @Override
- public void run() {
- if(photoFile!=null) {
- attachmentUri= Uri.fromFile(photoFile);
- }
- String imagePath = null;
- if (resultCode == RESULT_OK && data!=null) {
- if (requestCode == CAMERA_PHOTO) {
- cropCapturedImage(Uri.fromFile(photoFile));
- } else if (requestCode == GALLERY_PHOTO) {
- cropCapturedImage(data.getData());
- } else if (requestCode == CROP_PHOTO){
- Uri selectedImageURI = Uri.fromFile(croppedPhotoFile);
- Bitmap croppedBitmap ;
- try {
- if (attachmentUri != null) {
- croppedBitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImageURI);
- } else {
- croppedBitmap = (Bitmap) data.getExtras().getParcelable("data");
- }
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
- profilePicture.setImageBitmap(croppedBitmap);
- attachmentUri = getImageUri(croppedBitmap);
- }catch (IOException e){
- Log.d("error", " IOException");
- }
- boolean hasDrawable = (profilePicture.getDrawable() != null);
- if (hasDrawable) {
- String filename = System.currentTimeMillis() + ".png";
- File imageFile = new File(getActivity().getCacheDir(), filename);
- try {
- imageFile = InterfaceManager.sharedInstance().convertUriImageToFile(getActivity(), attachmentUri, imageFile);
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (imageFile != null) {
- imageUrlFromS3 = UploadManager.getInstance().uploadProfilePictureImageAndGetImageURL(imageFile);
- ServerManager.getInstance().updateProfile(profileName.getText().toString(), imageUrlFromS3);
- }
- }
- }
- } else if(resultCode == RESULT_OK && attachmentUri!=null){
- if (requestCode == CAMERA_PHOTO) {
- cropCapturedImage(Uri.fromFile(photoFile));
- } else if (requestCode == GALLERY_PHOTO) {
- cropCapturedImage(data.getData());
- } else if (requestCode == CROP_PHOTO){
- attachmentUri = Uri.fromFile(croppedPhotoFile);
- Bitmap croppedBitmap ;
- try {
- if (attachmentUri != null) {
- croppedBitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), attachmentUri);
- } else {
- croppedBitmap = (Bitmap) data.getExtras().getParcelable("data");
- }
- if(croppedBitmap!=null) {
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
- profilePicture.setImageBitmap(croppedBitmap);
- attachmentUri = getImageUri(croppedBitmap);
- }
- }catch (IOException e){
- Log.d("error", " IOException");
- }
- boolean hasDrawable = (profilePicture.getDrawable() != null);
- if (hasDrawable) {
- String filename = System.currentTimeMillis() + ".png";
- File imageFile = new File(getActivity().getCacheDir(), filename);
- try {
- imageFile = InterfaceManager.sharedInstance().convertUriImageToFile(getActivity(), attachmentUri, imageFile);
- } catch (IOException e) {
- e.printStackTrace();
- }
- if (imageFile != null) {
- imageUrlFromS3 = UploadManager.getInstance().uploadProfilePictureImageAndGetImageURL(imageFile);
- ServerManager.getInstance().updateProfile(profileName.getText().toString(), imageUrlFromS3);
- }
- }
- }
- }
- }
- },1000);
- }
- private File createImageFile() throws IOException {
- String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
- String imageFileName = "JPEG_" + timeStamp + "_";
- File storageDir = Environment.getExternalStoragePublicDirectory(
- Environment.DIRECTORY_PICTURES);
- File image = File.createTempFile(
- imageFileName, ".jpeg", storageDir
- );
- mCurrentPhotoPath = "file:" + image.getAbsolutePath();
- return image;
- }
- public Uri getImageUri(Bitmap inImage) {
- ByteArrayOutputStream bytes = new ByteArrayOutputStream();
- inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
- String path = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), inImage, "Title", null);
- return Uri.parse(path);
- }
- public void cropCapturedImage(Uri picUri){
- try {
- Intent cropIntent = new Intent("com.android.camera.action.CROP");
- cropIntent.setDataAndType(picUri, "image/*");
- cropIntent.putExtra("crop", "true");
- cropIntent.putExtra("aspectX", 1);
- cropIntent.putExtra("aspectY", 1);
- cropIntent.putExtra("outputX", 400);
- cropIntent.putExtra("outputY", 400);
- cropIntent.putExtra("scale", true);
- cropIntent.putExtra("return-data", false);
- croppedPhotoFile = createImageFile();
- cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(croppedPhotoFile));
- startActivityForResult(cropIntent, 4);
- }
- catch (ActivityNotFoundException anfe) {
- Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.notification_can_not_crop), Toast.LENGTH_SHORT).show();
- }catch (IOException e){
- }
- }
- public void onEvent(SignOutFinishedEvent event){
- if(event.errorMessage.equalsIgnoreCase("")){
- SettingsManager.getInstance().setCurrentUser(null);
- SettingsManager.getInstance().setCurrentUserId(null);
- Intent i = new Intent(getActivity(), LoginMainPageActivity.class);
- getActivity().startActivity(i);
- getActivity().finish();
- }else{
- InterfaceManager.sharedInstance().showErrorMessage(getActivity(), event.errorMessage);
- }
- }
- public void onEvent(AddPicturePermissionEvent event){
- isEligibleToTakePicture = event.isEligible;
- if(isEligibleToTakePicture){
- takePhoto(event.requestCode);
- }
- }
- public void onEvent(GetUpdateUserFinishedEvent event){
- if(event.user==null){
- InterfaceManager.sharedInstance().showErrorMessage(getActivity(), event.errorMessage);
- }
- }
- @Override
- public void onDestroy(){
- super.onDestroy();
- if(EventBus.getDefault().isRegistered(this)) {
- EventBus.getDefault().unregister(this);
- }
- }
- }
Add Comment
Please, Sign In to add comment