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

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