gust94

ProfileFragment

Jan 19th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 22.39 KB | None | 0 0
  1. package com.dss.invitup.vc.homePage;
  2. import android.Manifest;
  3. import android.content.ActivityNotFoundException;
  4. import android.content.Context;
  5. import android.content.DialogInterface;
  6. import android.content.Intent;
  7. import android.content.pm.PackageManager;
  8. import android.graphics.Bitmap;
  9. import android.graphics.Typeface;
  10. import android.net.Uri;
  11. import android.os.Build;
  12. import android.os.Bundle;
  13. import android.os.Environment;
  14. import android.provider.MediaStore;
  15. import android.support.v4.app.ActivityCompat;
  16. import android.support.v4.app.Fragment;
  17. import android.support.v7.app.AlertDialog;
  18. import android.util.Log;
  19. import android.view.LayoutInflater;
  20. import android.view.MotionEvent;
  21. import android.view.View;
  22. import android.view.ViewGroup;
  23. import android.view.inputmethod.InputMethodManager;
  24. import android.widget.Button;
  25. import android.widget.ImageButton;
  26. import android.widget.LinearLayout;
  27. import android.widget.Toast;
  28. import com.bumptech.glide.Glide;
  29. import com.bumptech.glide.load.resource.drawable.GlideDrawable;
  30. import com.bumptech.glide.request.RequestListener;
  31. import com.bumptech.glide.request.target.Target;
  32. import com.dss.invitup.R;
  33. import com.dss.invitup.events.AddPicturePermissionEvent;
  34. import com.dss.invitup.events.GetUpdateUserFinishedEvent;
  35. import com.dss.invitup.events.HomePageBackButtonTapped;
  36. import com.dss.invitup.events.SignOutFinishedEvent;
  37. import com.dss.invitup.models.User;
  38. import com.dss.invitup.singleton.InterfaceManager;
  39. import com.dss.invitup.singleton.ServerManager;
  40. import com.dss.invitup.singleton.SettingsManager;
  41. import com.dss.invitup.singleton.UploadManager;
  42. import com.dss.invitup.vc.login.LoginMainPageActivity;
  43. import com.dss.invitup.view.RobotoBoldTextView;
  44. import com.dss.invitup.view.RobotoLightEditText;
  45. import com.dss.invitup.view.RobotoLightTextView;
  46. import com.facebook.login.LoginManager;
  47. import java.io.ByteArrayOutputStream;
  48. import java.io.File;
  49. import java.io.IOException;
  50. import java.text.SimpleDateFormat;
  51. import java.util.Date;
  52. import de.greenrobot.event.EventBus;
  53. import de.hdodenhof.circleimageview.CircleImageView;
  54. import static android.app.Activity.RESULT_OK;
  55. /**
  56. * Copyright © 2016 Dihardja Software Solutions. All rights reserved.
  57. */
  58. public class ProfileFragment extends Fragment{
  59. ImageButton backButton;
  60. Button logoutButton;
  61. CircleImageView profilePicture, profilePictureLoading;
  62. RobotoLightTextView profileEmail;
  63. RobotoLightEditText profileName;
  64. RobotoBoldTextView profileHostingCount, profileAttendingCount;
  65. String imageUrlFromS3;
  66. static final int CAMERA_PHOTO = 0;
  67. static final int GALLERY_PHOTO = 1;
  68. static final int REMOVE_PHOTO = 2;
  69. File photoFile = null;
  70. File croppedPhotoFile = null;
  71. String mCurrentPhotoPath;
  72. Uri attachmentUri;
  73. LinearLayout profileFragmentLinearLayout;
  74. InputMethodManager inputMethodManager;
  75. User user;
  76. boolean isEligibleToTakePicture = false;
  77. @Override
  78. public View onCreateView(LayoutInflater inflater, ViewGroup container,
  79. Bundle savedInstanceState) {
  80. View view = inflater.inflate(R.layout.fragment_profile, container, false);
  81. backButton = (ImageButton)view.findViewById(R.id.profileFragment_backButton);
  82. logoutButton = (Button) view.findViewById(R.id.profileFragment_logoutButton);
  83. profilePicture = (CircleImageView) view.findViewById(R.id.profileFragment_profilePicture);
  84. profilePictureLoading = (CircleImageView) view.findViewById(R.id.profileFragment_profilePictureLoading);
  85. profileName = (RobotoLightEditText) view.findViewById(R.id.profileFragment_profileName);
  86. profileEmail = (RobotoLightTextView) view.findViewById(R.id.profileFragment_profileEmail);
  87. profileHostingCount = (RobotoBoldTextView) view.findViewById(R.id.profileFragment_hostingCount);
  88. profileAttendingCount = (RobotoBoldTextView) view.findViewById(R.id.profileFragment_attendingCount);
  89. profileFragmentLinearLayout = (LinearLayout) view.findViewById(R.id.profileFragmentLinearLayout);
  90. inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
  91. return view;
  92. }
  93. @Override
  94. public void onViewCreated(View view, Bundle savedInstanceState) {
  95. super.onViewCreated(view, savedInstanceState);
  96. if(!EventBus.getDefault().isRegistered(this)){
  97. EventBus.getDefault().register(this);
  98. }
  99. if(SettingsManager.getInstance().getCurrentUser()!=null){
  100. user = SettingsManager.getInstance().getCurrentUser();
  101. }
  102. profileFragmentLinearLayout.setOnTouchListener(new View.OnTouchListener() {
  103. @Override
  104. public boolean onTouch(View v, MotionEvent event) {
  105. profileName.clearFocus();
  106. inputMethodManager.hideSoftInputFromWindow(profileFragmentLinearLayout.getWindowToken(), 0);
  107. return false;
  108. }
  109. });
  110. String firstName = "";
  111. String lastName = "";
  112. if(user.getFirstName()!= null){
  113. if(!user.getFirstName().equals("")){
  114. firstName = InterfaceManager.sharedInstance().getFirstLetterCapitalized(user.getFirstName());
  115. }
  116. }
  117. if(user.getLastName()!= null){
  118. if(!user.getLastName().equals("")){
  119. lastName = " " + InterfaceManager.sharedInstance().getFirstLetterCapitalized(user.getLastName());
  120. }
  121. }
  122. profileName.setText(firstName + lastName);
  123. String email = "";
  124. if(user.getEmail()!=null){
  125. email = user.getEmail();
  126. }
  127. profileEmail.setText(email);
  128. int attendingCount = 0;
  129. int hostingCount = 0;
  130. if(SettingsManager.getInstance().getCurrentUserOccasionResponse()!=null) {
  131. if (SettingsManager.getInstance().getCurrentUserOccasionResponse().getJoinedOccasions().size() != 0) {
  132. attendingCount = SettingsManager.getInstance().getCurrentUserOccasionResponse().getJoinedOccasions().size();
  133. }
  134. if (SettingsManager.getInstance().getCurrentUserOccasionResponse().getManagedOccasions().size() != 0) {
  135. hostingCount = SettingsManager.getInstance().getCurrentUserOccasionResponse().getManagedOccasions().size();
  136. }
  137. }
  138. profileHostingCount.setText(String.valueOf(hostingCount));
  139. profileAttendingCount.setText(String.valueOf(attendingCount));
  140. Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Light.otf");
  141. logoutButton.setTypeface(font);
  142. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  143. logoutButton.setLetterSpacing(0.07f);
  144. }
  145. profilePicture.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.profile));
  146. if(user.getImageURL()!=null){
  147. if(!user.getImageURL().equals("")){
  148. imageUrlFromS3 = user.getImageURL();
  149. profilePictureLoading.setVisibility(View.VISIBLE);
  150. Glide.with(getActivity()).load(user.getImageURL()).listener(new RequestListener<String, GlideDrawable>() {
  151. @Override
  152. public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
  153. return false;
  154. }
  155. @Override
  156. public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
  157. profilePictureLoading.setVisibility(View.GONE);
  158. return false;
  159. }
  160. }).into(profilePicture);
  161. }
  162. }
  163. profileName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
  164. @Override
  165. public void onFocusChange(View v, boolean hasFocus) {
  166. if(!hasFocus){
  167. ServerManager.getInstance().updateProfile(profileName.getText().toString(), imageUrlFromS3);
  168. }
  169. }
  170. });
  171. profilePicture.setOnClickListener(profilePictureListener);
  172. logoutButton.setOnClickListener(logoutButtonListener);
  173. backButton.setOnClickListener(backButtonListener);
  174. }
  175. ImageButton.OnClickListener backButtonListener = new View.OnClickListener() {
  176. @Override
  177. public void onClick(View v) {
  178. EventBus.getDefault().post(new HomePageBackButtonTapped());
  179. }
  180. };
  181. CircleImageView.OnClickListener profilePictureListener = new View.OnClickListener() {
  182. @Override
  183. public void onClick(View v) {
  184. final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
  185. final CharSequence options[] = new CharSequence[]{getActivity().getResources().getString(R.string.builder_take_picture),
  186. getActivity().getResources().getString(R.string.builder_choose_picture), getActivity().getResources().getString(R.string.builder_remove_picture)};
  187. builder.setTitle(getActivity().getResources().getString(R.string.builder_set_profile_picture));
  188. builder.setItems(options, new DialogInterface.OnClickListener() {
  189. @Override
  190. public void onClick(DialogInterface dialog, int which) {
  191. photoFile = null;
  192. try{
  193. photoFile = createImageFile();
  194. }catch (IOException ex){
  195. Log.e("err",ex.toString());
  196. }
  197. takePhoto(which);
  198. }
  199. });
  200. builder.show();
  201. if(profileName.hasFocus()){
  202. profileName.clearFocus();
  203. inputMethodManager.hideSoftInputFromWindow(profileFragmentLinearLayout.getWindowToken(), 0);
  204. }
  205. }
  206. };
  207. Button.OnClickListener logoutButtonListener = new View.OnClickListener() {
  208. @Override
  209. public void onClick(View v) {
  210. if(SettingsManager.getInstance().getCurrentUser().getLoginWithFacebook()){
  211. LoginManager.getInstance().logOut();
  212. }
  213. ServerManager.getInstance().logout();
  214. }
  215. };
  216. void takePhoto(int which){
  217. switch (which){
  218. case 0:
  219. if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
  220. if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
  221. ActivityCompat.requestPermissions(getActivity(),
  222. new String[]{Manifest.permission.CAMERA,
  223. Manifest.permission.WRITE_EXTERNAL_STORAGE},
  224. 0);
  225. return;
  226. } else {
  227. ActivityCompat.requestPermissions(getActivity(),
  228. new String[]{Manifest.permission.CAMERA},
  229. 0);
  230. return;
  231. }
  232. } else {
  233. if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
  234. ActivityCompat.requestPermissions(getActivity(),
  235. new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
  236. 0);
  237. return;
  238. }else{
  239. isEligibleToTakePicture = true;
  240. }
  241. }
  242. if(isEligibleToTakePicture){
  243. Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  244. if (photoFile != null) {
  245. cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
  246. startActivityForResult(cameraIntent, CAMERA_PHOTO);
  247. }
  248. }
  249. break;
  250. case 1:
  251. if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
  252. ActivityCompat.requestPermissions(getActivity(),
  253. new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
  254. 1);
  255. return;
  256. }else{
  257. isEligibleToTakePicture = true;
  258. }
  259. if(isEligibleToTakePicture){
  260. Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  261. startActivityForResult(galleryIntent, GALLERY_PHOTO);
  262. }
  263. break;
  264. case 2:
  265. imageUrlFromS3 = "";
  266. profilePicture.setImageDrawable(getActivity().getResources().getDrawable(R.drawable.profile));
  267. ServerManager.getInstance().updateProfile(profileName.getText().toString(), imageUrlFromS3);
  268. break;
  269. }
  270. }
  271. @Override
  272. public void onRequestPermissionsResult(int requestCode,
  273. String permissions[], int[] grantResults) {
  274. switch (requestCode) {
  275. case GALLERY_PHOTO: {
  276. if (grantResults.length > 0
  277. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  278. takePhoto(GALLERY_PHOTO);
  279. } else {
  280. }
  281. return;
  282. }
  283. case CAMERA_PHOTO:{
  284. if (grantResults.length > 0
  285. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  286. takePhoto(CAMERA_PHOTO);
  287. } else {
  288. }
  289. return;
  290. }
  291. }
  292. }
  293. @Override
  294. public void onActivityResult(final int requestCode, final int resultCode,final Intent data) {
  295. super.onActivityResult(requestCode, resultCode, data);
  296. final int CAMERA_PHOTO = 0;
  297. final int GALLERY_PHOTO = 1;
  298. final int CROP_PHOTO = 4;
  299. final android.os.Handler handler = new android.os.Handler();
  300. handler.postDelayed(new Runnable() {
  301. @Override
  302. public void run() {
  303. if(photoFile!=null) {
  304. attachmentUri= Uri.fromFile(photoFile);
  305. }
  306. String imagePath = null;
  307. if (resultCode == RESULT_OK && data!=null) {
  308. if (requestCode == CAMERA_PHOTO) {
  309. cropCapturedImage(Uri.fromFile(photoFile));
  310. } else if (requestCode == GALLERY_PHOTO) {
  311. cropCapturedImage(data.getData());
  312. } else if (requestCode == CROP_PHOTO){
  313. Uri selectedImageURI = Uri.fromFile(croppedPhotoFile);
  314. Bitmap croppedBitmap ;
  315. try {
  316. if (attachmentUri != null) {
  317. croppedBitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), selectedImageURI);
  318. } else {
  319. croppedBitmap = (Bitmap) data.getExtras().getParcelable("data");
  320. }
  321. ByteArrayOutputStream stream = new ByteArrayOutputStream();
  322. croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
  323. profilePicture.setImageBitmap(croppedBitmap);
  324. attachmentUri = getImageUri(croppedBitmap);
  325. }catch (IOException e){
  326. Log.d("error", " IOException");
  327. }
  328. boolean hasDrawable = (profilePicture.getDrawable() != null);
  329. if (hasDrawable) {
  330. String filename = System.currentTimeMillis() + ".png";
  331. File imageFile = new File(getActivity().getCacheDir(), filename);
  332. try {
  333. imageFile = InterfaceManager.sharedInstance().convertUriImageToFile(getActivity(), attachmentUri, imageFile);
  334. } catch (IOException e) {
  335. e.printStackTrace();
  336. }
  337. if (imageFile != null) {
  338. imageUrlFromS3 = UploadManager.getInstance().uploadProfilePictureImageAndGetImageURL(imageFile);
  339. ServerManager.getInstance().updateProfile(profileName.getText().toString(), imageUrlFromS3);
  340. }
  341. }
  342. }
  343. } else if(resultCode == RESULT_OK && attachmentUri!=null){
  344. if (requestCode == CAMERA_PHOTO) {
  345. cropCapturedImage(Uri.fromFile(photoFile));
  346. } else if (requestCode == GALLERY_PHOTO) {
  347. cropCapturedImage(data.getData());
  348. } else if (requestCode == CROP_PHOTO){
  349. attachmentUri = Uri.fromFile(croppedPhotoFile);
  350. Bitmap croppedBitmap ;
  351. try {
  352. if (attachmentUri != null) {
  353. croppedBitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), attachmentUri);
  354. } else {
  355. croppedBitmap = (Bitmap) data.getExtras().getParcelable("data");
  356. }
  357. if(croppedBitmap!=null) {
  358. ByteArrayOutputStream stream = new ByteArrayOutputStream();
  359. croppedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
  360. profilePicture.setImageBitmap(croppedBitmap);
  361. attachmentUri = getImageUri(croppedBitmap);
  362. }
  363. }catch (IOException e){
  364. Log.d("error", " IOException");
  365. }
  366. boolean hasDrawable = (profilePicture.getDrawable() != null);
  367. if (hasDrawable) {
  368. String filename = System.currentTimeMillis() + ".png";
  369. File imageFile = new File(getActivity().getCacheDir(), filename);
  370. try {
  371. imageFile = InterfaceManager.sharedInstance().convertUriImageToFile(getActivity(), attachmentUri, imageFile);
  372. } catch (IOException e) {
  373. e.printStackTrace();
  374. }
  375. if (imageFile != null) {
  376. imageUrlFromS3 = UploadManager.getInstance().uploadProfilePictureImageAndGetImageURL(imageFile);
  377. ServerManager.getInstance().updateProfile(profileName.getText().toString(), imageUrlFromS3);
  378. }
  379. }
  380. }
  381. }
  382. }
  383. },1000);
  384. }
  385. private File createImageFile() throws IOException {
  386. String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
  387. String imageFileName = "JPEG_" + timeStamp + "_";
  388. File storageDir = Environment.getExternalStoragePublicDirectory(
  389. Environment.DIRECTORY_PICTURES);
  390. File image = File.createTempFile(
  391. imageFileName, ".jpeg", storageDir
  392. );
  393. mCurrentPhotoPath = "file:" + image.getAbsolutePath();
  394. return image;
  395. }
  396. public Uri getImageUri(Bitmap inImage) {
  397. ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  398. inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
  399. String path = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), inImage, "Title", null);
  400. return Uri.parse(path);
  401. }
  402. public void cropCapturedImage(Uri picUri){
  403. try {
  404. Intent cropIntent = new Intent("com.android.camera.action.CROP");
  405. cropIntent.setDataAndType(picUri, "image/*");
  406. cropIntent.putExtra("crop", "true");
  407. cropIntent.putExtra("aspectX", 1);
  408. cropIntent.putExtra("aspectY", 1);
  409. cropIntent.putExtra("outputX", 400);
  410. cropIntent.putExtra("outputY", 400);
  411. cropIntent.putExtra("scale", true);
  412. cropIntent.putExtra("return-data", false);
  413. croppedPhotoFile = createImageFile();
  414. cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(croppedPhotoFile));
  415. startActivityForResult(cropIntent, 4);
  416. }
  417. catch (ActivityNotFoundException anfe) {
  418. Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.notification_can_not_crop), Toast.LENGTH_SHORT).show();
  419. }catch (IOException e){
  420. }
  421. }
  422. public void onEvent(SignOutFinishedEvent event){
  423. if(event.errorMessage.equalsIgnoreCase("")){
  424. SettingsManager.getInstance().setCurrentUser(null);
  425. SettingsManager.getInstance().setCurrentUserId(null);
  426. Intent i = new Intent(getActivity(), LoginMainPageActivity.class);
  427. getActivity().startActivity(i);
  428. getActivity().finish();
  429. }else{
  430. InterfaceManager.sharedInstance().showErrorMessage(getActivity(), event.errorMessage);
  431. }
  432. }
  433. public void onEvent(AddPicturePermissionEvent event){
  434. isEligibleToTakePicture = event.isEligible;
  435. if(isEligibleToTakePicture){
  436. takePhoto(event.requestCode);
  437. }
  438. }
  439. public void onEvent(GetUpdateUserFinishedEvent event){
  440. if(event.user==null){
  441. InterfaceManager.sharedInstance().showErrorMessage(getActivity(), event.errorMessage);
  442. }
  443. }
  444. @Override
  445. public void onDestroy(){
  446. super.onDestroy();
  447. if(EventBus.getDefault().isRegistered(this)) {
  448. EventBus.getDefault().unregister(this);
  449. }
  450. }
  451. }
Add Comment
Please, Sign In to add comment