Ver Fonte

Merge branch 'master' into newui

seavenois há 9 anos atrás
pai
commit
43739f75c2

+ 1 - 1
app/build.gradle

@@ -19,7 +19,7 @@ android {
     }
 
     dexOptions {
-        incremental = true
+        //incremental = true
         preDexLibraries = false
         javaMaxHeapSize "2g"
     }

+ 3 - 3
app/src/main/java/com/ivalentin/margolariak/ActivityFutureLayout.java

@@ -78,7 +78,7 @@ public class ActivityFutureLayout extends Fragment implements OnMapReadyCallback
         }
 
         //Get data from database
-        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
         final Cursor cursor;
 		String lang = GM.getLang();
 
@@ -135,7 +135,7 @@ public class ActivityFutureLayout extends Fragment implements OnMapReadyCallback
                 fpath = new File(this.getActivity().getFilesDir().toString() + "/img/actividades/preview/");
                 //noinspection ResultOfMethodCallIgnored
                 fpath.mkdirs();
-                new DownloadImage(GM.SERVER + "/img/actividades/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/actividades/preview/" + image, images[i], GM.IMG_PREVIEW).execute();
+                new DownloadImage(GM.API.SERVER + "/img/actividades/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/actividades/preview/" + image, images[i], GM.IMG.SIZE.PREVIEW).execute();
             }
             images[i].setVisibility(View.VISIBLE);
             i ++;
@@ -244,7 +244,7 @@ public class ActivityFutureLayout extends Fragment implements OnMapReadyCallback
         Button btClose = (Button) dialog.findViewById(R.id.bt_schedule_close);
 
         //Get info about the event
-        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
         String lang = GM.getLang();
         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);
         if (cursor.getCount() > 0){

+ 3 - 3
app/src/main/java/com/ivalentin/margolariak/ActivityLayout.java

@@ -72,7 +72,7 @@ public class ActivityLayout extends Fragment{
         //An inflater
         LayoutInflater factory = LayoutInflater.from(getActivity());
 
-        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
         final Cursor cursor;
         String lang = GM.getLang();
 
@@ -137,7 +137,7 @@ public class ActivityLayout extends Fragment{
                         File fpath;
                         fpath = new File(this.getActivity().getFilesDir().toString() + "/img/actividades/miniature/");
                         fpath.mkdirs();
-                        new DownloadImage(GM.SERVER + "/img/actividades/miniature/" + image, this.getActivity().getFilesDir().toString() + "/img/actividades/miniature/" + image, iv, GM.IMG_MINIATURE).execute();
+                        new DownloadImage(GM.API.SERVER + "/img/actividades/miniature/" + image, this.getActivity().getFilesDir().toString() + "/img/actividades/miniature/" + image, iv, GM.IMG.SIZE.MINIATURE).execute();
                     }
                 }
                 cursorImage.close();
@@ -231,7 +231,7 @@ public class ActivityLayout extends Fragment{
                     File fpath;
                     fpath = new File(this.getActivity().getFilesDir().toString() + "/img/actividades/miniature/");
                     fpath.mkdirs();
-                    new DownloadImage(GM.SERVER + "/img/actividades/miniature/" + image, this.getActivity().getFilesDir().toString() + "/img/actividades/miniature/" + image, iv, GM.IMG_MINIATURE).execute();
+                    new DownloadImage(GM.API.SERVER + "/img/actividades/miniature/" + image, this.getActivity().getFilesDir().toString() + "/img/actividades/miniature/" + image, iv, GM.IMG.SIZE.MINIATURE).execute();
                 }
             }
             cursorImage.close();

+ 2 - 2
app/src/main/java/com/ivalentin/margolariak/ActivityPastLayout.java

@@ -47,7 +47,7 @@ public class ActivityPastLayout extends Fragment {
         }
 
         //Get data from database
-        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
         final Cursor cursor;
         String lang = GM.getLang();
         cursor = db.rawQuery("SELECT id, title_" + lang+ " AS title, text_" + lang + " AS text, date, city, after_" + lang + " AS after FROM activity WHERE id = " + id + ";", null);
@@ -107,7 +107,7 @@ public class ActivityPastLayout extends Fragment {
                 File fpath;
                 fpath = new File(this.getActivity().getFilesDir().toString() + "/img/actividades/preview/");
                 fpath.mkdirs();
-                new DownloadImage(GM.SERVER + "/img/actividades/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/actividades/preview/" + image, images[i], GM.IMG_PREVIEW).execute();
+                new DownloadImage(GM.API.SERVER + "/img/actividades/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/actividades/preview/" + image, images[i], GM.IMG.SIZE.PREVIEW).execute();
              }
             images[i].setVisibility(View.VISIBLE);
             i ++;

+ 67 - 53
app/src/main/java/com/ivalentin/margolariak/AlarmReceiver.java

@@ -1,5 +1,7 @@
 package com.ivalentin.margolariak;
 
+//TODO: This doesn't work. Revise once the notification API is ready
+
 import android.app.AlarmManager;
 import android.app.NotificationManager;
 import android.app.PendingIntent;
@@ -8,6 +10,8 @@ import android.content.Context;
 import android.content.Intent;
 import android.content.SharedPreferences;
 import android.content.pm.PackageManager;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
 import android.graphics.BitmapFactory;
 import android.media.RingtoneManager;
 import android.support.v4.app.NotificationCompat;
@@ -51,7 +55,7 @@ public class AlarmReceiver extends BroadcastReceiver {
 			//Get the file
 			try{
 				fu = new FetchURL();
-				fu.Run(GM.SERVER + "/app/notifications.php");
+				fu.Run(GM.API.SERVER + "/app/notifications.php");
 				Log.d("Alarm", "Fetched notifications");
 
 				//Parse info
@@ -64,57 +68,67 @@ public class AlarmReceiver extends BroadcastReceiver {
 
 					//Is the notification seen already?
 					//TODO: Create a db table for this
-					if(!preferences.getBoolean(GM.NOTIFICATION_SEEN_ + id, false)){
-
-						String lang = GM.getLang();
-						String title = notification.substring(notification.indexOf("<title_" + lang + ">") + 10, notification.indexOf("</title_" + lang + ">"));
-						String text = notification.substring(notification.indexOf("<text_" + lang + ">") + 9, notification.indexOf("</text_" + lang + ">"));
-
-
-						//Get the notification manager ready
-						NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
-
-						//Variables to create intents for each notification
-						Intent resultIntent;
-						TaskStackBuilder stackBuilder;
-
-						//Send the notification.
-						NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
-								.setSmallIcon(R.drawable.ic_notification)
-								.setContentTitle(title)
-								.setAutoCancel(true)
-								.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher))
-								.setVibrate((new long[] { 400, 400, 400}))
-								.setColor(context.getResources().getColor(R.color.background_notification))
-								.setSubText(context.getString(R.string.app_name))
-								.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
-								.setContentText(text);
-
-						// Creates an intent for an Activity to be launched from the notification.
-						resultIntent = new Intent(context, MainActivity.class);
-						resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
-
-						//Set extras depending on type.
-						resultIntent.putExtra(GM.EXTRA_TEXT, text);
-						resultIntent.putExtra(GM.EXTRA_TITLE, title);
-						resultIntent.putExtra(GM.EXTRA_ACTION, action);
-
-						//Add the intent to the notification.
-						stackBuilder = TaskStackBuilder.create(context);
-						stackBuilder.addParentStack(MainActivity.class);
-
-						// Adds the Intent that starts the Activity to the top of the stack.
-						stackBuilder.addNextIntent(resultIntent);
-						PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
-						mBuilder.setContentIntent(resultPendingIntent);
-
-						//Actually send the notification.
-						mNotificationManager.notify(Integer.parseInt(id), mBuilder.build());
-
-						//Mark as notified
-						SharedPreferences.Editor editor = preferences.edit();
-						editor.putBoolean(GM.NOTIFICATION_SEEN_ + id, true);
-						editor.apply();
+
+					//Get data from database
+					SQLiteDatabase db = SQLiteDatabase.openDatabase(context.getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+					final Cursor cursor;
+					cursor = db.rawQuery("SELECT id, seen FROM notification WHERE id = " + id + ";", null);
+					if (cursor.getCount() == 0){
+
+					}
+					else {
+
+						if (cursor.getInt(1) == 0) {
+
+
+							String lang = GM.getLang();
+							String title = notification.substring(notification.indexOf("<title_" + lang + ">") + 10, notification.indexOf("</title_" + lang + ">"));
+							String text = notification.substring(notification.indexOf("<text_" + lang + ">") + 9, notification.indexOf("</text_" + lang + ">"));
+
+
+							//Get the notification manager ready
+							NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
+
+							//Variables to create intents for each notification
+							Intent resultIntent;
+							TaskStackBuilder stackBuilder;
+
+							//Send the notification.
+							NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
+									.setSmallIcon(R.drawable.ic_notification)
+									.setContentTitle(title)
+									.setAutoCancel(true)
+									.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher))
+									.setVibrate((new long[]{400, 400, 400}))
+									.setColor(context.getResources().getColor(R.color.background_notification))
+									.setSubText(context.getString(R.string.app_name))
+									.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
+									.setContentText(text);
+
+							// Creates an intent for an Activity to be launched from the notification.
+							resultIntent = new Intent(context, MainActivity.class);
+							resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
+
+							//Set extras depending on type.
+							resultIntent.putExtra(GM.EXTRA.TEXT, text);
+							resultIntent.putExtra(GM.EXTRA.TITLE, title);
+							resultIntent.putExtra(GM.EXTRA.ACTION, action);
+
+							//Add the intent to the notification.
+							stackBuilder = TaskStackBuilder.create(context);
+							stackBuilder.addParentStack(MainActivity.class);
+
+							// Adds the Intent that starts the Activity to the top of the stack.
+							stackBuilder.addNextIntent(resultIntent);
+							PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
+							mBuilder.setContentIntent(resultPendingIntent);
+
+							//Actually send the notification.
+							mNotificationManager.notify(Integer.parseInt(id), mBuilder.build());
+
+							//Mark as notified
+							db.execSQL("UPDATE notification SET seen = 1 WHERE id = " + id);
+						}
 					}
 				o = o.substring(o.indexOf("</notification>") + 15);
 				}
@@ -143,7 +157,7 @@ public class AlarmReceiver extends BroadcastReceiver {
 			PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
 
 			//Set the alarm cycle.
-			alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, GM.PERIOD_SYNC, GM.PERIOD_SYNC, alarmIntent);
+			alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, GM.PERIOD_SYNC.FESTIVALS, GM.PERIOD_SYNC.NORMAL, alarmIntent);
 
 			// Enable SampleBootReceiver to automatically restart the alarm when the device is rebooted.
 			ComponentName receiver = new ComponentName(context, BootReceiver.class);

+ 5 - 5
app/src/main/java/com/ivalentin/margolariak/AlbumLayout.java

@@ -49,7 +49,7 @@ public class AlbumLayout extends Fragment {
         }
 
         //Get data from database
-        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
         final Cursor cursor;
 		String lang = GM.getLang();
         cursor = db.rawQuery("SELECT id, title_" + lang + " AS title, description_" + lang + " AS description FROM album WHERE id = " + id + ";", null);
@@ -117,7 +117,7 @@ public class AlbumLayout extends Fragment {
                 //If the image exists, set it.
 				try{
 					File file = new File(this.getActivity().getFilesDir().toString() + "/img/galeria/preview/" + image);
-					ivLeft.setImageBitmap(GM.decodeSampledBitmapFromFile(file.getAbsolutePath(), GM.IMG_PREVIEW));
+					ivLeft.setImageBitmap(GM.decodeSampledBitmapFromFile(file.getAbsolutePath(), GM.IMG.SIZE.PREVIEW));
 				}
 				catch (Exception ex){
 					Log.e("Bitmap error", "Not loading image " + image + ": " + ex.toString());
@@ -128,7 +128,7 @@ public class AlbumLayout extends Fragment {
                 File fpath;
                 fpath = new File(this.getActivity().getFilesDir().toString() + "/img/galeria/preview/");
                 fpath.mkdirs();
-				new DownloadImage(GM.SERVER + "/img/galeria/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/galeria/preview/" + image, ivLeft, GM.IMG_PREVIEW).execute();
+				new DownloadImage(GM.API.SERVER + "/img/galeria/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/galeria/preview/" + image, ivLeft, GM.IMG.SIZE.PREVIEW).execute();
             }
 
 			//Count comments
@@ -187,7 +187,7 @@ public class AlbumLayout extends Fragment {
                     //If the image exists, set it.
 					try {
 						File file = new File(this.getActivity().getFilesDir().toString() + "/img/galeria/preview/" + image);
-						ivRight.setImageBitmap(GM.decodeSampledBitmapFromFile(file.getAbsolutePath(), GM.IMG_PREVIEW));
+						ivRight.setImageBitmap(GM.decodeSampledBitmapFromFile(file.getAbsolutePath(), GM.IMG.SIZE.PREVIEW));
 					}
 					catch (Exception ex){
 						Log.e("Bitmap error", "Not loading image " + image + ": " + ex.toString());
@@ -198,7 +198,7 @@ public class AlbumLayout extends Fragment {
                     File fpath;
                     fpath = new File(this.getActivity().getFilesDir().toString() + "/img/galeria/preview/");
                     fpath.mkdirs();
-					new DownloadImage(GM.SERVER + "/img/galeria/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/galeria/preview/" + image, ivRight, GM.IMG_PREVIEW).execute();
+					new DownloadImage(GM.API.SERVER + "/img/galeria/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/galeria/preview/" + image, ivRight, GM.IMG.SIZE.PREVIEW).execute();
                 }
 
 				//Count comments

+ 3 - 3
app/src/main/java/com/ivalentin/margolariak/BlogLayout.java

@@ -60,7 +60,7 @@ public class BlogLayout extends Fragment{
         ((MainActivity) getActivity()).setSectionTitle(view.getContext().getString(R.string.menu_blog));
 
         //Get total posts
-        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
         Cursor cursor = db.rawQuery("SELECT id FROM post;", null);
         totalPost = cursor.getCount();
         cursor.close();
@@ -142,7 +142,7 @@ public class BlogLayout extends Fragment{
         //An inflater
         LayoutInflater factory = LayoutInflater.from(getActivity());
 
-        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
         final Cursor cursor;
         String lang = GM.getLang();
 
@@ -201,7 +201,7 @@ public class BlogLayout extends Fragment{
                     File fpath;
                     fpath = new File(this.getActivity().getFilesDir().toString() + "/img/blog/miniature/");
                     fpath.mkdirs();
-                    new DownloadImage(GM.SERVER + "/img/blog/miniature/" + image, this.getActivity().getFilesDir().toString() + "/img/blog/miniature/" + image, iv, GM.IMG_MINIATURE).execute();
+                    new DownloadImage(GM.API.SERVER + "/img/blog/miniature/" + image, this.getActivity().getFilesDir().toString() + "/img/blog/miniature/" + image, iv, GM.IMG.SIZE.MINIATURE).execute();
                 }
             }
             else{

Diff do ficheiro suprimidas por serem muito extensas
+ 874 - 243
app/src/main/java/com/ivalentin/margolariak/GM.java


+ 2 - 2
app/src/main/java/com/ivalentin/margolariak/GalleryLayout.java

@@ -72,7 +72,7 @@ public class GalleryLayout extends Fragment{
         //An inflater
         LayoutInflater factory = LayoutInflater.from(getActivity());
 
-        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
         final Cursor cursor;
 		String lang = GM.getLang();
 
@@ -128,7 +128,7 @@ public class GalleryLayout extends Fragment{
                     File fpath;
                     fpath = new File(this.getActivity().getFilesDir().toString() + "/img/galeria/miniature/");
                     fpath.mkdirs();
-                    new DownloadImage(GM.SERVER + "/img/galeria/miniature/" + image, this.getActivity().getFilesDir().toString() + "/img/galeria/miniature/" + image, preview[i], GM.IMG_MINIATURE).execute();
+                    new DownloadImage(GM.API.SERVER + "/img/galeria/miniature/" + image, this.getActivity().getFilesDir().toString() + "/img/galeria/miniature/" + image, preview[i], GM.IMG.SIZE.MINIATURE).execute();
                 }
 
                 //Rotate the image

+ 50 - 67
app/src/main/java/com/ivalentin/margolariak/HomeLayout.java

@@ -8,6 +8,7 @@ import java.util.Locale;
 
 import android.annotation.SuppressLint;
 import android.Manifest;
+import android.app.Activity;
 import android.content.Context;
 import android.content.Intent;
 import android.content.SharedPreferences;
@@ -55,8 +56,6 @@ public class HomeLayout extends Fragment implements LocationListener {
 
 	@Override
 	public boolean onOptionsItemSelected(MenuItem item) {
-		// TODO Auto-generated method stub
-		Log.e("MENU", "FROM HOME");
 		return false;
 	}
 
@@ -81,42 +80,15 @@ public class HomeLayout extends Fragment implements LocationListener {
 		//Load the layout.
 		view = inflater.inflate(R.layout.fragment_layout_home, null);
 
-		//Variable to know if I need a location manager
-		//boolean requestLocation = false;
-
-		//Show tutorial if its the first time
-		/*final SharedPreferences preferences = view.getContext().getSharedPreferences(GM.PREF, Context.MODE_PRIVATE);
-		if (!preferences.getBoolean(GM.PREF_TUTORIAL, false)) {
-			final RelativeLayout llTutorial = (RelativeLayout) getActivity().findViewById(R.id.rl_tutorial);
-			llTutorial.setVisibility(View.VISIBLE);
-			llTutorial.setOnTouchListener(new View.OnTouchListener() {
-				@Override
-				public boolean onTouch(View v, MotionEvent event) {
-					return true;
-				}
-			});
-			Button btTutorial = (Button) getActivity().findViewById(R.id.bt_tutorial);
-			btTutorial.setOnClickListener(new OnClickListener() {
-				@Override
-				public void onClick(View v) {
-					llTutorial.setVisibility(View.GONE);
-					SharedPreferences.Editor editor = preferences.edit();
-					editor.putBoolean(GM.PREF_TUTORIAL, true);
-					editor.apply();
-				}
-			});
-		}*/
-
 		//Request location permissions if not set
 		if (ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
-			ActivityCompat.requestPermissions(this.getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, GM.PERMISSION_LOCATION);
+			ActivityCompat.requestPermissions(this.getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, GM.PERMISSION.LOCATION);
 		}
 
 		//Set Location manager
-		//TODO: Only do this if location is required
 		locationManager = (LocationManager) view.getContext().getSystemService(Context.LOCATION_SERVICE);
 		if (!(ActivityCompat.checkSelfPermission(view.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(view.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
-			locationManager.requestLocationUpdates(locationManager.getBestProvider(new Criteria(), true), GM.LOCATION_ACCURACY_TIME, GM.LOCATION_ACCURACY_SPACE, this);
+			locationManager.requestLocationUpdates(locationManager.getBestProvider(new Criteria(), true), GM.LOCATION.ACCURACY.TIME, GM.LOCATION.ACCURACY.SPACE, this);
 			onLocationChanged(locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER));
 		}
 
@@ -165,7 +137,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 			return count;
 		}
 
-		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
 		Calendar calendar = Calendar.getInstance();
 		Calendar calendarEnd;
 		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
@@ -226,7 +198,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 			tvRowPlace.setText(cursorNow.getString(6));
 
 			//Set icon
-			if (gm == GM.SECTION_LABLANCA_GM_SCHEDULE) {
+			if (gm == GM.SECTION.GM_SCHEDULE) {
 				ImageView pinPoint = (ImageView) entry.findViewById(R.id.iv_row_home_schedule_pinpoint);
 				pinPoint.setImageResource(getResources().getIdentifier("com.ivalentin.gm:drawable/pinpoint_gm", null, null));
 			}
@@ -270,7 +242,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 			tvRowPlace.setText(cursorNext.getString(6));
 
 			//Set icon
-			if (gm == GM.SECTION_LABLANCA_GM_SCHEDULE) {
+			if (gm == GM.SECTION.GM_SCHEDULE) {
 				ImageView pinPoint = (ImageView) entry.findViewById(R.id.iv_row_home_schedule_pinpoint);
 				pinPoint.setImageResource(getResources().getIdentifier("com.ivalentin.gm:drawable/pinpoint_gm", null, null));
 			}
@@ -293,7 +265,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 				section.setOnClickListener(new OnClickListener() {
 					@Override
 					public void onClick(View v) {
-						((MainActivity) getActivity()).loadSection(GM.SECTION_LABLANCA_GM_SCHEDULE);
+						((MainActivity) getActivity()).loadSection(GM.SECTION.GM_SCHEDULE);
 					}
 				});
 
@@ -301,7 +273,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 				section.setOnClickListener(new OnClickListener() {
 					@Override
 					public void onClick(View v) {
-						((MainActivity) getActivity()).loadSection(GM.SECTION_LABLANCA_SCHEDULE);
+						((MainActivity) getActivity()).loadSection(GM.SECTION.SCHEDULE);
 					}
 				});
 			}
@@ -429,12 +401,12 @@ public class HomeLayout extends Fragment implements LocationListener {
 			llSection.setOnClickListener(new OnClickListener() {
 				@Override
 				public void onClick(View v) {
-					((MainActivity) getActivity()).loadSection(GM.SECTION_LABLANCA);
+					((MainActivity) getActivity()).loadSection(GM.SECTION.LABLANCA);
 				}
 			});
 
 			//Get data from the database of the future activities
-			SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+			SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
 			int year = Calendar.getInstance().get(Calendar.YEAR);
 			String lang = GM.getLang();
 			Cursor cursor = db.rawQuery("SELECT text_" + lang + ", img FROM festival WHERE year = " + year + ";", null);
@@ -475,7 +447,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 						File fpath;
 						fpath = new File(this.getActivity().getFilesDir().toString() + "/img/fiestas/preview/");
 						fpath.mkdirs();
-						new DownloadImage(GM.SERVER + "/img/fiestas/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/fiestas/preview/" + image, ivImage, GM.IMG_PREVIEW).execute();
+						new DownloadImage(GM.API.SERVER + "/img/fiestas/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/fiestas/preview/" + image, ivImage, GM.IMG.SIZE.PREVIEW).execute();
 					}
 				}
 				else {
@@ -496,12 +468,25 @@ public class HomeLayout extends Fragment implements LocationListener {
 	 * @return True if the section has been shown, false otherwise.
 	 */
 	private boolean setUpLocation(Location location, View view) {
-		SharedPreferences preferences = view.getContext().getSharedPreferences(GM.PREFERENCES.PREFERNCES, Context.MODE_PRIVATE);
-		//Do this from db
-		if (!preferences.getString(GM.PREF_GM_LOCATION, GM.DEFAULT_PREF_GM_LOCATION).equals(GM.DEFAULT_PREF_GM_LOCATION)) {
-			try {
-				Double lat = Double.longBitsToDouble(preferences.getLong(GM.PREF_GM_LATITUDE, 0));
-				Double lon = Double.longBitsToDouble(preferences.getLong(GM.PREF_GM_LONGITUDE, 0));
+		try {
+
+			Double lat, lon;
+
+			SQLiteDatabase db = getActivity().openOrCreateDatabase(GM.DB.NAME, Activity.MODE_PRIVATE, null);
+			Cursor cursor;
+			cursor = db.rawQuery("SELECT lat, lon FROM location WHERE dtime >= Datetime('now', '-10 minutes') ORDER BY dtime DESC LIMIT 1;", null);
+			if (cursor.getCount() == 0){
+				cursor.close();
+				db.close();
+				return false;
+			}
+			else {
+				cursor.moveToFirst();
+				lat = cursor.getDouble(0);
+				lon = cursor.getDouble(1);
+				cursor.close();
+				db.close();
+
 				Double distance = Distance.calculateDistance(lat, lon, location.getLatitude(), location.getLongitude());
 				TextView text = (TextView) view.findViewById(R.id.tv_home_section_location_distance);
 				if (distance <= 2) {
@@ -510,13 +495,14 @@ public class HomeLayout extends Fragment implements LocationListener {
 				} else {
 					text.setText(String.format(getString(R.string.home_section_location_text_long), String.format(Locale.US, "%.02f", distance)));
 				}
+
 				return true;
 			}
-			catch (Exception ex){
-				Log.e("Location", "Couldn't set up home location section: " + ex.toString());
-			}
-
 		}
+		catch (Exception ex){
+			Log.e("Location", "Couldn't set up home location section: " + ex.toString());
+		}
+
 		return false;
 	}
 
@@ -537,7 +523,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 		llGallery.setOnClickListener(new OnClickListener() {
 			@Override
 			public void onClick(View v) {
-				((MainActivity) getActivity()).loadSection(GM.SECTION_GALLERY);
+				((MainActivity) getActivity()).loadSection(GM.SECTION.GALLERY);
 			}
 		});
 
@@ -549,7 +535,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 		ivPhoto[3] = (ImageView) view.findViewById(R.id.iv_home_section_gallery_3);
 
 		//Get data from the database of the future activities
-		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
 		Cursor cursor = db.rawQuery("SELECT id, album, file, uploaded FROM photo, photo_album WHERE id = photo ORDER BY uploaded DESC LIMIT 4;", null);
 
 		while (cursor.moveToNext()) {
@@ -572,7 +558,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 				File fpath;
 				fpath = new File(this.getActivity().getFilesDir().toString() + "/img/galeria/preview/");
 				fpath.mkdirs();
-				new DownloadImage(GM.SERVER + "/img/galeria/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/galeria/preview/" + image, ivPhoto[counter], GM.IMG_PREVIEW).execute();
+				new DownloadImage(GM.API.SERVER + "/img/galeria/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/galeria/preview/" + image, ivPhoto[counter], GM.IMG.SIZE.PREVIEW).execute();
 			}
 
 			//Set listeners for images
@@ -623,7 +609,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 		String lang = GM.getLang();
 
 		//Get data from the database of the future activities
-		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
 		Cursor cursor = db.rawQuery("SELECT id, date, city, title_" + lang + " AS title, text_" + lang + " AS text, price, after_" + lang + " AS after FROM activity WHERE date < date('now') ORDER BY date DESC LIMIT 2;", null);
 
 		//Show section
@@ -634,7 +620,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 		llActivitiesPast.setOnClickListener(new OnClickListener() {
 			@Override
 			public void onClick(View v) {
-				((MainActivity) getActivity()).loadSection(GM.SECTION_ACTIVITIES);
+				((MainActivity) getActivity()).loadSection(GM.SECTION.ACTIVITIES);
 			}
 		});
 
@@ -651,7 +637,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 
 			//Set margins
 			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
-			layoutParams.setMargins(GM.ENTRY_MARGIN, GM.ENTRY_MARGIN, GM.ENTRY_MARGIN, GM.ENTRY_MARGIN);
+			layoutParams.setMargins(GM.UI.ENTRY_MARGIN, GM.UI.ENTRY_MARGIN, GM.UI.ENTRY_MARGIN, GM.UI.ENTRY_MARGIN);
 			entry.setLayoutParams(layoutParams);
 
 			//Set title
@@ -705,7 +691,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 					File fpath;
 					fpath = new File(this.getActivity().getFilesDir().toString() + "/img/actividades/miniature/");
 					fpath.mkdirs();
-					new DownloadImage(GM.SERVER + "/img/actividades/miniature/" + image, this.getActivity().getFilesDir().toString() + "/img/actividades/miniature/" + image, iv, GM.IMG_MINIATURE).execute();
+					new DownloadImage(GM.API.SERVER + "/img/actividades/miniature/" + image, this.getActivity().getFilesDir().toString() + "/img/actividades/miniature/" + image, iv, GM.IMG.SIZE.MINIATURE).execute();
 				}
 			}
 			cursorImage.close();
@@ -764,7 +750,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 		LayoutInflater factory = LayoutInflater.from(getActivity());
 
 		//Get data from the database of the future activities
-		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
 		Cursor cursor = db.rawQuery("SELECT id, date, city, title_" + lang + " AS title, text_" + lang + " AS text, price FROM activity WHERE date >= date('now') ORDER BY date LIMIT 2;", null);
 
 		//If there are future activities...
@@ -778,7 +764,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 			llActivitiesFuture.setOnClickListener(new OnClickListener() {
 				@Override
 				public void onClick(View v) {
-					((MainActivity) getActivity()).loadSection(GM.SECTION_ACTIVITIES);
+					((MainActivity) getActivity()).loadSection(GM.SECTION.ACTIVITIES);
 				}
 			});
 
@@ -789,7 +775,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 
 				//Set margins
 				LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
-				layoutParams.setMargins(GM.ENTRY_MARGIN, GM.ENTRY_MARGIN, GM.ENTRY_MARGIN, GM.ENTRY_MARGIN);
+				layoutParams.setMargins(GM.UI.ENTRY_MARGIN, GM.UI.ENTRY_MARGIN, GM.UI.ENTRY_MARGIN, GM.UI.ENTRY_MARGIN);
 				entry.setLayoutParams(layoutParams);
 
 				//Set title
@@ -836,7 +822,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 						File fpath;
 						fpath = new File(this.getActivity().getFilesDir().toString() + "/img/actividades/miniature/");
 						fpath.mkdirs();
-						new DownloadImage(GM.SERVER + "/img/actividades/miniature/" + image, this.getActivity().getFilesDir().toString() + "/img/actividades/miniature/" + image, iv, GM.IMG_MINIATURE).execute();
+						new DownloadImage(GM.API.SERVER + "/img/actividades/miniature/" + image, this.getActivity().getFilesDir().toString() + "/img/actividades/miniature/" + image, iv, GM.IMG.SIZE.MINIATURE).execute();
 					}
 				}
 
@@ -891,7 +877,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 		llBlog.setOnClickListener(new OnClickListener() {
 			@Override
 			public void onClick(View v) {
-				((MainActivity) getActivity()).loadSection(GM.SECTION_BLOG);
+				((MainActivity) getActivity()).loadSection(GM.SECTION.BLOG);
 			}
 		});
 
@@ -902,7 +888,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 		//An inflater
 		LayoutInflater factory = LayoutInflater.from(getActivity());
 
-		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
 		final Cursor cursor;
 
 		//Get data from the database
@@ -916,7 +902,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 
 			//Set margins
 			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
-			layoutParams.setMargins(GM.ENTRY_MARGIN, GM.ENTRY_MARGIN, GM.ENTRY_MARGIN, GM.ENTRY_MARGIN);
+			layoutParams.setMargins(GM.UI.ENTRY_MARGIN, GM.UI.ENTRY_MARGIN, GM.UI.ENTRY_MARGIN, GM.UI.ENTRY_MARGIN);
 			entry.setLayoutParams(layoutParams);
 
 			//Set title
@@ -955,7 +941,7 @@ public class HomeLayout extends Fragment implements LocationListener {
 					File fpath;
 					fpath = new File(this.getActivity().getFilesDir().toString() + "/img/blog/miniature/");
 					fpath.mkdirs();
-					new DownloadImage(GM.SERVER + "/img/blog/miniature/" + image, this.getActivity().getFilesDir().toString() + "/img/blog/miniature/" + image, iv, GM.IMG_MINIATURE).execute();
+					new DownloadImage(GM.API.SERVER + "/img/blog/miniature/" + image, this.getActivity().getFilesDir().toString() + "/img/blog/miniature/" + image, iv, GM.IMG.SIZE.MINIATURE).execute();
 				}
 			}
 
@@ -1057,7 +1043,6 @@ public class HomeLayout extends Fragment implements LocationListener {
 	 */
 	@Override
 	public void onPause() {
-		//TODO: Only do this if location is required
 		if (!(ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
 			locationManager.removeUpdates(this);
 		}
@@ -1071,7 +1056,6 @@ public class HomeLayout extends Fragment implements LocationListener {
 	 */
 	@Override
 	public void onDestroy() {
-		//TODO: Only do this if location is required
 		try {
 			if (!(ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
 				locationManager.removeUpdates(this);
@@ -1091,7 +1075,6 @@ public class HomeLayout extends Fragment implements LocationListener {
 	 */
 	@Override
 	public void onResume(){
-		//TODO: Only do this if location is required
 		if (!(ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
 			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
 		}

+ 4 - 4
app/src/main/java/com/ivalentin/margolariak/HomeSectionLocation.java

@@ -50,7 +50,7 @@ class HomeSectionLocation extends AsyncTask<Void, Void, Void> {
 		try {
 
 			FetchURL fu = new FetchURL();
-			fu.Run(GM.SERVER + "/app/location.php");
+			fu.Run(GM.API.SERVER + "/app/location.php");
 			//All the info
 			o = fu.getOutput().toString();
 
@@ -78,12 +78,12 @@ class HomeSectionLocation extends AsyncTask<Void, Void, Void> {
 		if (isLocationReported){
 
 			//TODO: Do this on a db table
-			SharedPreferences preferences = view.getContext().getSharedPreferences(GM.PREFERENCES.PREFERNCES, Context.MODE_PRIVATE);
+			/*SharedPreferences preferences = view.getContext().getSharedPreferences(GM.PREFERENCES.PREFERNCES, Context.MODE_PRIVATE);
 			SharedPreferences.Editor editor = preferences.edit();
 			editor.putLong(GM.PREF_GM_LATITUDE, Double.doubleToLongBits(coord.latitude));
 			editor.putLong(GM.PREF_GM_LONGITUDE, Double.doubleToLongBits(coord.longitude));
 			editor.putString(GM.PREF_GM_LOCATION, new SimpleDateFormat("yyyyMMddHHmmss", Locale.US).format(Calendar.getInstance().getTime()));
-			editor.apply();
+			editor.apply();*/
 
 			//Show menu entry
 			//LinearLayout menuEntry = (LinearLayout) activity.findViewById(R.id.rl_menu_location);
@@ -95,7 +95,7 @@ class HomeSectionLocation extends AsyncTask<Void, Void, Void> {
 			section.setOnClickListener(new View.OnClickListener(){
 				@Override
 				public void onClick(View v) {
-					((MainActivity) v.getContext()).loadSection(GM.SECTION_LOCATION);
+					((MainActivity) v.getContext()).loadSection(GM.SECTION.LOCATION);
 				}
 			});
 

+ 4 - 4
app/src/main/java/com/ivalentin/margolariak/LablancaLayout.java

@@ -58,7 +58,7 @@ public class LablancaLayout extends Fragment {
 		//Get database info from the database
 		String lang = GM.getLang();
 		int year = Calendar.getInstance().get(Calendar.YEAR);
-		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
 		Cursor cursor = db.rawQuery("SELECT text_" + lang + ", img FROM festival WHERE year = " + year + ";", null);
 		cursor.moveToFirst();
 
@@ -91,7 +91,7 @@ public class LablancaLayout extends Fragment {
 				File fpath;
 				fpath = new File(this.getActivity().getFilesDir().toString() + "/img/fiestas/preview/");
 				fpath.mkdirs();
-				new DownloadImage(GM.SERVER + "/img/fiestas/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/fiestas/preview/" + image, headerImage, GM.IMG_PREVIEW).execute();
+				new DownloadImage(GM.API.SERVER + "/img/fiestas/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/fiestas/preview/" + image, headerImage, GM.IMG.SIZE.PREVIEW).execute();
 			}
 		}
 		else{
@@ -189,14 +189,14 @@ public class LablancaLayout extends Fragment {
 		gmSchedule.setOnClickListener(new View.OnClickListener() {
 			@Override
 			public void onClick(View v) {
-				((MainActivity) getActivity()).loadSection(GM.SECTION_LABLANCA_GM_SCHEDULE);
+				((MainActivity) getActivity()).loadSection(GM.SECTION.GM_SCHEDULE);
 			}
 		});
 
 		citySchedule.setOnClickListener(new View.OnClickListener() {
 			@Override
 			public void onClick(View v) {
-				((MainActivity) getActivity()).loadSection(GM.SECTION_LABLANCA_SCHEDULE);
+				((MainActivity) getActivity()).loadSection(GM.SECTION.SCHEDULE);
 			}
 		});
 

+ 96 - 35
app/src/main/java/com/ivalentin/margolariak/LocationLayout.java

@@ -9,17 +9,21 @@ import com.google.android.gms.maps.MapsInitializer;
 import com.google.android.gms.maps.OnMapReadyCallback;
 import com.google.android.gms.maps.model.BitmapDescriptorFactory;
 import com.google.android.gms.maps.model.LatLng;
+import com.google.android.gms.maps.model.Marker;
 import com.google.android.gms.maps.model.MarkerOptions;
 
+import android.app.Activity;
 import android.content.Context;
-import android.content.SharedPreferences;
 import android.content.pm.PackageManager;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
 import android.location.Criteria;
 import android.location.Location;
 import android.location.LocationListener;
 import android.location.LocationManager;
 import android.os.Bundle;
 import android.app.Fragment;
+import android.os.Handler;
 import android.support.v4.app.ActivityCompat;
 import android.util.Log;
 import android.view.LayoutInflater;
@@ -42,7 +46,7 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 
 	//The map view
 	private MapView mapView;
-	private MarkerOptions moGm;
+	GoogleMap gMap;
 
 	private LocationManager locationManager;
 
@@ -52,6 +56,35 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 	//The main View
 	private View v;
 
+	private double lat, lon;
+
+	//Map marker
+	Marker gmMarker;
+	MarkerOptions moGm = new MarkerOptions();
+
+	private final Handler markerHandler = new Handler();
+
+	private final Runnable resetMarker = new Runnable() {
+		@Override
+		public void run() {
+
+			if (gmMarker != null) {
+				gmMarker.remove();
+				if (refreshLocation()) {
+					gmMarker.setPosition(new LatLng(lat, lon));
+					gmLocation = new LatLng(lat, lon);
+					//moGm = new MarkerOptions();
+					moGm.title(v.getContext().getString(R.string.app_name));
+					moGm.position(gmLocation);
+					moGm.icon(BitmapDescriptorFactory.fromResource(R.drawable.pinpoint_gm));
+					gmMarker = gMap.addMarker(moGm);
+				}
+			}
+			markerHandler.postDelayed(resetMarker, GM.LOCATION.INTERVAL);
+		}
+	};
+
+
 	/**
 	 * Run when the fragment is inflated.
 	 *
@@ -70,12 +103,18 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 		//Set up
 		locationManager = (LocationManager) v.getContext().getSystemService(Context.LOCATION_SERVICE);
 		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)){
-			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, GM.LOCATION_ACCURACY_TIME, GM.LOCATION_ACCURACY_SPACE, this);
+			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, GM.LOCATION.ACCURACY.TIME, GM.LOCATION.ACCURACY.SPACE, this);
 		}
 
 		//Set the title
 		((MainActivity) getActivity()).setSectionTitle(v.getContext().getString(R.string.menu_location));
 
+		//Refresh the location.
+		refreshLocation();
+
+		//Periodically check map
+		markerHandler.post(resetMarker);
+
 		mapView = (MapView) v.findViewById(R.id.mapview);
 		mapView.onCreate(savedInstanceState);
 
@@ -98,9 +137,11 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 			mapView.onResume();
 		}
 		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)){
-			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, GM.LOCATION_ACCURACY_TIME, GM.LOCATION_ACCURACY_SPACE, this);
+			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, GM.LOCATION.ACCURACY.TIME, GM.LOCATION.ACCURACY.SPACE, this);
 		}
 		super.onResume();
+
+		markerHandler.post(resetMarker);
 	}
 
 	/**
@@ -114,6 +155,8 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 			locationManager.removeUpdates(this);
 		}
 		super.onPause();
+
+		markerHandler.removeCallbacks(resetMarker);
 	}
 
 	/**
@@ -128,10 +171,13 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 		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)) {
 			locationManager.removeUpdates(this);
 		}
+
 		if (mapView != null){
 			mapView.onResume();
 			mapView.onDestroy();
 		}
+
+		markerHandler.removeCallbacks(resetMarker);
 	}
 
 	/**
@@ -149,6 +195,34 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 		}
 	}
 
+	/**
+	 * Refresh the global variables "lat" and "lon".
+	 *
+	 * Uses the most recent data in the database, if they are not older than 10 minutes.
+	 *
+	 * @return true if there is a location from less than 10 minutes ago, 0 otherwise.
+	 */
+	private boolean refreshLocation(){
+
+		SQLiteDatabase db = getActivity().openOrCreateDatabase(GM.DB.NAME, Activity.MODE_PRIVATE, null);
+		Cursor cursor;
+		cursor = db.rawQuery("SELECT lat, lon FROM location WHERE dtime >= Datetime('now', '-10 minutes') ORDER BY dtime DESC LIMIT 1;", null);
+		if (cursor.getCount() == 0){
+			cursor.close();
+			db.close();
+			return false;
+		}
+		else {
+			cursor.moveToFirst();
+			lat = cursor.getDouble(0);
+			lon = cursor.getDouble(1);
+			cursor.close();
+			db.close();
+			return true;
+		}
+
+	}
+
 	/**
 	 * Called when the map is ready to be used. 
 	 * Initializes it and sets the Gasteizko Margolariak marker.
@@ -160,6 +234,8 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 	@Override
 	public void onMapReady(GoogleMap googleMap) {
 
+		gMap = googleMap;
+
 		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)) {
 			googleMap.setMyLocationEnabled(true);
 		}
@@ -171,31 +247,31 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 		} catch (Exception e) {
 			Log.e("Error initializing maps", e.toString());
 		}
-		
-		//Set GM marker
-		//TODO: Use db
-		SharedPreferences preferences = v.getContext().getSharedPreferences(GM.PREFERENCES.PREFERNCES, Context.MODE_PRIVATE);
-		Double lat = Double.longBitsToDouble(preferences.getLong(GM.PREF_GM_LATITUDE, 0));
-		Double lon = Double.longBitsToDouble(preferences.getLong(GM.PREF_GM_LONGITUDE, 0));
-		gmLocation = new LatLng(lat, lon);
-		moGm = new MarkerOptions();
-		moGm.title(v.getContext().getString(R.string.app_name));
-		moGm.position(gmLocation);
-		moGm.icon(BitmapDescriptorFactory.fromResource(R.drawable.pinpoint_gm));
-		googleMap.addMarker(moGm);
-		googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 14.0f));
+
+		//If there is a location, set it
+		if (refreshLocation()) {
+
+			//Set the marker
+			gmLocation = new LatLng(lat, lon);
+			moGm.title(v.getContext().getString(R.string.app_name));
+			moGm.position(gmLocation);
+			moGm.icon(BitmapDescriptorFactory.fromResource(R.drawable.pinpoint_gm));
+			gmMarker = googleMap.addMarker(moGm);
+			googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 14.0f));
+		}
 
 		//Start device location requests
 		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)) {
-			locationManager.requestLocationUpdates(locationManager.getBestProvider(new Criteria(), true), GM.LOCATION_ACCURACY_TIME, GM.LOCATION_ACCURACY_SPACE, this);
+			locationManager.requestLocationUpdates(locationManager.getBestProvider(new Criteria(), true), GM.LOCATION.ACCURACY.TIME, GM.LOCATION.ACCURACY.SPACE, this);
 			onLocationChanged(locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER));
 		}
 	}
 
+
 	private void calCulateDistance(Location userLocation){
 		TextView text = (TextView) v.findViewById(R.id.tv_location_distance);
 		try {
-			Double distance = Distance.calculateDistance(userLocation.getLatitude(), userLocation.getLongitude(), gmLocation.latitude, gmLocation.longitude);
+			Double distance = Distance.calculateDistance(userLocation.getLatitude(), userLocation.getLongitude(), lat, lon);
 			if (distance <= 2) {
 				distance = 1000 * distance;
 				text.setText(String.format(getString(R.string.home_section_location_text_short), distance.intValue(), (int) (0.012 * distance.intValue())));
@@ -220,23 +296,11 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 	 */
 	@Override
 	public void onLocationChanged(Location location) {
-		//TODO: Read again the GM Location.
-		SharedPreferences preferences = v.getContext().getSharedPreferences(GM.PREFERENCES.PREFERNCES, Context.MODE_PRIVATE);
-		if (!preferences.getString(GM.PREF_GM_LOCATION, GM.DEFAULT_PREF_GM_LOCATION).equals(GM.DEFAULT_PREF_GM_LOCATION)) {
-
-			Double lat = Double.longBitsToDouble(preferences.getLong(GM.PREF_GM_LATITUDE, 0));
-			Double lon = Double.longBitsToDouble(preferences.getLong(GM.PREF_GM_LONGITUDE, 0));
-			gmLocation = new LatLng(lat, lon);
-						calCulateDistance(location);
-			if (moGm != null){
-				moGm.visible(true);
-			}
-		}
+		calCulateDistance(location);
 	}
 
 	/**
 	 * Called when the location provider changes it's state.
-	 * Recalculates the list of events in the around section.
 	 *
 	 * @param provider The name of the provider
 	 * @param status Status code of the provider
@@ -275,7 +339,4 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 	public void onProviderDisabled(String provider) {
 		//populateAround();
 	}
-
-
-
 }

+ 84 - 85
app/src/main/java/com/ivalentin/margolariak/MainActivity.java

@@ -2,9 +2,6 @@ package com.ivalentin.margolariak;
 
 import java.math.BigInteger;
 import java.security.SecureRandom;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Locale;
 
 import android.app.Activity;
 import android.app.Fragment;
@@ -55,64 +52,52 @@ public class MainActivity extends Activity {
 	//Alarm to get location and notifications.
 	private AlarmReceiver notificationAlarm;
 
-	//The menu entries
-	private RelativeLayout menuItem[];
 	private TextView menuText[];
 	private ImageView menuImage[];
 
 	//Handler to periodically check for location updates
 	private final Handler locationHandler = new Handler();
 	// Code to check for location updates
+	private MainActivity activity = this;
 	private final Runnable checkForLocation = new Runnable() {
 		@Override
 		public void run() {
 
-			//Get location page and parse it
-			boolean result = false;
-			FetchURL fu = new FetchURL();
-			//TODO: This needs a simple API too
-			fu.Run(GM.SERVER + "/app/location.php");
-			String lat = "", lon = "";
-			String o = fu.getOutput().toString();
-			Log.d("Location", "Fetched location page");
-			if (o.contains("<location>none</location>"))
-				result = false;
-			if (o.contains("<lat>") && o.contains("<lon>")) {
-				lat = o.substring(o.indexOf("<lat>") + 5, o.indexOf("</lat>"));
-				lon = o.substring(o.indexOf("<lon>") + 5, o.indexOf("</lon>"));
-				result = true;
-			}
-
-			//TODO: Store in database
-			SharedPreferences settings = getSharedPreferences(GM.PREFERENCES.PREFERNCES, Context.MODE_PRIVATE);
-			SharedPreferences.Editor editor = settings.edit();
-			if (result) {
-				editor.putLong(GM.PREF_GM_LATITUDE, Double.doubleToLongBits(Double.parseDouble(lat)));
-				editor.putLong(GM.PREF_GM_LONGITUDE, Double.doubleToLongBits(Double.parseDouble(lon)));
-				editor.putString(GM.PREF_GM_LOCATION, new SimpleDateFormat("yyyyMMddHHmmss", Locale.US).format(Calendar.getInstance().getTime()));
-
-				//Show menu entry
-				if (menuItem[1] != null) {
-					menuItem[1].setVisibility(View.VISIBLE);
-				}
-			} else {
-				editor.putString(GM.PREF_GM_LOCATION, GM.DEFAULT_PREF_GM_LOCATION);
-				if (menuItem[1] != null) {
-					menuItem[1].setVisibility(View.GONE);
-				}
-			}
-			editor.apply();
+			new ReceiveLocation(activity).execute();
 
 			//Repeat this the same runnable code block again another th specified interval
-			locationHandler.postDelayed(checkForLocation, GM.INTERVAL_LOCATION);
+			locationHandler.postDelayed(checkForLocation, GM.LOCATION.INTERVAL);
 		}
 	};
+
 	/**
 	 * ATTENTION: This was auto-generated to implement the App Indexing API.
 	 * See https://g.co/AppIndexing/AndroidStudio for more information.
 	 */
 	private GoogleApiClient client;
 
+	/**
+	 * Enables o disables the location section.
+	 *
+	 * Shows or hiddes the menu entry and the home fragment,
+	 *
+	 * @param report True to show, false to hide.
+	 */
+	public void gotLocation(boolean report){
+		if (report) {
+			findViewById(R.id.rl_menu_location).setVisibility(View.VISIBLE);
+			if (findViewById(R.id.ll_home_section_location) != null){
+				findViewById(R.id.ll_home_section_location).setVisibility(View.VISIBLE);
+			}
+		}
+		else {
+			findViewById(R.id.rl_menu_location).setVisibility(View.GONE);
+			if (findViewById(R.id.ll_home_section_location) != null) {
+				findViewById(R.id.ll_home_section_location).setVisibility(View.GONE);
+			}
+		}
+	}
+
 	//Not referenced in code.
 	public void showMenu(View v) {
 		PopupMenu popup = new PopupMenu(this, v);
@@ -170,21 +155,21 @@ public class MainActivity extends Activity {
 		}
 
 		switch (section) {
-			case GM.SECTION_HOME:
+			case GM.SECTION.HOME:
 				fragment = new HomeLayout();
 				title = getString(R.string.menu_home);
 				menuText[0].setTypeface(null, Typeface.BOLD);
 				menuImage[0].getLayoutParams().height = 8;
 				break;
 
-			case GM.SECTION_LOCATION:
+			case GM.SECTION.LOCATION:
 				fragment = new LocationLayout();
 				title = getString(R.string.menu_location);
 				menuText[1].setTypeface(null, Typeface.BOLD);
 				menuImage[1].getLayoutParams().height = 8;
 				break;
 
-			case GM.SECTION_LABLANCA:
+			case GM.SECTION.LABLANCA:
 				//Get settings
 				SharedPreferences sharedData = getSharedPreferences(GM.DATA.DATA, Context.MODE_PRIVATE);
 				if (sharedData.getBoolean(GM.DATA.KEY.LABLANCA, GM.DATA.DEFAULT.LABLANCA)) {
@@ -197,39 +182,39 @@ public class MainActivity extends Activity {
 				menuImage[2].getLayoutParams().height = 8;
 				break;
 
-			case GM.SECTION_LABLANCA_SCHEDULE:
+			case GM.SECTION.SCHEDULE:
 				fragment = new ScheduleLayout();
-				bundle.putInt(GM.SCHEDULE, GM.SECTION_LABLANCA_SCHEDULE);
+				bundle.putInt(GM.SCHEDULE.KEY, GM.SCHEDULE.MARGOLARIAK);
 				fragment.setArguments(bundle);
 				title = getString(R.string.menu_lablanca_schedule);
 				menuText[2].setTypeface(null, Typeface.BOLD);
 				menuImage[2].getLayoutParams().height = 8;
 				break;
 
-			case GM.SECTION_LABLANCA_GM_SCHEDULE:
+			case GM.SECTION.GM_SCHEDULE:
 				fragment = new ScheduleLayout();
-				bundle.putInt(GM.SCHEDULE, GM.SECTION_LABLANCA_GM_SCHEDULE);
+				bundle.putInt(GM.SCHEDULE.KEY, GM.SCHEDULE.MARGOLARIAK);
 				fragment.setArguments(bundle);
 				title = getString(R.string.menu_lablanca_gm_schedule);
 				menuText[2].setTypeface(null, Typeface.BOLD);
 				menuImage[2].getLayoutParams().height = 8;
 				break;
 
-			case GM.SECTION_ACTIVITIES:
+			case GM.SECTION.ACTIVITIES:
 				fragment = new ActivityLayout();
 				title = getString(R.string.menu_activities);
 				menuText[3].setTypeface(null, Typeface.BOLD);
 				menuImage[3].getLayoutParams().height = 8;
 				break;
 
-			case GM.SECTION_BLOG:
+			case GM.SECTION.BLOG:
 				fragment = new BlogLayout();
 				title = getString(R.string.menu_blog);
 				menuText[4].setTypeface(null, Typeface.BOLD);
 				menuImage[4].getLayoutParams().height = 8;
 				break;
 
-			case GM.SECTION_GALLERY:
+			case GM.SECTION.GALLERY:
 				fragment = new GalleryLayout();
 				title = getString(R.string.menu_blog);
 				menuText[5].setTypeface(null, Typeface.BOLD);
@@ -265,9 +250,9 @@ public class MainActivity extends Activity {
 	protected void onCreate(Bundle savedInstanceState) {
 
 		//Get intent extras
-		String action = getIntent().getStringExtra(GM.EXTRA_ACTION);
-		String actionText = getIntent().getStringExtra(GM.EXTRA_TEXT);
-		String actionTitle = getIntent().getStringExtra(GM.EXTRA_TITLE);
+		String action = getIntent().getStringExtra(GM.EXTRA.ACTION);
+		String actionText = getIntent().getStringExtra(GM.EXTRA.TEXT);
+		String actionTitle = getIntent().getStringExtra(GM.EXTRA.TITLE);
 
 		//Set an alarm for notifications..
 		//Wait a little
@@ -304,7 +289,7 @@ public class MainActivity extends Activity {
 		setContentView(R.layout.activity_main);
 
 		//Assign menu items
-		menuItem = new RelativeLayout[6];
+		RelativeLayout[] menuItem = new RelativeLayout[6];
 		menuItem[0] = (RelativeLayout) findViewById(R.id.rl_menu_home);
 		menuItem[1] = (RelativeLayout) findViewById(R.id.rl_menu_location);
 		menuItem[2] = (RelativeLayout) findViewById(R.id.rl_menu_lablanca);
@@ -334,37 +319,37 @@ public class MainActivity extends Activity {
 		menuItem[0].setOnClickListener(new OnClickListener() {
 			@Override
 			public void onClick(View v) {
-				loadSection(GM.SECTION_HOME);
+				loadSection(GM.SECTION.HOME);
 			}
 		});
 		menuItem[1].setOnClickListener(new OnClickListener() {
 			@Override
 			public void onClick(View v) {
-				loadSection(GM.SECTION_LOCATION);
+				loadSection(GM.SECTION.LOCATION);
 			}
 		});
 		menuItem[2].setOnClickListener(new OnClickListener() {
 			@Override
 			public void onClick(View v) {
-				loadSection(GM.SECTION_LABLANCA);
+				loadSection(GM.SECTION.LABLANCA);
 			}
 		});
 		menuItem[3].setOnClickListener(new OnClickListener() {
 			@Override
 			public void onClick(View v) {
-				loadSection(GM.SECTION_ACTIVITIES);
+				loadSection(GM.SECTION.ACTIVITIES);
 			}
 		});
 		menuItem[4].setOnClickListener(new OnClickListener() {
 			@Override
 			public void onClick(View v) {
-				loadSection(GM.SECTION_BLOG);
+				loadSection(GM.SECTION.BLOG);
 			}
 		});
 		menuItem[5].setOnClickListener(new OnClickListener() {
 			@Override
 			public void onClick(View v) {
-				loadSection(GM.SECTION_GALLERY);
+				loadSection(GM.SECTION.GALLERY);
 			}
 		});
 
@@ -372,13 +357,11 @@ public class MainActivity extends Activity {
 		SharedPreferences sharedData = getSharedPreferences(GM.PREFERENCES.PREFERNCES, Context.MODE_PRIVATE);
 		SharedPreferences.Editor dataEditor = sharedData.edit();
 
-		//TODO: Read database. If there is a recent location, show the menu entry
-
 		//If the user code is not set, generate one
 		if (sharedData.getString(GM.DATA.KEY.USER, GM.DATA.DEFAULT.USER).length() == GM.DATA.DEFAULT.USER.length()) {
 			SecureRandom random = new SecureRandom();
 			String newCode = new BigInteger(130, random).toString(32).substring(0, 16);
-			dataEditor.putString(GM.USER_CODE, newCode);
+			dataEditor.putString(GM.DATA.KEY.USER, newCode);
 			dataEditor.apply();
 		}
 
@@ -399,7 +382,7 @@ public class MainActivity extends Activity {
 			sync();
 
 			//Load initial section
-			loadSection(GM.SECTION_HOME);
+			loadSection(GM.SECTION.HOME);
 
 			//If the intent had extras (from notifications), do something
 			if (actionText != null) {
@@ -448,7 +431,7 @@ public class MainActivity extends Activity {
 					if (action != null) {
 						switch (action) {
 
-							case GM.EXTRA_ACTION_LABLANCA:
+							case GM.EXTRA.SECTION.LABLANCA:
 
 								//Set up the action button
 								btDialogAction.setVisibility(View.VISIBLE);
@@ -457,15 +440,15 @@ public class MainActivity extends Activity {
 									@Override
 									public void onClick(View v) {
 										dialog.dismiss();
-										loadSection(GM.SECTION_LABLANCA);
+										loadSection(GM.SECTION.LABLANCA);
 									}
 								});
 								break;
 
-							case GM.EXTRA_ACTION_LOCATION:
+							case GM.EXTRA.SECTION.LOCATION:
 
 								//TODO: Read from database
-								if (!sharedData.getString(GM.PREF_GM_LOCATION, GM.DEFAULT_PREF_GM_LOCATION).equals(GM.DEFAULT_PREF_GM_LOCATION)) {
+								/*if (!sharedData.getString(GM.PREF_GM_LOCATION, GM.DEFAULT_PREF_GM_LOCATION).equals(GM.DEFAULT_PREF_GM_LOCATION)) {
 									//Set up the action button if location is reported
 									btDialogAction.setVisibility(View.VISIBLE);
 									btDialogAction.setText(this.getApplicationContext().getString(R.string.notification_action_location));
@@ -477,10 +460,10 @@ public class MainActivity extends Activity {
 										}
 									});
 
-								}
+								}*/
 								break;
 
-							case GM.EXTRA_ACTION_BLOG:
+							case GM.EXTRA.SECTION.BLOG:
 
 								//Set up the action button
 								btDialogAction.setVisibility(View.VISIBLE);
@@ -489,12 +472,12 @@ public class MainActivity extends Activity {
 									@Override
 									public void onClick(View v) {
 										dialog.dismiss();
-										loadSection(GM.SECTION_BLOG);
+										loadSection(GM.SECTION.BLOG);
 									}
 								});
 								break;
 
-							case GM.EXTRA_ACTION_ACTIVITIES:
+							case GM.EXTRA.SECTION.ACTIVITIES:
 
 								//Set up the action button
 								btDialogAction.setVisibility(View.VISIBLE);
@@ -503,12 +486,12 @@ public class MainActivity extends Activity {
 									@Override
 									public void onClick(View v) {
 										dialog.dismiss();
-										loadSection(GM.SECTION_ACTIVITIES);
+										loadSection(GM.SECTION.ACTIVITIES);
 									}
 								});
 								break;
 
-							case GM.EXTRA_ACTION_GALLERY:
+							case GM.EXTRA.SECTION.GALLERY:
 
 								//Set up the action button
 								btDialogAction.setVisibility(View.VISIBLE);
@@ -517,12 +500,12 @@ public class MainActivity extends Activity {
 									@Override
 									public void onClick(View v) {
 										dialog.dismiss();
-										loadSection(GM.SECTION_GALLERY);
+										loadSection(GM.SECTION.GALLERY);
 									}
 								});
 								break;
 
-							case GM.EXTRA_ACTION_GMSCHEDULE:
+							case GM.EXTRA.SECTION.GMSCHEDULE:
 
 								if (festivals) {
 									//Set up the action button
@@ -532,13 +515,13 @@ public class MainActivity extends Activity {
 										@Override
 										public void onClick(View v) {
 											dialog.dismiss();
-											loadSection(GM.SECTION_LABLANCA_GM_SCHEDULE);
+											loadSection(GM.SECTION.GM_SCHEDULE);
 										}
 									});
 								}
 								break;
 
-							case GM.EXTRA_ACTION_CITYSCHEDULE:
+							case GM.EXTRA.SECTION.SCHEDULE:
 								if (festivals) {
 									//Set up the action button
 									btDialogAction.setVisibility(View.VISIBLE);
@@ -547,7 +530,7 @@ public class MainActivity extends Activity {
 										@Override
 										public void onClick(View v) {
 											dialog.dismiss();
-											loadSection(GM.SECTION_LABLANCA_SCHEDULE);
+											loadSection(GM.SECTION.SCHEDULE);
 										}
 									});
 								}
@@ -589,7 +572,7 @@ public class MainActivity extends Activity {
 		SQLiteDatabase db;
 		try {
 			//Create database
-			db = openOrCreateDatabase(GM.DB_NAME, Activity.MODE_PRIVATE, null);
+			db = openOrCreateDatabase(GM.DB.NAME, Activity.MODE_PRIVATE, null);
 			db.execSQL(GM.DB.QUERY.CREATE.ACTIVITY);
 			db.execSQL(GM.DB.QUERY.CREATE.ACTIVITY_COMMENT);
 			db.execSQL(GM.DB.QUERY.CREATE.ACTIVITY_IMAGE);
@@ -612,7 +595,7 @@ public class MainActivity extends Activity {
 			db.execSQL(GM.DB.QUERY.CREATE.POST_COMMENT);
 			db.execSQL(GM.DB.QUERY.CREATE.POST_IMAGE);
 			db.execSQL(GM.DB.QUERY.CREATE.POST_TAG);
-			db.execSQL(GM.DB.QUERY.CREATE.SETTINGS);
+			//db.execSQL(GM.DB.QUERY.CREATE.SETTINGS);
 			db.execSQL(GM.DB.QUERY.CREATE.SPONSOR);
 			db.execSQL(GM.DB.QUERY.CREATE.VERSION);
 			db.close();
@@ -625,9 +608,8 @@ public class MainActivity extends Activity {
 	 * Creates the app database and fills it with the hard coded, default data.
 	 */
 	private void deleteDatabase() {
-		SQLiteDatabase db;
 		try {
-			getApplicationContext().deleteDatabase(GM.DB_NAME);
+			getApplicationContext().deleteDatabase(GM.DB.NAME);
 		} catch (Exception ex) {
 			Log.e("Error deleting database", ex.toString());
 		}
@@ -690,7 +672,6 @@ public class MainActivity extends Activity {
 			}
 		} catch (Exception ex) {
 			Log.e("Error going back", "Finishing activity: " + ex.toString());
-			Log.e("RUNNABLE", "Finishing callback for location");
 			locationHandler.removeCallbacks(checkForLocation);
 			finish();
 			//super.onBackPressed();
@@ -713,18 +694,36 @@ public class MainActivity extends Activity {
 		return super.onKeyUp(keyCode, event);
 	}
 
+	/**
+	 * Overrides onResume().
+	 * Resumes the location handler to check for location regularly.
+	 *
+	 * @see Activity#onResume()
+	 */
 	@Override
 	public void onResume() {
 		locationHandler.post(checkForLocation);
 		super.onResume();
 	}
 
+	/**
+	 * Overrides onPause().
+	 * Stops the location handler to check for location regularly.
+	 *
+	 * @see Activity#onPause()
+	 */
 	@Override
 	public void onPause() {
 		locationHandler.removeCallbacks(checkForLocation);
 		super.onPause();
 	}
 
+	/**
+	 * Overrides onDestroy().
+	 * Stops the location handler to check for location regularly.
+	 *
+	 * @see Activity#onDestroy()
+	 */
 	@Override
 	public void onDestroy() {
 		locationHandler.removeCallbacks(checkForLocation);

+ 3 - 3
app/src/main/java/com/ivalentin/margolariak/PhotoLayout.java

@@ -123,7 +123,7 @@ public class PhotoLayout extends Fragment {
 	 */
 	private Integer[] loadPhotos(int id){
 
-		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
 
 		//Get album id for the photo
 		Cursor cAlbum = db.rawQuery("SELECT album FROM photo_album WHERE photo = " + id + ";", null);
@@ -156,7 +156,7 @@ public class PhotoLayout extends Fragment {
 		final int photoId = id;
 
 		//Get data from database
-		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
 		final Cursor cursor;
 		final String lang = GM.getLang();
 		cursor = db.rawQuery("SELECT id, file, title_" + lang+ " AS title, description_" + lang + " AS description, uploaded, width, height, size FROM photo WHERE id = " + id + ";", null);
@@ -208,7 +208,7 @@ public class PhotoLayout extends Fragment {
 			File fpath;
 			fpath = new File(this.getActivity().getFilesDir().toString() + "/img/galeria/view/");
 			fpath.mkdirs();
-			new DownloadImage(GM.SERVER + "/img/galeria/view/" + image, this.getActivity().getFilesDir().toString() + "/img/galeria/view/" + image, imageView, GM.IMG_VIEW).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
+			new DownloadImage(GM.API.SERVER + "/img/galeria/view/" + image, this.getActivity().getFilesDir().toString() + "/img/galeria/view/" + image, imageView, GM.IMG.SIZE.VIEW).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
 		}
 
 		//Hide or show comments, as needed

+ 2 - 2
app/src/main/java/com/ivalentin/margolariak/PostComment.java

@@ -103,7 +103,7 @@ class PostComment extends AsyncTask<String, String, Integer> {
             urlParams = urlParams + "&from=app&code=" + userCode;
             byte[] postData       = urlParams.getBytes("UTF-8");
             int    postDataLength = postData.length;
-            String request        = GM.SERVER + "/" + type + "/comment.php";
+            String request        = GM.API.SERVER + "/" + type + "/comment.php";
             url            = new URL( request );
             HttpURLConnection conn= (HttpURLConnection) url.openConnection();
             conn.setDoOutput( true );
@@ -122,7 +122,7 @@ class PostComment extends AsyncTask<String, String, Integer> {
 
             if (code == 200){
                 //Insert into local db
-                SQLiteDatabase db = SQLiteDatabase.openDatabase(context.getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
+                SQLiteDatabase db = SQLiteDatabase.openDatabase(context.getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
                 String table = "";
                 String item = "";
                 switch (type){

+ 2 - 2
app/src/main/java/com/ivalentin/margolariak/PostLayout.java

@@ -57,7 +57,7 @@ public class PostLayout extends Fragment {
         }
 
         //Get data from database
-        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+        SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
         final Cursor cursor;
         String lang = GM.getLang();
         cursor = db.rawQuery("SELECT id, title_" + lang+ " AS title, text_" + lang + " AS text, dtime FROM post WHERE id = " + id + ";", null);
@@ -110,7 +110,7 @@ public class PostLayout extends Fragment {
                 File fpath;
                 fpath = new File(this.getActivity().getFilesDir().toString() + "/img/blog/preview/");
                 fpath.mkdirs();
-				new DownloadImage(GM.SERVER + "/img/blog/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/blog/preview/" + image, images[i], GM.IMG_PREVIEW).execute();
+				new DownloadImage(GM.API.SERVER + "/img/blog/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/blog/preview/" + image, images[i], GM.IMG.SIZE.PREVIEW).execute();
             }
             images[i].setVisibility(View.VISIBLE);
             i ++;

+ 101 - 0
app/src/main/java/com/ivalentin/margolariak/ReceiveLocation.java

@@ -0,0 +1,101 @@
+package com.ivalentin.margolariak;
+
+import android.app.Activity;
+import android.database.sqlite.SQLiteDatabase;
+import android.os.AsyncTask;
+import android.util.Log;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+/**
+ * AsyncTask to get Gasteizko Margolariak location.
+ *
+ * Uses the Location V1 API.
+ *
+ * @author Inigo Valentin
+ *
+ * @see AsyncTask
+ */
+
+class ReceiveLocation extends AsyncTask<Void, Void, Void> {
+
+	private MainActivity activity;
+	private boolean report = false;
+
+	/**
+	 * Called when the AsyncTask is created.
+	 *
+	 * @param activity The calling activity.
+	 */
+	ReceiveLocation(MainActivity activity){
+		this.activity = activity;
+	}
+
+	@Override
+	protected Void doInBackground(Void... params) {
+
+		try {
+			String uri = GM.API.SERVER + GM.API.LOCATION.PATH;
+			URL url = new URL(uri);
+			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
+
+			int httpCode = urlConnection.getResponseCode();
+			switch (httpCode) {
+				case 400:	//Client error: Bad request
+					Log.e("LOCATION", "The server returned a 400 code (Client Error: Bad request) for the url \"" + uri + "\"");
+					break;
+				case 204:	//Success: No content
+					Log.d("LOCATION", "The server returned a 204 code (Success: No content) for the url \"" + uri + "\". Not getting location...");
+					break;
+				case 200:	//Success: OK
+					Log.d("LOCATION", "The server returned a 200 code (Success: OK) for the url \"" + uri + "\". Now getting location...");
+					BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
+					StringBuilder sb = new StringBuilder();
+					String o;
+					while ((o = br.readLine()) != null) {
+						sb.append(o);
+					}
+
+					//Get the string with the sync json. (The whole page)
+					String strLocation = sb.toString();
+					String lat = strLocation.substring(strLocation.indexOf("\"lat\":\"") + 7, strLocation.indexOf("\"", strLocation.indexOf("\"lat\":\"") + 8));
+					String lon = strLocation.substring(strLocation.indexOf("\"lon\":\"") + 7, strLocation.indexOf("\"", strLocation.indexOf("\"lon\":\"") + 8));
+					String dtime = strLocation.substring(strLocation.indexOf("\"dtime\":\"") + 9, strLocation.indexOf("\"", strLocation.indexOf("\"dtime\":\"") + 10));
+					Log.d("LOCATION", "Found location [" +lat + ", " + lon + "] sent " + dtime);
+
+					//Insert into the database
+					SQLiteDatabase db = activity.openOrCreateDatabase(GM.DB.NAME, Activity.MODE_PRIVATE, null);
+					db.execSQL("INSERT INTO location VALUES ('" + dtime + "', " + lat + ", " + lon + ")");
+					db.close();
+
+					//Set to true so the menu and relevant sections are hidden.
+					report = true;
+			}
+
+
+		} catch (MalformedURLException e) {
+			Log.e("LOCATION", "Unable to get location, malformed URL: " + e.toString());
+		} catch (IOException e) {
+			Log.e("LOCATION", "Unable to get location, IO exception: " + e.toString());
+		}
+
+
+		return null;
+	}
+
+	/**
+	 * Things to do after sync. Shows or hides the menu entry and relevant sections.
+	 *
+	 * @see android.os.AsyncTask#onPreExecute()
+	 */
+	@Override
+	protected void onPostExecute(Void v){
+		activity.gotLocation(report);
+	}
+
+}

+ 9 - 9
app/src/main/java/com/ivalentin/margolariak/ScheduleLayout.java

@@ -105,18 +105,18 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 
 		//Get schedule type
 		Bundle bundle = this.getArguments();
-		schedule = bundle.getInt(GM.SCHEDULE, GM.SECTION_LABLANCA_SCHEDULE);
+		schedule = bundle.getInt(GM.SCHEDULE.KEY, GM.SCHEDULE.CITY);
 		
 		//Set the title
-		if (schedule == GM.SECTION_LABLANCA_SCHEDULE)
+		if (schedule == GM.SCHEDULE.CITY)
 			((MainActivity) getActivity()).setSectionTitle(view.getContext().getString(R.string.menu_lablanca_schedule));
 		else
 			((MainActivity) getActivity()).setSectionTitle(view.getContext().getString(R.string.menu_lablanca_gm_schedule));
 
 		//Populate the dates array
-		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
 		Cursor cursor;
-		if (schedule == GM.SECTION_LABLANCA_GM_SCHEDULE) {
+		if (schedule == GM.SCHEDULE.MARGOLARIAK) {
 			cursor = db.rawQuery("SELECT DISTINCT date(start) FROM festival_event WHERE strftime('%Y', start) = '" + year + "' AND strftime('%H', start) > '06' AND gm = 1;", null);
 		}
 		else{
@@ -224,7 +224,7 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 			Log.e("Datetime error", ex.toString());
 		}
 
-		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
 
 		String lang = GM.getLang();
 
@@ -252,7 +252,7 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 				tvDayMonth.setText(getString(R.string.schedule_month_august));
 				break;
 		}
-		if (schedule == GM.SECTION_LABLANCA_GM_SCHEDULE) {
+		if (schedule == GM.SCHEDULE.MARGOLARIAK) {
 			Cursor cursorDay = db.rawQuery("SELECT name_" + lang + " FROM festival_day WHERE date(date) = '" + dates[selected] + "';", null);
 			if (cursorDay.getCount() > 0) {
 				cursorDay.moveToFirst();
@@ -278,7 +278,7 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 
 		String query = "SELECT festival_event.id, title_" + lang + ", description_" + lang + ", place, start, end, name_" + lang + ", address_" + lang + ", lat, lon FROM festival_event, place WHERE place = place.id AND start >= '" + dates[selected] + " 06:00:00' AND start < '" + endDate + " 05:59:59' AND ";
 
-		if (schedule == GM.SECTION_LABLANCA_GM_SCHEDULE) {
+		if (schedule == GM.SCHEDULE.MARGOLARIAK) {
 			query = query + "gm = 1 ";
 		} else {
 			query = query + "gm = 0 ";
@@ -327,7 +327,7 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 			}
 
 			//Set icon
-			if (schedule == GM.SECTION_LABLANCA_GM_SCHEDULE) {
+			if (schedule == GM.SCHEDULE.MARGOLARIAK) {
 				ImageView pinPoint = (ImageView) entry.findViewById(R.id.iv_row_schedule_pinpoint);
 				pinPoint.setImageResource(getResources().getIdentifier("com.ivalentin.margolariak:drawable/pinpoint_gm", null, null));
 			}
@@ -399,7 +399,7 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 		Button btClose = (Button) dialog.findViewById(R.id.bt_schedule_close);
 		
 		//Get info about the event
-		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB_NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
+		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
 		String lang = GM.getLang();
 		Cursor cursor = db.rawQuery("SELECT festival_event.id, title_" + lang + ", description_" + lang + ", place, start, end, name_" + lang + ", address_" + lang + ", lat, lon, host FROM festival_event, place WHERE place = place.id AND festival_event.id = " + id + ";", null);
 		if (cursor.getCount() > 0){

+ 13 - 13
app/src/main/java/com/ivalentin/margolariak/Sync.java

@@ -112,7 +112,7 @@ class Sync extends AsyncTask<Void, Void, Void> {
 			dialog.dismiss();
 
 			//Check db version again
-			SQLiteDatabase db = myContextRef.openOrCreateDatabase(GM.DB_NAME, Activity.MODE_PRIVATE, null);
+			SQLiteDatabase db = myContextRef.openOrCreateDatabase(GM.DB.NAME, Activity.MODE_PRIVATE, null);
 			if (db.isReadOnly()){
 				Log.e("Db ro", "Database is locked and in read only mode. Skipping sync.");
 				return;
@@ -128,7 +128,7 @@ class Sync extends AsyncTask<Void, Void, Void> {
 			db.close();
 
 			//If the database is on it's initial version (i.e: There is no data, new or old)
-			if (dbVersion == GM.DEFAULT_PREF_DB_VERSION){
+			if (true){ //TODO dbVersion == GM.DATA.DEFAULT.DEFAULT_PREF_DB_VERSION){
 
 				Log.e("SYNC", "Full sync failed");
 
@@ -155,7 +155,7 @@ class Sync extends AsyncTask<Void, Void, Void> {
 			}
 			else{
 				Log.d("SYNC", "Full sync finished");
-				activity.loadSection(GM.SECTION_HOME);
+				activity.loadSection(GM.SECTION.HOME);
 			}
 		}
 
@@ -245,15 +245,15 @@ class Sync extends AsyncTask<Void, Void, Void> {
 	private String buildUrl(String user, int version, int foreground, String lang){
 		String url = "";
 		try {
-			url = GM.SERVER + GM.SERVER_SYNC + "?" +
-					GM.SERVER_SYNC_KEY_CLIENT + "=" + URLEncoder.encode(GM.CLIENT, "UTF-8") + "&" +
-					GM.SERVER_SYNC_KEY_USER + "=" + URLEncoder.encode(user, "UTF-8") + "&" +
-					GM.SERVER_SYNC_KEY_ACTION + "=" + URLEncoder.encode(GM.SERVER_SYNC_VALUE_ACTION, "UTF-8") + "&" +
-					GM.SERVER_SYNC_KEY_SECTION + "=" + URLEncoder.encode(GM.SERVER_SYNC_VALUE_SECTION, "UTF-8") + "&" +
-					GM.SERVER_SYNC_KEY_VERSION + "=" + version + "&" +
-					GM.SERVER_SYNC_KEY_FOREGROUND + "=" + foreground + "&" +
-					GM.SERVER_SYNC_KEY_FORMAT + "=" + URLEncoder.encode(GM.SERVER_SYNC_VALUE_FORMAT, "UTF-8") + "&" +
-					GM.SERVER_SYNC_KEY_LANG + "=" + URLEncoder.encode(lang, "UTF-8");
+			url = GM.API.SERVER + GM.API.SYNC.PATH + "?" +
+					GM.API.SYNC.KEY.CLIENT + "=" + URLEncoder.encode(GM.API.CLIENT, "UTF-8") + "&" +
+					GM.API.SYNC.KEY.USER + "=" + URLEncoder.encode(user, "UTF-8") + "&" +
+					GM.API.SYNC.KEY.ACTION + "=" + URLEncoder.encode(GM.API.SYNC.VALUE.ACTION, "UTF-8") + "&" +
+					GM.API.SYNC.KEY.SECTION + "=" + URLEncoder.encode(GM.API.SYNC.VALUE.SECTION, "UTF-8") + "&" +
+					GM.API.SYNC.KEY.VERSION + "=" + version + "&" +
+					GM.API.SYNC.KEY.FOREGROUND + "=" + foreground + "&" +
+					GM.API.SYNC.KEY.FORMAT + "=" + URLEncoder.encode(GM.API.SYNC.VALUE.FORMAT, "UTF-8") + "&" +
+					GM.API.SYNC.KEY.LANG + "=" + URLEncoder.encode(lang, "UTF-8");
 		}
 		catch (java.io.UnsupportedEncodingException ex){
 			Log.e("UTF-8", "Error encoding url for sync \"" + url + "\" - " + ex.toString());
@@ -592,7 +592,7 @@ class Sync extends AsyncTask<Void, Void, Void> {
 		String userCode = preferences.getString(GM.DATA.KEY.USER, GM.DATA.DEFAULT.USER);
 
 		//Get database. Stop if it's locked
-		SQLiteDatabase db = myContextRef.openOrCreateDatabase(GM.DB_NAME, Activity.MODE_PRIVATE, null);
+		SQLiteDatabase db = myContextRef.openOrCreateDatabase(GM.DB.NAME, Activity.MODE_PRIVATE, null);
 		if (db.isReadOnly()){
 			Log.e("SYNC", "Database is locked and in read only mode. Skipping sync.");
 			return null;

Alguns ficheiros não foram mostrados porque muitos ficheiros mudaram neste diff