You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TasksFragment.java 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. package com.example.meinwald.ui.task;
  2. import android.Manifest;
  3. import android.app.Activity;
  4. import android.app.AlertDialog;
  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.BitmapFactory;
  10. import android.graphics.Color;
  11. import android.location.Location;
  12. import android.media.Image;
  13. import android.os.Build;
  14. import android.os.Bundle;
  15. import android.os.Handler;
  16. import android.preference.PreferenceManager;
  17. import android.util.Log;
  18. import android.view.Gravity;
  19. import android.view.LayoutInflater;
  20. import android.view.View;
  21. import android.view.ViewGroup;
  22. import android.widget.AdapterView;
  23. import android.widget.Button;
  24. import android.widget.ImageView;
  25. import android.widget.ListView;
  26. import android.widget.TextView;
  27. import android.widget.Toast;
  28. import androidx.annotation.NonNull;
  29. import androidx.annotation.Nullable;
  30. import androidx.annotation.RequiresApi;
  31. import androidx.core.app.ActivityCompat;
  32. import androidx.core.content.ContextCompat;
  33. import androidx.fragment.app.Fragment;
  34. import androidx.lifecycle.Observer;
  35. import androidx.lifecycle.ViewModelProviders;
  36. import com.example.meinwald.BuildConfig;
  37. import com.example.meinwald.R;
  38. import com.google.android.gms.location.FusedLocationProviderClient;
  39. import com.google.android.gms.location.LocationServices;
  40. import com.google.android.gms.maps.CameraUpdateFactory;
  41. import com.google.android.gms.tasks.OnCompleteListener;
  42. import com.google.android.gms.tasks.Task;
  43. import com.google.android.material.floatingactionbutton.FloatingActionButton;
  44. import com.google.android.material.snackbar.Snackbar;
  45. import org.json.JSONArray;
  46. import org.json.JSONException;
  47. import org.json.JSONObject;
  48. import java.io.File;
  49. import java.io.FileNotFoundException;
  50. import java.io.FileOutputStream;
  51. import java.io.IOException;
  52. import java.lang.reflect.Array;
  53. import java.nio.ByteBuffer;
  54. import java.util.ArrayList;
  55. import java.util.Date;
  56. import java.util.List;
  57. public class TasksFragment extends Fragment {
  58. private static final String TAG = TasksFragment.class.getSimpleName();
  59. private View root;
  60. private LayoutInflater layoutInflater;
  61. private ImageView imageToAdd;
  62. /**
  63. * ______________________________________________________________________________________________
  64. * LOCATION
  65. */
  66. private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
  67. /**
  68. * The entry point to the Fused Location Provider.
  69. */
  70. private FusedLocationProviderClient mFusedLocationProviderClient;
  71. private boolean mLocationPermissionGranted;
  72. /**
  73. * The geographical location where the device is currently located.
  74. * That is the last-known location retrieved by the Fused Location Provider.
  75. */
  76. private Location mLastKnownLocation;
  77. /**
  78. * ______________________________________________________________________________________________
  79. * TASKS
  80. */
  81. private OwnTask newTask = new OwnTask();
  82. private List<OwnTask> allTasks;
  83. private ListView taskList;
  84. private static final String KEY_ALL_TASKS = "allTasks";
  85. /**
  86. * ______________________________________________________________________________________________
  87. * CAMERA
  88. */
  89. private static final int MY_CAMERA_PERMISSION_CODE = 100;
  90. private boolean mCameraPermissionGranted;
  91. private static final int CAMERA_REQUEST = 1888;
  92. /**
  93. * ______________________________________________________________________________________________
  94. * STORAGE
  95. */
  96. private static final int READ_EXTERNAL_STORAGE_CODE = 200;
  97. private static final int WRITE_EXTERNAL_STORAGE_CODE = 201;
  98. private boolean mReadStorageGranted;
  99. private boolean mWriteStorageGranted;
  100. public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  101. layoutInflater = inflater;
  102. root = inflater.inflate(R.layout.fragment_tasks, container, false);
  103. taskList = (ListView) root.findViewById(R.id.taskListView);
  104. //instantiate add button
  105. FloatingActionButton fab = root.findViewById(R.id.fab_tasks);
  106. allTasks = readTasksFromPreferences();
  107. instantiateTaskList();
  108. //construct a FusedLocationProviderClient.
  109. mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
  110. //get read storage permission
  111. getReadStoragePermission();
  112. //get location permission
  113. getLocationPermission();
  114. fab.setOnClickListener(new View.OnClickListener() {
  115. @Override
  116. public void onClick(View view) {
  117. AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
  118. newTask = new OwnTask();
  119. //check permissions
  120. getDeviceLocation();
  121. getCameraPPermission();
  122. getWriteStoragePPermission();
  123. final View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.task_input, (ViewGroup) getView(), false);
  124. builder.setView(viewInflated);
  125. imageToAdd = viewInflated.findViewById(R.id.taskImage);
  126. //set location
  127. final Button buttonSetLocation = viewInflated.findViewById(R.id.taskSetLocation);
  128. final TextView locationText = viewInflated.findViewById(R.id.taskLocation);
  129. buttonSetLocation.setOnClickListener(new View.OnClickListener() {
  130. public void onClick(View v) {
  131. if (BuildConfig.DEBUG)
  132. {
  133. Log.d(TAG, "add Location!");
  134. }
  135. getLocationPermission();
  136. getDeviceLocation();
  137. do {
  138. final Handler handler = new Handler();
  139. handler.postDelayed(new Runnable() {
  140. @Override
  141. public void run() {
  142. //wait if there is no known location
  143. }
  144. }, 100);
  145. }while (mLastKnownLocation == null);
  146. //save and display location
  147. newTask.setLocation(mLastKnownLocation);
  148. locationText.setText("Lat: " +String.valueOf(mLastKnownLocation.getLatitude()) + " Lng: " + String.valueOf(mLastKnownLocation.getLongitude()));
  149. }
  150. });
  151. //add picture
  152. final Button buttonAddPicture = viewInflated.findViewById(R.id.taskAddPicture);
  153. buttonAddPicture.setOnClickListener(new View.OnClickListener() {
  154. public void onClick(View v) {
  155. if (BuildConfig.DEBUG)
  156. {
  157. Log.d(TAG, "add Picture!");
  158. }
  159. if (!mCameraPermissionGranted)
  160. {
  161. if (BuildConfig.DEBUG)
  162. {
  163. Log.d(TAG, "Camera permission not granted!");
  164. }
  165. getCameraPPermission();
  166. }
  167. else
  168. {
  169. if (BuildConfig.DEBUG)
  170. {
  171. Log.d(TAG, "Camera permission granted!");
  172. }
  173. Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
  174. startActivityForResult(cameraIntent, CAMERA_REQUEST);
  175. }
  176. }
  177. });
  178. builder.setPositiveButton("Bestätigen", new DialogInterface.OnClickListener() {
  179. @Override
  180. public void onClick(DialogInterface dialog, int which) {
  181. final TextView titleView = viewInflated.findViewById(R.id.taskTitleUserInput);
  182. final TextView noticeView = viewInflated.findViewById(R.id.taskNoticeUserInput);
  183. if (BuildConfig.DEBUG) {
  184. Log.d(TAG, "new title: " + titleView.getText());
  185. }
  186. if (titleView.getText().length()>0)
  187. {
  188. //save user input
  189. newTask.setTitle(String.valueOf(titleView.getText()));
  190. newTask.setNotice(String.valueOf(noticeView.getText()));
  191. boolean result = allTasks.add(newTask);
  192. if (BuildConfig.DEBUG)
  193. {
  194. Log.d(TAG, "new Task: " + newTask.toString());
  195. Log.d(TAG, "add new task result: " + result);
  196. /**
  197. for (OwnTask task: allTasks)
  198. {
  199. if (BuildConfig.DEBUG) {
  200. Log.d(TAG, task.toString());
  201. }
  202. }
  203. **/
  204. }
  205. instantiateTaskList();
  206. dialog.dismiss();
  207. //confirm added task
  208. Toast toast = Toast.makeText(getActivity(), "Aufgabe hinzugefügt!", Toast.LENGTH_SHORT);
  209. TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
  210. if( v != null)
  211. {
  212. //text align center
  213. v.setGravity(Gravity.CENTER);
  214. }
  215. toast.show();
  216. }
  217. else
  218. {
  219. //title needed
  220. Toast toast = Toast.makeText(getActivity(), "Aufgabentitel fehlt!", Toast.LENGTH_SHORT);
  221. TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
  222. if( v != null)
  223. {
  224. //text align center
  225. v.setGravity(Gravity.CENTER);
  226. }
  227. toast.show();
  228. }
  229. }
  230. });
  231. builder.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
  232. @Override
  233. public void onClick(DialogInterface dialog, int which) {
  234. dialog.cancel();
  235. }
  236. });
  237. builder.show();
  238. }
  239. });
  240. return root;
  241. }
  242. @Override
  243. public void onPause()
  244. {
  245. super.onPause();
  246. emptyPreferencesAndSaveTasksToPreferences();
  247. }
  248. /**
  249. * Saves tasks to preferences
  250. */
  251. private void emptyPreferencesAndSaveTasksToPreferences() {
  252. if (BuildConfig.DEBUG)
  253. {
  254. Log.d(TAG, "emptyPreferencesAndSaveTasksToPreferences()");
  255. }
  256. if (!allTasks.isEmpty()) {
  257. if (BuildConfig.DEBUG) {
  258. Log.d(TAG, "allTasks not empty!");
  259. for (OwnTask task: allTasks)
  260. {
  261. Log.d(TAG, task.toString());
  262. }
  263. }
  264. PreferenceManager.getDefaultSharedPreferences(getContext()).edit().remove(KEY_ALL_TASKS).commit();
  265. JSONArray writeObjects = new JSONArray();
  266. for (OwnTask task: allTasks)
  267. {
  268. if (BuildConfig.DEBUG) {
  269. Log.d(TAG, task.toString());
  270. }
  271. }
  272. for (OwnTask task: allTasks)
  273. {
  274. if (BuildConfig.DEBUG) {
  275. Log.d(TAG, "save task: " + task.toString());
  276. }
  277. if (task.getImage() != null)
  278. {
  279. //save image to external storage and save path
  280. String path = saveReceivedImage(task.getImage(), task.getId());
  281. task.setPathImage(path);
  282. if (BuildConfig.DEBUG) {
  283. Log.d(TAG, "saved image with path: " + task.getPathImage());
  284. }
  285. }
  286. JSONObject object = task.toJSONObject();
  287. writeObjects.put(object);
  288. if (BuildConfig.DEBUG) {
  289. Log.d(TAG, object.toString());
  290. }
  291. }
  292. PreferenceManager.getDefaultSharedPreferences(getContext()).edit().putString(KEY_ALL_TASKS, writeObjects.toString()).commit();
  293. }
  294. }
  295. private String saveReceivedImage(Bitmap bitmap, String imageName){
  296. File path = null;
  297. try {
  298. path = new File(getContext().getFilesDir(), "meinWald" + File.separator + "Images");
  299. if(!path.exists()){
  300. path.mkdirs();
  301. }
  302. if (BuildConfig.DEBUG) {
  303. Log.d(TAG, "Image file path: " + path);
  304. }
  305. File outFile = new File(path, imageName + ".jpeg");
  306. if (!outFile.exists())
  307. {
  308. FileOutputStream outputStream = new FileOutputStream(outFile);
  309. bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
  310. outputStream.close();
  311. }
  312. } catch (FileNotFoundException e) {
  313. Log.e(TAG, "Saving received message failed with", e);
  314. } catch (IOException e) {
  315. Log.e(TAG, "Saving received message failed with", e);
  316. }
  317. return path.toString();
  318. }
  319. /**
  320. * Reads tasks saved in preferences as jsonStrings
  321. *
  322. * @return list of OwnTask
  323. */
  324. private List<OwnTask> readTasksFromPreferences() {
  325. List<OwnTask> tasks = new ArrayList<>();
  326. try {
  327. String jsonString = PreferenceManager.getDefaultSharedPreferences(getContext()).getString(KEY_ALL_TASKS, "error");
  328. if(!"error".equalsIgnoreCase(jsonString)) {
  329. JSONArray jsonObjects = new JSONArray(jsonString);
  330. for (int i = 0; i<jsonObjects.length();i++) {
  331. tasks.add(new OwnTask(jsonObjects.getJSONObject(i)));
  332. if (BuildConfig.DEBUG) {
  333. Log.d(TAG, "Task loaded from shared preferences: " + tasks.get(i).toString());
  334. }
  335. Bitmap image = BitmapFactory.decodeFile(tasks.get(i).getPathImage() + File.separator + tasks.get(i).getId() + ".jpeg");
  336. if (BuildConfig.DEBUG) {
  337. Log.d(TAG, "Image loaded from shared preferences: " + image.getByteCount());
  338. }
  339. tasks.get(i).setImage(image);
  340. }
  341. }
  342. } catch (JSONException e) {
  343. if (BuildConfig.DEBUG) {
  344. Log.e(TAG, "Error while parsing tasks as jsonObjects from preferences");
  345. e.printStackTrace();
  346. }
  347. }
  348. return tasks;
  349. }
  350. /**
  351. * Get all stored tasks and save them temporary.
  352. */
  353. public void instantiateTaskList()
  354. {
  355. final TaskAdapter adapter = new TaskAdapter(getActivity().getApplicationContext(),allTasks);
  356. taskList.setAdapter(adapter);
  357. //initialise onClickListeners
  358. taskList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  359. @Override
  360. public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
  361. //for (int j = 0; j < adapterView.getChildCount(); j++)
  362. //adapterView.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);
  363. // change the background color of the selected element
  364. //view.setBackgroundColor(Color.LTGRAY);
  365. //adapterView.setSelection(i);
  366. }});
  367. }
  368. /**
  369. * Request location permission, so that we can get the location of the device.
  370. * The result of the permission request is handled by a callback,
  371. * onRequestPermissionsResult.
  372. *
  373. */
  374. private void getLocationPermission() {
  375. if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
  376. android.Manifest.permission.ACCESS_FINE_LOCATION)
  377. == PackageManager.PERMISSION_GRANTED) {
  378. mLocationPermissionGranted = true;
  379. } else {
  380. ActivityCompat.requestPermissions(getActivity(),
  381. new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
  382. PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
  383. }
  384. }
  385. /**
  386. * Request camera permission, so that we can get an image from the camera.
  387. * The result of the permission request is handled by a callback,
  388. * onRequestPermissionsResult.
  389. *
  390. */
  391. private void getCameraPPermission() {
  392. if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
  393. Manifest.permission.CAMERA)
  394. == PackageManager.PERMISSION_GRANTED) {
  395. mCameraPermissionGranted = true;
  396. } else {
  397. ActivityCompat.requestPermissions(getActivity(),
  398. new String[]{android.Manifest.permission.CAMERA},
  399. MY_CAMERA_PERMISSION_CODE);
  400. }
  401. }
  402. /**
  403. * Request read external storage permission, so that we can get saved images from external storage.
  404. * The result of the permission request is handled by a callback,
  405. * onRequestPermissionsResult.
  406. *
  407. */
  408. private void getReadStoragePermission() {
  409. if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
  410. Manifest.permission.READ_EXTERNAL_STORAGE)
  411. == PackageManager.PERMISSION_GRANTED) {
  412. mReadStorageGranted = true;
  413. } else {
  414. ActivityCompat.requestPermissions(getActivity(),
  415. new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
  416. READ_EXTERNAL_STORAGE_CODE);
  417. }
  418. }
  419. /**
  420. * Request read external storage permission, so that we can get saved images from external storage.
  421. * The result of the permission request is handled by a callback,
  422. * onRequestPermissionsResult.
  423. *
  424. */
  425. private void getWriteStoragePPermission() {
  426. if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
  427. Manifest.permission.WRITE_EXTERNAL_STORAGE)
  428. == PackageManager.PERMISSION_GRANTED) {
  429. mWriteStorageGranted = true;
  430. } else {
  431. ActivityCompat.requestPermissions(getActivity(),
  432. new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
  433. WRITE_EXTERNAL_STORAGE_CODE);
  434. }
  435. }
  436. /**
  437. * DOCU ME!
  438. * TOOD: What are grant results etc for?
  439. * @param requestCode
  440. * @param permissions
  441. * @param grantResults
  442. */
  443. @Override
  444. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
  445. {
  446. if (BuildConfig.DEBUG) {
  447. Log.d(TAG, "onRequestPermissionResult Code: " + requestCode);
  448. }
  449. mLocationPermissionGranted = false;
  450. switch (requestCode) {
  451. case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
  452. // If request is cancelled, the result arrays are empty.
  453. if (grantResults.length > 0
  454. && grantResults[0] == PackageManager.PERMISSION_GRANTED)
  455. {
  456. mLocationPermissionGranted = true;
  457. }
  458. }
  459. case MY_CAMERA_PERMISSION_CODE: {
  460. if (grantResults.length > 0
  461. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  462. mCameraPermissionGranted = true;
  463. }
  464. }
  465. case READ_EXTERNAL_STORAGE_CODE: {
  466. if (grantResults.length > 0
  467. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  468. mReadStorageGranted = true;
  469. }
  470. }
  471. case WRITE_EXTERNAL_STORAGE_CODE: {
  472. if (grantResults.length > 0
  473. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  474. mWriteStorageGranted = true;
  475. }
  476. }
  477. }
  478. }
  479. @RequiresApi(api = Build.VERSION_CODES.KITKAT)
  480. @Override
  481. public void onActivityResult(int requestCode, int resultCode, Intent data)
  482. {
  483. if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
  484. {
  485. Bitmap photo = (Bitmap) data.getExtras().get("data");
  486. newTask.setImage(photo);
  487. newTask.setPathImage(saveReceivedImage(photo,newTask.getId()));
  488. if (imageToAdd != null && photo != null)
  489. {
  490. imageToAdd.setImageBitmap(photo);
  491. }
  492. }
  493. }
  494. /**
  495. * Get the best and most recent location of the device, which may be null in rare
  496. * cases when a location is not available.
  497. *
  498. */
  499. private void getDeviceLocation() {
  500. try {
  501. if (mLocationPermissionGranted) {
  502. Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
  503. locationResult.addOnCompleteListener(getActivity(), new OnCompleteListener<Location>() {
  504. @Override
  505. public void onComplete(@NonNull Task<Location> task) {
  506. if (task.isSuccessful()) {
  507. // Set the last known position to the current location of the device.
  508. mLastKnownLocation = task.getResult();
  509. if (BuildConfig.DEBUG) {
  510. if (task.getResult() != null)
  511. {
  512. Log.d(TAG, "getDeviceLocation " + task.getResult().toString());
  513. }
  514. }
  515. } else {
  516. if (BuildConfig.DEBUG) {
  517. Log.d(TAG, "Current location is null. Using defaults.");
  518. Log.e(TAG, "Exception: %s", task.getException());
  519. }
  520. if (BuildConfig.DEBUG) {
  521. Log.d(TAG, "getDeviceLocation: task not successful");
  522. }
  523. }
  524. }
  525. });
  526. }
  527. } catch (SecurityException e) {
  528. if (BuildConfig.DEBUG) {
  529. Log.e(TAG, "Exception occurred: ");
  530. e.printStackTrace();
  531. }
  532. }
  533. }
  534. }