Advertisement
Guest User

Untitled

a guest
Dec 11th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 15.08 KB | None | 0 0
  1. package ch.epfl.sweng.groupup.activity.event.files;
  2.  
  3. import android.content.ContentResolver;
  4. import android.content.Context;
  5. import android.content.Intent;
  6. import android.database.Cursor;
  7. import android.graphics.Bitmap;
  8. import android.graphics.BitmapFactory;
  9. import android.media.MediaMetadataRetriever;
  10. import android.media.ThumbnailUtils;
  11. import android.net.Uri;
  12. import android.os.Environment;
  13. import android.provider.MediaStore;
  14. import android.support.v4.content.CursorLoader;
  15. import android.support.v4.content.FileProvider;
  16. import android.util.Log;
  17. import android.view.View;
  18. import android.view.ViewGroup;
  19. import android.view.ViewTreeObserver;
  20. import android.widget.Button;
  21. import android.widget.GridLayout;
  22. import android.widget.ImageView;
  23. import android.widget.RelativeLayout;
  24. import android.widget.Toast;
  25.  
  26. import java.io.File;
  27. import java.io.FileNotFoundException;
  28. import java.io.IOException;
  29. import java.text.SimpleDateFormat;
  30. import java.util.Date;
  31. import java.util.List;
  32. import java.util.Locale;
  33.  
  34. import ch.epfl.sweng.groupup.R;
  35. import ch.epfl.sweng.groupup.activity.event.description.EventDescriptionActivity;
  36. import ch.epfl.sweng.groupup.lib.AndroidHelper;
  37. import ch.epfl.sweng.groupup.lib.Watcher;
  38. import ch.epfl.sweng.groupup.object.account.Account;
  39. import ch.epfl.sweng.groupup.object.event.Event;
  40.  
  41. import static android.app.Activity.RESULT_OK;
  42.  
  43. /**
  44. * FileManager class.
  45. * Contains all methods and attributes relative to the file management of an event.
  46. */
  47. @SuppressWarnings("WeakerAccess")
  48. public class FileManager implements Watcher {
  49.  
  50. private EventDescriptionActivity activity;
  51.  
  52. private final int COLUMNS = 3;
  53. private final int ROWS = 4;
  54. private int columnWidth;
  55. private int rowHeight;
  56. private final Event event;
  57. private int imagesAdded = 0;
  58.  
  59. private static final int REQUEST_IMAGE_CAPTURE = 1;
  60.  
  61. private String mCurrentPhotoPath;
  62.  
  63. /**
  64. * Creates a FileManager for a particular EventDescription activity.
  65. * @param activity the activity this FileManager is linked to.
  66. */
  67. public FileManager(final EventDescriptionActivity activity){
  68. this.activity = activity;
  69.  
  70. initializeTakePicture();
  71.  
  72. Intent i = activity.getIntent();
  73. final int eventIndex = i.getIntExtra(activity.getString(R.string.event_listing_extraIndex), -1);
  74. if (eventIndex > -1) {
  75. //!!!Order the events !!!
  76. event = Account.shared.getEvents().get(eventIndex);
  77. }else{
  78. event = null;
  79. }
  80.  
  81. if(event != null)
  82. event.addWatcher(this);
  83.  
  84. // Set onClickListeners to add files
  85. // TODO adding videos.
  86. activity.findViewById(R.id.add_files).setOnClickListener(new Button.OnClickListener() {
  87. @Override
  88. public void onClick(View arg0) {
  89. /*Intent intent = new Intent(Intent.ACTION_PICK,
  90. android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  91. activity.startActivityForResult(intent, 0);*/
  92. Intent intent = new Intent(Intent.ACTION_PICK);
  93. intent.setType("*/*");
  94. activity.startActivityForResult(intent, 0);
  95. }
  96. });
  97.  
  98. // Set onClickListener to create aftermovie
  99. activity.findViewById(R.id.create_aftermovie).setOnClickListener(new Button.OnClickListener(){
  100. @Override
  101. public void onClick(View arg0) {
  102. Intent i = new Intent(activity, SlideshowActivity.class);
  103. i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
  104. Intent.FLAG_ACTIVITY_CLEAR_TASK |
  105. Intent.FLAG_ACTIVITY_NEW_TASK);
  106. i.putExtra(activity.getString(R.string.event_listing_extraIndex), eventIndex);
  107. activity.startActivity(i);
  108. }});
  109.  
  110. // Set the GridLayout and initially get the height and width of the rows and columns.
  111. final GridLayout grid = activity.findViewById(R.id.image_grid);
  112. final RelativeLayout container = activity.findViewById(R.id.scroll_view_container);
  113. ViewTreeObserver vto = container.getViewTreeObserver();
  114. vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
  115. @Override
  116. public void onGlobalLayout() {
  117. container.getViewTreeObserver().removeOnGlobalLayoutListener(this);
  118. columnWidth = container.getMeasuredWidth() / COLUMNS;
  119. rowHeight = container.getMeasuredHeight() / ROWS;
  120. }
  121. });
  122.  
  123. ViewGroup.LayoutParams params = grid.getLayoutParams();
  124. params.height = rowHeight;
  125. grid.setLayoutParams(params);
  126.  
  127. // Add the event pictures as soon as possible to the Grid.
  128. ViewTreeObserver vto_grid = container.getViewTreeObserver();
  129. vto_grid.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
  130. @Override
  131. public void onGlobalLayout() {
  132. container.getViewTreeObserver().removeOnGlobalLayoutListener(this);
  133. if(event != null) {
  134. for (CompressedBitmap bitmap : event.getPictures()) {
  135. addImageToGrid(bitmap, false);
  136. }
  137. //TODO addvideotoGrid, on click listener to play the videoView
  138.  
  139. }
  140. }
  141. });
  142. }
  143.  
  144. /**
  145. * Closes the FileManager.
  146. * This method should be called when the activity using the FileManager is paused or destroyed
  147. * to avoid unnecessary network communications.
  148. */
  149. public void close(){
  150. event.removeWatcher(this);
  151. }
  152.  
  153. /**
  154. * Override of onActivityResult method.
  155. * Define the behavior when the user finished selecting the picture he wants to add or
  156. * taking a picture.
  157. *
  158. * @param requestCode unused.
  159. * @param resultCode indicate if the operation succeeded.
  160. * @param data the data returned by the previous activity.
  161. */
  162. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  163. event.addWatcher(this);
  164.  
  165. if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
  166. galleryAddPic();
  167. Bitmap imageBitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
  168. CompressedBitmap compressedBitmap = new CompressedBitmap(imageBitmap);
  169. addImageToGrid(compressedBitmap, true);
  170. } else if (resultCode == RESULT_OK) {
  171. Uri targetUri = data.getData();
  172. String type= data.getType();
  173. if (targetUri == null) {
  174. AndroidHelper.showToast(activity.getApplicationContext(),
  175. activity.getString(R.string.file_management_toast_error_file_uri),
  176. Toast.LENGTH_SHORT);
  177. return;
  178. }
  179.  
  180. if (imagesAdded % COLUMNS == 0) {
  181. ((GridLayout) activity.findViewById(R.id.image_grid))
  182. .setRowCount(imagesAdded / ROWS + 1);
  183. ViewGroup.LayoutParams params = activity.findViewById(R.id.image_grid).getLayoutParams();
  184. params.height = Math.round(rowHeight * (imagesAdded / ROWS + 1));
  185. activity.findViewById(R.id.image_grid)
  186. .setLayoutParams(params);
  187. }
  188.  
  189.  
  190. if(type.contains("image")) {
  191. recoverAndUploadImage(targetUri);
  192. }else {
  193. recoverAndUploadVideo(targetUri);
  194. }
  195. }
  196. }
  197.  
  198. /**
  199. * Recover a video from the user's phone from its uri and upload it on the database.
  200. * @param targetUri the uri of the video.
  201. */
  202. private void recoverAndUploadVideo(Uri targetUri){
  203. addVideoToGrid(targetUri);
  204. event.addVideo(Account.shared.getUUID().getOrElse("Default ID"),targetUri);
  205. }
  206.  
  207. /**
  208. * Recover an image from the user's phone from its uri and download it on the database.
  209. * @param targetUri the uri of the image.
  210. */
  211. private void recoverAndUploadImage(Uri targetUri){
  212. Bitmap bitmap;
  213. try {
  214.  
  215. bitmap = BitmapFactory.decodeStream(activity.getContentResolver().openInputStream(targetUri));
  216.  
  217. } catch (FileNotFoundException e) {
  218. AndroidHelper.showToast(activity.getApplicationContext(),
  219. activity.getString(R.string.file_management_toast_error_file_uri),
  220. Toast.LENGTH_SHORT);
  221. return;
  222. }
  223. CompressedBitmap compressedBitmap = new CompressedBitmap(bitmap);
  224. addImageToGrid(compressedBitmap, true);
  225. }
  226.  
  227. //TODO TAKE VIDEOS FROM APP
  228. /**
  229. * Initialize the camera button and open the camera
  230. */
  231. private void initializeTakePicture() {
  232. Button takePicture = activity.findViewById(R.id.take_picture);
  233. final Context thisContext= activity.getApplicationContext();
  234. takePicture.setOnClickListener(new View.OnClickListener() {
  235. @Override
  236. public void onClick(View view) {
  237. Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  238. if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
  239. File photo = null;
  240. try {
  241. photo = createImageFile();
  242. } catch (IOException e) {
  243. AndroidHelper.showToast(activity.getApplicationContext(),
  244. activity.getString(R.string.file_management_toast_error_file_not_created),
  245. Toast.LENGTH_SHORT);
  246. }
  247. if (photo != null) {
  248. Uri photoUri= FileProvider.getUriForFile(thisContext,"com.example.android.fileprovider",photo);
  249. takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,photoUri);
  250. activity.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
  251. }
  252. }
  253. }
  254. });
  255. }
  256.  
  257. private File createImageFile() throws IOException {
  258. // Create an image file name
  259. String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss", Locale.getDefault()).format(new Date());
  260. String imageFileName = "JPEG_" + timeStamp + "_";
  261. File storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
  262. File image = File.createTempFile(
  263. imageFileName, /* prefix */
  264. ".jpg", /* suffix */
  265. storageDir /* directory */
  266. );
  267.  
  268. // Save a file: path for use with ACTION_VIEW intents
  269. mCurrentPhotoPath = image.getAbsolutePath();
  270. return image;
  271. }
  272.  
  273. /**
  274. * Add the photos to the gallery on the phone
  275. */
  276. private void galleryAddPic() {
  277. Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
  278. File f = new File(mCurrentPhotoPath);
  279. Uri contentUri = Uri.fromFile(f);
  280. mediaScanIntent.setData(contentUri);
  281. activity.sendBroadcast(mediaScanIntent);
  282. }
  283.  
  284.  
  285. /**
  286. * Helper method to clear all the images of the grid.
  287. */
  288. private void clearImages() {
  289. ((GridLayout) activity.findViewById(R.id.image_grid))
  290. .removeAllViews();
  291. imagesAdded = 0;
  292. }
  293.  
  294. private void addVideoToGrid(Uri uri){
  295. MediaMetadataRetriever mMMR = new MediaMetadataRetriever();
  296. mMMR.setDataSource(activity,uri);
  297. CompressedBitmap thumb = new CompressedBitmap(mMMR.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC));
  298. addImageToGrid(thumb, false);
  299. }
  300. /**
  301. * Add an image to the grid and to the Firebase storage.
  302. *
  303. * @param bitmap the image to add.
  304. */
  305. private void addImageToGrid(final CompressedBitmap bitmap, boolean addToDatabase) {
  306. ImageView image = new ImageView(activity);
  307.  
  308. GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
  309. layoutParams.width = columnWidth;
  310. layoutParams.height = rowHeight;
  311. image.setLayoutParams(layoutParams);
  312.  
  313. Bitmap trimed = trimBitmap(bitmap.asBitmap());
  314.  
  315. image.setImageBitmap(trimed);
  316.  
  317. image.setOnClickListener(new View.OnClickListener() {
  318. @Override
  319. public void onClick(View v) {
  320.  
  321. ((ImageView)activity.findViewById(R.id.show_image))
  322. .setImageBitmap(bitmap.asBitmap());
  323.  
  324. activity.findViewById(R.id.image_grid)
  325. .setVisibility(View.INVISIBLE);
  326.  
  327. activity.findViewById(R.id.show_image)
  328. .setVisibility(View.VISIBLE);
  329.  
  330. activity.findViewById(R.id.show_image)
  331. .setOnClickListener(new View.OnClickListener() {
  332. @Override
  333. public void onClick(View v) {
  334. activity.findViewById(R.id.show_image)
  335. .setVisibility(View.INVISIBLE);
  336.  
  337. activity.findViewById(R.id.image_grid)
  338. .setVisibility(View.VISIBLE);
  339. }
  340. });
  341. }
  342. });
  343.  
  344. ((GridLayout) activity.findViewById(R.id.image_grid))
  345. .addView(image, imagesAdded++);
  346.  
  347. if(addToDatabase)
  348. event.addPicture(Account.shared.getUUID().getOrElse("Default ID"),
  349. bitmap);
  350. }
  351.  
  352. /**
  353. * Helper method to trim an image, the resulting image will be centered, with a width of a
  354. * column and the height of a row in the grid.
  355. *
  356. * @param bitmap the bitmap to trim.
  357. * @return the trimmed image.
  358. */
  359. private Bitmap trimBitmap(Bitmap bitmap) {
  360.  
  361. //Scaling bitmap
  362. Bitmap scaled;
  363.  
  364. if (bitmap.getWidth() > bitmap.getHeight()) {
  365. int nh = (int) (bitmap.getWidth() * (1.0 * rowHeight / bitmap.getHeight()));
  366. scaled = Bitmap.createScaledBitmap(bitmap, nh, rowHeight, true);
  367. } else {
  368. int nh = (int) (bitmap.getHeight() * (1.0 * columnWidth / bitmap.getWidth()));
  369. scaled = Bitmap.createScaledBitmap(bitmap, columnWidth, nh, true);
  370. }
  371.  
  372. int cutOnSide = (scaled.getWidth() - columnWidth) / 2;
  373. int cutOnTop = (scaled.getHeight() - rowHeight) / 2;
  374.  
  375. if(cutOnSide > 0 || cutOnTop > 0)
  376. scaled = Bitmap.createBitmap(scaled, cutOnSide, cutOnTop,
  377. columnWidth, rowHeight);
  378.  
  379. return scaled;
  380. }
  381.  
  382. /**
  383. * Override of notifyWatcher.
  384. * When notified, synchronise the grid images with the event images.
  385. */
  386. @Override
  387. public void notifyWatcher() {
  388. clearImages();
  389. for(CompressedBitmap bitmap : event.getPictures()){
  390. addImageToGrid(bitmap, false);
  391. }
  392. for(Uri f : event.getEventVideos()){
  393. addVideoToGrid(f);
  394. }
  395. }
  396.  
  397. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement