ActivityFutureLayout.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. package com.ivalentin.margolariak;
  2. import android.annotation.SuppressLint;
  3. import android.app.Dialog;
  4. import android.content.DialogInterface;
  5. import android.content.pm.PackageManager;
  6. import android.database.Cursor;
  7. import android.database.sqlite.SQLiteDatabase;
  8. import android.graphics.Bitmap;
  9. import android.graphics.BitmapFactory;
  10. import android.os.Build;
  11. import android.os.Bundle;
  12. import android.app.Fragment;
  13. import android.support.v4.app.ActivityCompat;
  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.view.Window;
  20. import android.view.WindowManager;
  21. import android.webkit.WebView;
  22. import android.widget.Button;
  23. import android.widget.ImageView;
  24. import android.widget.LinearLayout;
  25. import android.widget.TextView;
  26. import com.google.android.gms.maps.CameraUpdate;
  27. import com.google.android.gms.maps.CameraUpdateFactory;
  28. import com.google.android.gms.maps.GoogleMap;
  29. import com.google.android.gms.maps.MapView;
  30. import com.google.android.gms.maps.MapsInitializer;
  31. import com.google.android.gms.maps.OnMapReadyCallback;
  32. import com.google.android.gms.maps.model.LatLng;
  33. import com.google.android.gms.maps.model.MarkerOptions;
  34. import java.io.File;
  35. import java.text.ParseException;
  36. import java.text.SimpleDateFormat;
  37. import java.util.Calendar;
  38. import java.util.Date;
  39. import java.util.Locale;
  40. /**
  41. * Fragment to display upcoming activities.
  42. * The id of the activity to display is passes in a bundle.
  43. * Everything is done on the onCreateView method.
  44. *
  45. * @author Iñigo Valentin
  46. *
  47. * @see Fragment
  48. *
  49. */
  50. public class ActivityFutureLayout extends Fragment implements OnMapReadyCallback {
  51. //Map stuff for the dialog
  52. private MapView mapView;
  53. private GoogleMap map;
  54. private LatLng location;
  55. private String markerName = "";
  56. private final Bundle bund = null;
  57. private View v;
  58. @SuppressWarnings("ResultOfMethodCallIgnored")
  59. @SuppressLint("InflateParams")
  60. @Override
  61. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
  62. //Load the layout
  63. View view = inflater.inflate(R.layout.fragment_layout_activity_future, null);
  64. //Get bundled id
  65. Bundle bundle = this.getArguments();
  66. int id = bundle.getInt("activity", -1);
  67. if (id == -1){
  68. Log.e("Activity error", "No such activity: " + id);
  69. this.getActivity().onBackPressed();
  70. }
  71. //Get data from database
  72. SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
  73. final Cursor cursor;
  74. String lang = GM.getLang();
  75. cursor = db.rawQuery("SELECT id, title_" + lang+ " AS title, text_" + lang + " AS text, date, city, price, permalink FROM activity WHERE id = " + id + ";", null);
  76. cursor.moveToFirst();
  77. //Get display elements
  78. ImageView images[] = new ImageView[5];
  79. images[0] = (ImageView) view.findViewById(R.id.iv_activity_future_0);
  80. images[1] = (ImageView) view.findViewById(R.id.iv_activity_future_1);
  81. images[2] = (ImageView) view.findViewById(R.id.iv_activity_future_2);
  82. images[3] = (ImageView) view.findViewById(R.id.iv_activity_future_3);
  83. images[4] = (ImageView) view.findViewById(R.id.iv_activity_future_4);
  84. TextView tvTitle = (TextView) view.findViewById(R.id.tv_activity_future_title);
  85. TextView tvDate = (TextView) view.findViewById(R.id.tv_activity_future_date);
  86. TextView tvCity = (TextView) view.findViewById(R.id.tv_activity_future_city);
  87. TextView tvPrice = (TextView) view.findViewById(R.id.tv_activity_future_price);
  88. WebView wvText = (WebView) view.findViewById(R.id.wv_activity_future_text);
  89. //Set fields
  90. tvTitle.setText(cursor.getString(1));
  91. ((MainActivity) getActivity()).setSectionTitle(cursor.getString(1));
  92. ((MainActivity) getActivity()).setShareLink(String.format(getString(R.string.share_with_title), cursor.getString(1)), GM.SHARE.ACTIVITIES + cursor.getString(6));
  93. if (Build.VERSION.SDK_INT >= 19) {
  94. wvText.setLayerType(View.LAYER_TYPE_HARDWARE, null);
  95. }
  96. else {
  97. wvText.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
  98. }
  99. wvText.loadDataWithBaseURL(null, cursor.getString(2), "text/html", "utf-8", null);
  100. //wvText.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
  101. tvDate.setText(GM.formatDate(cursor.getString(3) + " 00:00:00", lang, false));
  102. tvPrice.setText(String.format(getString(R.string.price), cursor.getInt(5)));
  103. tvCity.setText(cursor.getString(4));
  104. //Get images
  105. Cursor imageCursor = db.rawQuery("SELECT image, idx FROM activity_image WHERE activity = " + id + " ORDER BY idx LIMIT 5;", null);
  106. int i = 0;
  107. String image;
  108. while (imageCursor.moveToNext()) {
  109. image = imageCursor.getString(0);
  110. //Check if image exists
  111. File f;
  112. f = new File(this.getActivity().getFilesDir().toString() + "/img/actividades/preview/" + image);
  113. if (f.exists()){
  114. //If the image exists, set it.
  115. Bitmap myBitmap = BitmapFactory.decodeFile(this.getActivity().getFilesDir().toString() + "/img/actividades/preview/" + image);
  116. images[i].setImageBitmap(myBitmap);
  117. }
  118. else {
  119. //If not, create directories and download asynchronously
  120. File fpath;
  121. fpath = new File(this.getActivity().getFilesDir().toString() + "/img/actividades/preview/");
  122. //noinspection ResultOfMethodCallIgnored
  123. fpath.mkdirs();
  124. new DownloadImage(GM.API.SERVER + "/img/actividades/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/actividades/preview/" + image, images[i], GM.IMG.SIZE.PREVIEW).execute();
  125. }
  126. images[i].setVisibility(View.VISIBLE);
  127. i ++;
  128. }
  129. imageCursor.close();
  130. cursor.close();
  131. //Get itinerary
  132. Cursor cursorItinerary = db.rawQuery("SELECT activity_itinerary.id, activity_itinerary.name_" + lang + " AS name, description_" + lang + " AS description, start, place.name_" + lang + " AS placename, address_" + lang + " AS address, lat, lon FROM activity_itinerary, place WHERE activity_itinerary.place = place.id AND activity = " + id + ";", null);
  133. if (cursorItinerary.getCount() <= 0){
  134. LinearLayout sch = (LinearLayout) view.findViewById(R.id.ll_activity_future_schedule);
  135. sch.setVisibility(View.GONE);
  136. }
  137. else{
  138. LinearLayout list = (LinearLayout) view.findViewById(R.id.ll_activity_future_schedule_list);
  139. LinearLayout entry;
  140. LayoutInflater factory = LayoutInflater.from(getActivity());
  141. while (cursorItinerary.moveToNext()) {
  142. //Create a new row
  143. entry = (LinearLayout) factory.inflate(R.layout.row_activity_schedule, null);
  144. //Set time
  145. TextView tvSchTime = (TextView) entry.findViewById(R.id.tv_row_activity_itinerary_time);
  146. tvSchTime.setText(cursorItinerary.getString(3).substring(11, 16));
  147. //Set title
  148. TextView tvSchTitle = (TextView) entry.findViewById(R.id.tv_row_activity_itinerary_title);
  149. tvSchTitle.setText(cursorItinerary.getString(1));
  150. //Set Id
  151. TextView tvSchId = (TextView) entry.findViewById(R.id.tv_row_activity_itinerary_id);
  152. tvSchId.setText(cursorItinerary.getString(0));
  153. //Set description
  154. TextView tvSchDescription = (TextView) entry.findViewById(R.id.tv_row_activity_itinerary_description);
  155. if (!cursorItinerary.getString(1).equals(cursorItinerary.getString(2))){
  156. tvSchDescription.setVisibility(View.GONE);
  157. }
  158. else {
  159. tvSchTitle.setText(cursorItinerary.getString(2));
  160. }
  161. //Set place
  162. TextView tvSchPlace = (TextView) entry.findViewById(R.id.tv_row_activity_itinerary_place);
  163. tvSchPlace.setText(cursorItinerary.getString(4));
  164. //Set address
  165. TextView tvSchAddress = (TextView) entry.findViewById(R.id.tv_row_activity_itinerary_address);
  166. if (!cursorItinerary.getString(4).equals(cursorItinerary.getString(5))){
  167. tvSchAddress.setVisibility(View.GONE);
  168. }
  169. else {
  170. tvSchAddress.setText(cursorItinerary.getString(5));
  171. }
  172. //Set click listener
  173. entry.setOnClickListener(new View.OnClickListener() {
  174. @Override
  175. public void onClick(View v) {
  176. TextView tvId = (TextView) v.findViewById(R.id.tv_row_activity_itinerary_id);
  177. int id = Integer.parseInt(tvId.getText().toString());
  178. showDialog(id);
  179. }
  180. });
  181. list.addView(entry);
  182. }
  183. }
  184. cursorItinerary.close();
  185. db.close();
  186. v = view;
  187. return view;
  188. }
  189. /**
  190. * Shows a dialog with info about the selected event.
  191. *
  192. * @param id The event id
  193. */
  194. @SuppressWarnings("ConstantConditions")
  195. private void showDialog(final int id){
  196. //Create the dialog
  197. final Dialog dialog = new Dialog(getActivity());
  198. //Set up dialog window
  199. dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
  200. dialog.setContentView(R.layout.dialog_schedule);
  201. //Date formatters
  202. SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
  203. SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd-", Locale.US);
  204. SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.US);
  205. //Set the custom dialog components - text, image and button
  206. TextView tvTitle = (TextView) dialog.findViewById(R.id.tv_dialog_schedule_title);
  207. TextView tvDescription = (TextView) dialog.findViewById(R.id.tv_dialog_schedule_description);
  208. TextView tvHost = (TextView) dialog.findViewById(R.id.tv_dialog_schedule_host);
  209. TextView tvDate = (TextView) dialog.findViewById(R.id.tv_dialog_schedule_date);
  210. TextView tvTime = (TextView) dialog.findViewById(R.id.tv_dialog_schedule_time);
  211. TextView tvPlace = (TextView) dialog.findViewById(R.id.tv_dialog_schedule_place);
  212. TextView tvAddress = (TextView) dialog.findViewById(R.id.tv_dialog_schedule_address);
  213. Button btClose = (Button) dialog.findViewById(R.id.bt_schedule_close);
  214. //Get info about the event
  215. SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
  216. String lang = GM.getLang();
  217. Cursor cursor = db.rawQuery("SELECT activity_itinerary.id, activity_itinerary.name_" + lang + ", description_" + lang + ", place, start, end, place.name_" + lang + ", address_" + lang + ", lat, lon FROM activity_itinerary, place WHERE place = place.id AND activity_itinerary.id = " + id + ";", null);
  218. if (cursor.getCount() > 0){
  219. cursor.moveToNext();
  220. //Set title
  221. tvTitle.setText(cursor.getString(1));
  222. markerName = cursor.getString(1);
  223. //Set description
  224. tvDescription.setText(cursor.getString(2));
  225. //Set host field hidden
  226. tvHost.setVisibility(View.GONE);
  227. //Set date
  228. try{
  229. Date day = dateFormat.parse(cursor.getString(4));
  230. Date date = new Date();
  231. //If the event is today, show "Today" instead of the date
  232. if (dayFormat.format(day).equals(dayFormat.format(date)))
  233. tvDate.setText(dialog.getContext().getString(R.string.today));
  234. else{
  235. Calendar cal = Calendar.getInstance();
  236. cal.setTime(date);
  237. cal.add(Calendar.HOUR_OF_DAY, 24);
  238. //If the event is tomorrow, show "Tomorrow" instead of the date
  239. if (dayFormat.format(cal.getTime()).equals(dayFormat.format(date))){
  240. tvDate.setText(dialog.getContext().getString(R.string.tomorrow));
  241. }
  242. //Else, show the date
  243. else{
  244. SimpleDateFormat printFormat = new SimpleDateFormat("dd MMMM", Locale.US);
  245. tvDate.setText(printFormat.format(day));
  246. }
  247. }
  248. }
  249. catch (Exception ex){
  250. Log.e("Error parsing date", ex.toString());
  251. }
  252. //Set time
  253. try{
  254. if (cursor.getString(5) == null || cursor.getString(5).length() == 0) {
  255. tvTime.setText(timeFormat.format(dateFormat.parse(cursor.getString(4))));
  256. }
  257. else {
  258. String time = timeFormat.format(dateFormat.parse(cursor.getString(4))) + " - " + timeFormat.format(dateFormat.parse(cursor.getString(5)));
  259. tvTime.setText(time);
  260. }
  261. }
  262. catch (ParseException ex){
  263. Log.e("Error parsing time", ex.toString());
  264. }
  265. //Set the place
  266. tvPlace.setText(cursor.getString(6));
  267. tvAddress.setText(cursor.getString(7));
  268. //Set up map
  269. location = new LatLng(Double.parseDouble(cursor.getString(8)), Double.parseDouble(cursor.getString(9)));
  270. mapView = (MapView) dialog.findViewById(R.id.mv_dialog_schedule_map);
  271. mapView.onCreate(bund);
  272. //Close the db connection
  273. cursor.close();
  274. db.close();
  275. //Set close button
  276. btClose.setOnClickListener(new View.OnClickListener() {
  277. @Override
  278. public void onClick(View v) {
  279. dialog.dismiss();
  280. }
  281. });
  282. //Actions to take when the dialog is cancelled
  283. dialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
  284. @Override
  285. public void onCancel(DialogInterface dialog) {
  286. if (map != null) {
  287. if (!(ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
  288. map.setMyLocationEnabled(false);
  289. }
  290. }
  291. if (mapView != null){
  292. mapView.onResume();
  293. mapView.onDestroy();
  294. }
  295. }
  296. });
  297. //Show the dialog
  298. WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
  299. lp.copyFrom(dialog.getWindow().getAttributes());
  300. lp.width = WindowManager.LayoutParams.MATCH_PARENT;
  301. lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
  302. lp.gravity = Gravity.CENTER;
  303. lp.dimAmount = 0.0f;
  304. dialog.getWindow().setAttributes(lp);
  305. //Show dialog
  306. dialog.show();
  307. //Start the map
  308. startMap();
  309. mapView.onResume();
  310. dialog.setOnShowListener(new DialogInterface.OnShowListener(){
  311. @Override
  312. public void onShow(DialogInterface dialog) {
  313. // Gets to GoogleMap from the MapView and does initialization stuff
  314. startMap();
  315. }
  316. });
  317. }
  318. }
  319. /**
  320. * Starts the map in the dialog.
  321. */
  322. private void startMap(){
  323. mapView.getMapAsync(this);
  324. }
  325. /**
  326. * Called when the fragment is brought back into the foreground.
  327. * Resumes the map and the location manager.
  328. *
  329. * @see android.app.Fragment#onResume()
  330. */
  331. @Override
  332. public void onResume() {
  333. if (mapView != null)
  334. mapView.onResume();
  335. if (map != null) {
  336. if (!(ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
  337. map.setMyLocationEnabled(true);
  338. }
  339. }
  340. super.onResume();
  341. }
  342. /**
  343. * Called when the fragment is destroyed.
  344. * Finishes the map.
  345. *
  346. * @see android.app.Fragment#onDestroy()
  347. */
  348. @Override
  349. public void onDestroy() {
  350. super.onDestroy();
  351. if (map != null) {
  352. if (!(ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
  353. map.setMyLocationEnabled(false);
  354. }
  355. }
  356. if (mapView != null){
  357. mapView.onResume();
  358. mapView.onDestroy();
  359. }
  360. }
  361. /**
  362. * Called when the fragment is paused.
  363. * Finishes the map.
  364. *
  365. * @see android.app.Fragment#onPause()
  366. */
  367. @Override
  368. public void onPause() {
  369. super.onDestroy();
  370. if (map != null) {
  371. if (!(ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
  372. map.setMyLocationEnabled(false);
  373. }
  374. }
  375. if (mapView != null){
  376. mapView.onPause();
  377. }
  378. }
  379. /**
  380. * Called in a situation of low memory.
  381. * Lets the map handle this situation.
  382. *
  383. * @see android.app.Fragment#onLowMemory()
  384. */
  385. @Override
  386. public void onLowMemory() {
  387. super.onLowMemory();
  388. if (mapView != null){
  389. if (!(ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
  390. mapView.onResume();
  391. }
  392. mapView.onLowMemory();
  393. }
  394. }
  395. /**
  396. * Called when the map is ready to be displayed.
  397. * Sets the map options and a marker for the map.
  398. *
  399. * @param googleMap The map to be shown
  400. *
  401. * @see com.google.android.gms.maps.OnMapReadyCallback#onMapReady(com.google.android.gms.maps.GoogleMap)
  402. */
  403. @Override
  404. public void onMapReady(GoogleMap googleMap) {
  405. this.map = googleMap;
  406. map.getUiSettings().setMyLocationButtonEnabled(false);
  407. if (!(ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
  408. map.setMyLocationEnabled(true);
  409. }
  410. // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
  411. try {
  412. MapsInitializer.initialize(this.getActivity());
  413. CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(location, 14);
  414. map.animateCamera(cameraUpdate);
  415. } catch (Exception e) {
  416. Log.e("Error initializing maps", e.toString());
  417. }
  418. //Set GM marker
  419. MarkerOptions mo = new MarkerOptions();
  420. mo.title(markerName);
  421. mo.position(location);
  422. map.addMarker(mo);
  423. }
  424. }