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.

AreaFragment.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. package com.example.meinwald.ui.area;
  2. import android.Manifest;
  3. import android.annotation.SuppressLint;
  4. import android.app.AlertDialog;
  5. import android.content.ComponentName;
  6. import android.content.DialogInterface;
  7. import android.content.ServiceConnection;
  8. import android.content.pm.PackageManager;
  9. import android.location.Location;
  10. import android.os.Bundle;
  11. import android.os.IBinder;
  12. import android.os.PowerManager;
  13. import android.preference.PreferenceManager;
  14. import android.util.Log;
  15. import android.view.Gravity;
  16. import android.view.LayoutInflater;
  17. import android.view.View;
  18. import android.view.ViewGroup;
  19. import android.widget.AdapterView;
  20. import android.widget.Button;
  21. import android.widget.ListView;
  22. import android.widget.TextView;
  23. import android.widget.Toast;
  24. import androidx.annotation.NonNull;
  25. import androidx.annotation.Nullable;
  26. import androidx.core.app.ActivityCompat;
  27. import androidx.core.content.ContextCompat;
  28. import androidx.fragment.app.Fragment;
  29. import androidx.lifecycle.Observer;
  30. import com.example.meinwald.BuildConfig;
  31. import com.example.meinwald.R;
  32. import com.example.meinwald.ui.task.TaskAdapter;
  33. import com.example.meinwald.ui.task.TasksFragment;
  34. import com.google.android.gms.location.FusedLocationProviderClient;
  35. import com.google.android.gms.location.LocationServices;
  36. import com.google.android.gms.maps.model.LatLng;
  37. import com.google.android.gms.tasks.OnCompleteListener;
  38. import com.google.android.gms.tasks.Task;
  39. import com.google.android.material.floatingactionbutton.FloatingActionButton;
  40. import org.json.JSONArray;
  41. import org.json.JSONException;
  42. import org.json.JSONObject;
  43. import org.json.JSONStringer;
  44. import java.io.BufferedReader;
  45. import java.io.File;
  46. import java.io.FileNotFoundException;
  47. import java.io.FileOutputStream;
  48. import java.io.FileReader;
  49. import java.io.IOException;
  50. import java.io.InputStream;
  51. import java.io.InputStreamReader;
  52. import java.io.PrintWriter;
  53. import java.util.ArrayList;
  54. import java.util.List;
  55. import static android.content.Context.POWER_SERVICE;
  56. public class AreaFragment extends Fragment {
  57. private static final String TAG = TasksFragment.class.getSimpleName();
  58. /**
  59. * ______________________________________________________________________________________________
  60. * AREA
  61. */
  62. private OwnArea newArea = new OwnArea();
  63. private List<OwnArea> allAreas;
  64. private ListView areaList;
  65. private static final String KEY_AREA_REFERENCES = "areaReferences";
  66. private List<AreaReference> areaReferences;
  67. /**
  68. * ______________________________________________________________________________________________
  69. * LOCATION
  70. */
  71. private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
  72. /**
  73. * The entry point to the Fused Location Provider.
  74. */
  75. private FusedLocationProviderClient mFusedLocationProviderClient;
  76. private boolean mLocationPermissionGranted;
  77. /**
  78. * The geographical locations which were received from location tracking.
  79. */
  80. private List<LatLng> newPositions;
  81. /**
  82. * ______________________________________________________________________________________________
  83. * CAMERA
  84. */
  85. private static final int MY_CAMERA_PERMISSION_CODE = 100;
  86. private boolean mCameraPermissionGranted;
  87. private static final int CAMERA_REQUEST = 1888;
  88. /**
  89. * ______________________________________________________________________________________________
  90. * STORAGE
  91. */
  92. private static final int READ_EXTERNAL_STORAGE_CODE = 200;
  93. private static final int WRITE_EXTERNAL_STORAGE_CODE = 201;
  94. private boolean mReadStorageGranted;
  95. private boolean mWriteStorageGranted;
  96. PowerManager.WakeLock wakeLock;
  97. LocationService gps;
  98. @SuppressLint("InvalidWakeLockTag")
  99. public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  100. View root = inflater.inflate(R.layout.fragment_areas, container, false);
  101. //construct a FusedLocationProviderClient.
  102. mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getActivity());
  103. //get permissions
  104. getLocationPermission();
  105. getReadStoragePermission();
  106. //instantiate area lists
  107. areaList = (ListView) root.findViewById(R.id.areaListView);
  108. allAreas = new ArrayList<>();
  109. areaReferences = new ArrayList<>();
  110. PowerManager powerManager = (PowerManager) getContext().getSystemService(POWER_SERVICE);
  111. wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
  112. gps = new LocationService(getContext());
  113. //instantiate add button
  114. final FloatingActionButton fab = root.findViewById(R.id.fab_areas);
  115. fab.setOnClickListener(new View.OnClickListener() {
  116. @Override
  117. public void onClick(View view) {
  118. //permissions
  119. getLocationPermission();
  120. getWriteStoragePPermission();
  121. //get saved areas
  122. areaReferences = readAreaReferencesFromPreferences();
  123. allAreas = loadAreasFromPreferences();
  124. instantiateAreasList();
  125. AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
  126. newArea = new OwnArea();
  127. final View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.area_input, (ViewGroup) getView(), false);
  128. builder.setView(viewInflated);
  129. final Button startTracking = viewInflated.findViewById(R.id.areaStartTracking);
  130. final Button stopTracking = viewInflated.findViewById(R.id.areaStopTracking);
  131. startTracking.setOnClickListener(new View.OnClickListener() {
  132. @Override
  133. public void onClick(View view) {
  134. //start tracking
  135. startLocationTracking();
  136. startTracking.setVisibility(View.INVISIBLE);
  137. stopTracking.setVisibility(View.VISIBLE);
  138. }
  139. });
  140. stopTracking.setOnClickListener(new View.OnClickListener() {
  141. @Override
  142. public void onClick(View view) {
  143. //stop tracking
  144. newPositions = gps.getPositions();
  145. if (BuildConfig.DEBUG)
  146. {
  147. Log.d(TAG, "Received locations: " + newPositions.size());
  148. }
  149. newArea.setLocations(newPositions);
  150. wakeLock.release();
  151. startTracking.setVisibility(View.VISIBLE);
  152. stopTracking.setVisibility(View.INVISIBLE);
  153. }
  154. });
  155. builder.setPositiveButton("Bestätigen", new DialogInterface.OnClickListener() {
  156. @Override
  157. public void onClick(DialogInterface dialog, int which) {
  158. final TextView titleView = viewInflated.findViewById(R.id.areaTitleUserInput);
  159. final TextView noticeView = viewInflated.findViewById(R.id.areaNoticeUserInput);
  160. if (BuildConfig.DEBUG) {
  161. Log.d(TAG, "new title: " + titleView.getText());
  162. }
  163. if (titleView.getText().length()>0)
  164. {
  165. //save user input
  166. newArea.setTitle(String.valueOf(titleView.getText()));
  167. newArea.setNotice(String.valueOf(noticeView.getText()));
  168. boolean result = allAreas.add(newArea);
  169. if (BuildConfig.DEBUG)
  170. {
  171. Log.d(TAG, "new Task: " + newArea.toString());
  172. Log.d(TAG, "add new task result: " + result);
  173. }
  174. //stop tracking
  175. //wakeLock.release();
  176. //save new area
  177. allAreas.add(newArea);
  178. writeAreaToExternalStorage(newArea);
  179. //actuate list
  180. instantiateAreasList();
  181. dialog.dismiss();
  182. //confirm added task
  183. Toast toast = Toast.makeText(getActivity(), "Grundstück hinzugefügt!", Toast.LENGTH_SHORT);
  184. TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
  185. if( v != null)
  186. {
  187. //text align center
  188. v.setGravity(Gravity.CENTER);
  189. }
  190. toast.show();
  191. }
  192. else
  193. {
  194. //title needed
  195. Toast toast = Toast.makeText(getActivity(), "Grundstückstitel fehlt!", Toast.LENGTH_SHORT);
  196. TextView v = (TextView) toast.getView().findViewById(android.R.id.message);
  197. if( v != null)
  198. {
  199. //text align center
  200. v.setGravity(Gravity.CENTER);
  201. }
  202. toast.show();
  203. }
  204. }
  205. });
  206. builder.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
  207. @Override
  208. public void onClick(DialogInterface dialog, int which) {
  209. dialog.cancel();
  210. }
  211. });
  212. builder.show();
  213. }});
  214. return root;
  215. }
  216. /**
  217. * Get all stored areas and save them temporary.
  218. */
  219. public void instantiateAreasList()
  220. {
  221. final AreaAdapter adapter = new AreaAdapter(getActivity().getApplicationContext(), allAreas);
  222. areaList.setAdapter(adapter);
  223. //initialise onClickListeners
  224. areaList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  225. @Override
  226. public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
  227. //for (int j = 0; j < adapterView.getChildCount(); j++)
  228. //adapterView.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);
  229. // change the background color of the selected element
  230. //view.setBackgroundColor(Color.LTGRAY);
  231. //adapterView.setSelection(i);
  232. }});
  233. }
  234. @Override
  235. public void onPause() {
  236. //save area references to shared preferences
  237. emptyPreferencesAndSaveEpiColorsToPreferences();
  238. super.onPause();
  239. }
  240. /**
  241. * Get OwnAreas from a JSONString.
  242. * @return
  243. */
  244. private List<OwnArea> loadAreasFromPreferences()
  245. {
  246. List<OwnArea> areas = new ArrayList<>();
  247. for (AreaReference reference: areaReferences)
  248. {
  249. String jsonString = readAreaFromExternalStorage(reference.getPath());
  250. areas.add(new OwnArea(jsonString));
  251. }
  252. return areas;
  253. }
  254. /**
  255. * Save OwnArea object in textfile on external storage.
  256. *
  257. * @param newArea OwnArea object to write to file.
  258. * @return
  259. */
  260. private String writeAreaToExternalStorage(OwnArea newArea){
  261. // Find the root of the external storage.
  262. File root = android.os.Environment.getExternalStorageDirectory();
  263. //create file if it does not exist
  264. File path = new File (root.getAbsolutePath() + "meinWald" + File.pathSeparator + "areas");
  265. if(!path.exists()){
  266. path.mkdirs();
  267. }
  268. File file = new File(path, newArea.getId() + ".txt");
  269. //open file and write to it
  270. try {
  271. FileOutputStream f = new FileOutputStream(file);
  272. PrintWriter pw = new PrintWriter(f);
  273. pw.print(areaToString(newArea));
  274. pw.close();
  275. f.close();
  276. } catch (FileNotFoundException e) {
  277. e.printStackTrace();
  278. } catch (IOException e) {
  279. e.printStackTrace();
  280. }
  281. return file.getPath();
  282. }
  283. /**
  284. * Read OwnArea from file in external storage and return as a string.
  285. *
  286. * @param path File path where the OwnArea is saved.
  287. * @return
  288. */
  289. private String readAreaFromExternalStorage(String path)
  290. {
  291. //Get the text file
  292. File file = new File(path);
  293. //Read text from file
  294. StringBuilder text = new StringBuilder();
  295. try {
  296. BufferedReader br = new BufferedReader(new FileReader(file));
  297. String line;
  298. while ((line = br.readLine()) != null) {
  299. text.append(line);
  300. }
  301. br.close();
  302. }
  303. catch (IOException e) {
  304. e.printStackTrace();
  305. }
  306. return text.toString();
  307. }
  308. /**
  309. * Converts an OwnArea object into a JSONString object.
  310. *
  311. * @param area Area to convert into JSONString
  312. * @return
  313. */
  314. public String areaToString(OwnArea area)
  315. {
  316. JSONObject areaObject = newArea.toJSONObject();
  317. return areaObject.toString();
  318. }
  319. /**
  320. * Reads areaReferences saved in preferences as jsonStrings
  321. *
  322. * @return list of epiColorDtos
  323. */
  324. private List<AreaReference> readAreaReferencesFromPreferences() {
  325. List<AreaReference> areas = new ArrayList<>();
  326. try {
  327. String jsonString = PreferenceManager.getDefaultSharedPreferences(getContext()).getString(KEY_AREA_REFERENCES, "error");
  328. if(!"error".equalsIgnoreCase(jsonString)) {
  329. JSONArray jsonObjects = new JSONArray(jsonString);
  330. for (int i = 0; i<jsonObjects.length();i++) {
  331. areaReferences.add(new AreaReference(jsonObjects.getJSONObject(i)));
  332. }
  333. }
  334. } catch (JSONException e) {
  335. if (BuildConfig.DEBUG) {
  336. Log.e(TAG, "Error while parsing epicolors as jsonObjects from preferences");
  337. e.printStackTrace();
  338. }
  339. }
  340. return areas;
  341. }
  342. /**
  343. * Saves epicolors to preferences
  344. */
  345. private void emptyPreferencesAndSaveEpiColorsToPreferences()
  346. {
  347. if (!areaReferences.isEmpty()) {
  348. if (BuildConfig.DEBUG) {
  349. Log.d(TAG, "areaReferences not empty");
  350. }
  351. PreferenceManager.getDefaultSharedPreferences(getContext()).edit().remove(KEY_AREA_REFERENCES).commit();
  352. JSONArray writeObjects = new JSONArray();
  353. for (AreaReference reference: areaReferences) {
  354. JSONObject object = reference.toJSONObject();
  355. writeObjects.put(object);
  356. if (BuildConfig.DEBUG) {
  357. Log.d("Color is ", object.toString());
  358. }
  359. }
  360. PreferenceManager.getDefaultSharedPreferences(getContext()).edit().putString(KEY_AREA_REFERENCES, writeObjects.toString()).commit();
  361. }
  362. }
  363. /**
  364. * DOCU ME!
  365. * TOOD: What are grant results etc for?
  366. * @param requestCode
  367. * @param permissions
  368. * @param grantResults
  369. */
  370. @Override
  371. public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
  372. {
  373. if (BuildConfig.DEBUG) {
  374. Log.d(TAG, "onRequestPermissionResult Code: " + requestCode);
  375. }
  376. mLocationPermissionGranted = false;
  377. switch (requestCode) {
  378. case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
  379. // If request is cancelled, the result arrays are empty.
  380. if (grantResults.length > 0
  381. && grantResults[0] == PackageManager.PERMISSION_GRANTED)
  382. {
  383. mLocationPermissionGranted = true;
  384. }
  385. }
  386. case MY_CAMERA_PERMISSION_CODE: {
  387. if (grantResults.length > 0
  388. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  389. mCameraPermissionGranted = true;
  390. }
  391. }
  392. case READ_EXTERNAL_STORAGE_CODE: {
  393. if (grantResults.length > 0
  394. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  395. mReadStorageGranted = true;
  396. }
  397. }
  398. case WRITE_EXTERNAL_STORAGE_CODE: {
  399. if (grantResults.length > 0
  400. && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  401. mWriteStorageGranted = true;
  402. }
  403. }
  404. }
  405. }
  406. public void getLocation(){
  407. wakeLock.acquire();
  408. gps = new LocationService(getContext());
  409. }
  410. public void startLocationTracking(){
  411. final Runnable runnable= new Runnable() {
  412. public void run() {
  413. // do stuff here
  414. getLocation();
  415. }
  416. };
  417. runnable.run();
  418. }
  419. /**
  420. * Request location permission, so that we can get the location of the device.
  421. * The result of the permission request is handled by a callback,
  422. * onRequestPermissionsResult.
  423. *
  424. */
  425. private void getLocationPermission() {
  426. if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
  427. android.Manifest.permission.ACCESS_FINE_LOCATION)
  428. == PackageManager.PERMISSION_GRANTED) {
  429. mLocationPermissionGranted = true;
  430. } else {
  431. ActivityCompat.requestPermissions(getActivity(),
  432. new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
  433. PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
  434. }
  435. }
  436. /**
  437. * Request read external storage permission, so that we can get saved images from external storage.
  438. * The result of the permission request is handled by a callback,
  439. * onRequestPermissionsResult.
  440. *
  441. */
  442. private void getReadStoragePermission() {
  443. if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
  444. Manifest.permission.READ_EXTERNAL_STORAGE)
  445. == PackageManager.PERMISSION_GRANTED) {
  446. mReadStorageGranted = true;
  447. } else {
  448. ActivityCompat.requestPermissions(getActivity(),
  449. new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
  450. READ_EXTERNAL_STORAGE_CODE);
  451. }
  452. }
  453. /**
  454. * Request read external storage permission, so that we can get saved images from external storage.
  455. * The result of the permission request is handled by a callback,
  456. * onRequestPermissionsResult.
  457. *
  458. */
  459. private void getWriteStoragePPermission() {
  460. if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(),
  461. Manifest.permission.WRITE_EXTERNAL_STORAGE)
  462. == PackageManager.PERMISSION_GRANTED) {
  463. mWriteStorageGranted = true;
  464. } else {
  465. ActivityCompat.requestPermissions(getActivity(),
  466. new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
  467. WRITE_EXTERNAL_STORAGE_CODE);
  468. }
  469. }
  470. }