Iñigo Valentin 9 лет назад
Родитель
Сommit
23f54f88a7

+ 1 - 84
app/src/main/java/com/ivalentin/margolariak/GM.java

@@ -26,7 +26,7 @@ final class GM {
 		/**
 		 * Name of the database.
 		 */
-		static final String NAME = "gm";
+		static final String NAME = "gmv3";
 
 		/**
 		 * Initial version of the database.
@@ -967,57 +967,12 @@ final class GM {
 				 */
 				static final String USER = "user";
 
-				/**
-				 * Key for the action to perform with the API ("sync" or "version").
-				 */
-				static final String ACTION = "action";
-
-				/**
-				 * Key for the section to sync.
-				 */
-				static final String SECTION = "section";
-
-				/**
-				 * Key for the current version of the database to send to the API.
-				 */
-				static final String VERSION = "version";
-
 				/**
 				 * Key to indicate to the API if the sync is being performed on the foreground.
 				 */
 				static final String FOREGROUND = "foreground";
 
-				/**
-				 * Key to indicate the format of the data for the API to send.
-				 */
-				static final String FORMAT = "format";
-
-				/**
-				 * Key to indicate the language to the API.
-				 */
-				static final String LANG = "lang";
 			}
-
-			/**
-			 * Values for the parameters.
-			 */
-			 static final class VALUE {
-
-				/**
-				 * Value for the ACTION key.
-				 */
-				static final String ACTION = "sync";
-
-				/**
-				 * Value for the SECTION key,
-				 */
-				 static final String SECTION = "all";
-
-				/**
-				 * Value for the FORMAT key.
-				 */
-				static final String FORMAT = "json";
-			 }
 		}
 
 		/**
@@ -1029,28 +984,6 @@ final class GM {
 			 * Path to the API.
 			 */
 			static final String PATH = "/API/v3/location.php";
-
-			/**
-			 * Keys fotr the API parameters.
-			 */
-			static final class KEY {
-
-				/**
-				 * Key to indicate the format of the data for the API to send.
-				 */
-				static final String FORMAT = "format";
-			}
-
-			/**
-			 * Values for the parameters.
-			 */
-			static final class VALUE {
-
-				/**
-				 * Value for the FORMAT key.
-				 */
-				static final String FORMAT = "json";
-			}
 		}
 
 		/**
@@ -1082,22 +1015,6 @@ final class GM {
 				 * Key for the action to perform with the API ("sync" or "version").
 				 */
 				static final String TARGET = "target";
-
-				/**
-				 * Key to indicate the format of the data for the API to send.
-				 */
-				static final String FORMAT = "format";
-			}
-
-			/**
-			 * Values for the parameters.
-			 */
-			static final class VALUE {
-
-				/**
-				 * Value for the FORMAT key.
-				 */
-				static final String FORMAT = "json";
 			}
 		}
 

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

@@ -60,127 +60,129 @@ public class LablancaLayout extends Fragment {
 		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);
 		Cursor cursor = db.rawQuery("SELECT text_" + lang + ", img FROM festival WHERE year = " + year + ";", null);
-		cursor.moveToFirst();
 
-		//Set text
-		WebView headerText = (WebView) view.findViewById(R.id.wv_lablanca_header);
+		if (cursor.getCount() > 0) {
+			cursor.moveToFirst();
 
-		if (Build.VERSION.SDK_INT >= 19) {
-			headerText.setLayerType(View.LAYER_TYPE_HARDWARE, null);
-		}
-		else {
-			headerText.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
-		}
-
-		headerText.loadDataWithBaseURL(null, cursor.getString(0), "text/html", "utf-8", null);
+			//Set text
+			WebView headerText = (WebView) view.findViewById(R.id.wv_lablanca_header);
 
-		//Set image
-		ImageView headerImage = (ImageView) view.findViewById(R.id.iv_lablanca_header);
-		String image = cursor.getString(1);
-		if (image != null && image.length() > 0){
+			if (Build.VERSION.SDK_INT >= 19) {
+				headerText.setLayerType(View.LAYER_TYPE_HARDWARE, null);
+			} else {
+				headerText.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
+			}
 
-			//Check if image exists
-			File f;
-			f = new File(this.getActivity().getFilesDir().toString() + "/img/fiestas/preview/" + image);
-			if (f.exists()) {
-				//If the image exists, set it.
-				Bitmap myBitmap = BitmapFactory.decodeFile(this.getActivity().getFilesDir().toString() + "/img/fiestas/preview/" + image);
-				headerImage.setImageBitmap(myBitmap);
+			headerText.loadDataWithBaseURL(null, cursor.getString(0), "text/html", "utf-8", null);
+
+			//Set image
+			ImageView headerImage = (ImageView) view.findViewById(R.id.iv_lablanca_header);
+			String image = cursor.getString(1);
+			if (image != null && image.length() > 0) {
+
+				//Check if image exists
+				File f;
+				f = new File(this.getActivity().getFilesDir().toString() + "/img/fiestas/preview/" + image);
+				if (f.exists()) {
+					//If the image exists, set it.
+					Bitmap myBitmap = BitmapFactory.decodeFile(this.getActivity().getFilesDir().toString() + "/img/fiestas/preview/" + image);
+					headerImage.setImageBitmap(myBitmap);
+				} else {
+					//If not, create directories and download asynchronously
+					File fpath;
+					fpath = new File(this.getActivity().getFilesDir().toString() + "/img/fiestas/preview/");
+					fpath.mkdirs();
+					new DownloadImage(GM.API.SERVER + "/img/fiestas/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/fiestas/preview/" + image, headerImage, GM.IMG.SIZE.PREVIEW).execute();
+				}
 			} else {
-				//If not, create directories and download asynchronously
-				File fpath;
-				fpath = new File(this.getActivity().getFilesDir().toString() + "/img/fiestas/preview/");
-				fpath.mkdirs();
-				new DownloadImage(GM.API.SERVER + "/img/fiestas/preview/" + image, this.getActivity().getFilesDir().toString() + "/img/fiestas/preview/" + image, headerImage, GM.IMG.SIZE.PREVIEW).execute();
+				headerImage.setVisibility(View.GONE);
 			}
-		}
-		else{
-			headerImage.setVisibility(View.GONE);
-		}
 
-		//Get prices for single days
-		Cursor cursorDays = db.rawQuery("SELECT date, name_" + lang + ", price FROM festival_day WHERE strftime('%Y', date) = '" + year + "' ORDER BY date;", null);
-		LinearLayout list = (LinearLayout) view.findViewById(R.id.ll_lablanca_prices_days_list);
-		LinearLayout entry;
-		LayoutInflater factory = LayoutInflater.from(getActivity());
-		while (cursorDays.moveToNext()){
-
-			//Create a new row
-			entry = (LinearLayout) factory.inflate(R.layout.row_festival_price_day, null);
-
-			//Set margins
-			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
-			layoutParams.setMargins(10, 10, 10, 25);
-			entry.setLayoutParams(layoutParams);
-
-			//Set title
-			TextView tvName = (TextView) entry.findViewById(R.id.tv_row_festival_price_day_name);
-			tvName.setText(cursorDays.getString(1));
-
-			//Set price
-			TextView tvPrice = (TextView) entry.findViewById(R.id.tv_row_festival_price_day_price);
-			String price = cursorDays.getString(2) + " " + getString(R.string.eur);
-			tvPrice.setText(price);
-
-			//Set date
-			TextView tvDate = (TextView) entry.findViewById(R.id.tv_row_festival_price_day_date);
-			tvDate.setText(GM.formatDate(cursorDays.getString(0) + " 00:00:00", lang, false, false, false));
-			/*DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
-			Date date;
-			try {
-				date = format.parse(cursorDays.getString(0));
-				Calendar calendar = Calendar.getInstance();
-				calendar.setTime(date);
-				int day = calendar.get(Calendar.DAY_OF_MONTH);
-				int month = calendar.get(Calendar.MONTH);
-				switch (month){
-					case 6:
-						tvDate.setText(String.format(getString(R.string.lablanca_date_july), String.valueOf(day)));
-						break;
-					case 7:
-						tvDate.setText(String.format(getString(R.string.lablanca_date_august), String.valueOf(day)));
-						break;
+			//Get prices for single days
+			Cursor cursorDays = db.rawQuery("SELECT date, name_" + lang + ", price FROM festival_day WHERE strftime('%Y', date) = '" + year + "' ORDER BY date;", null);
+			LinearLayout list = (LinearLayout) view.findViewById(R.id.ll_lablanca_prices_days_list);
+			LinearLayout entry;
+			LayoutInflater factory = LayoutInflater.from(getActivity());
+			while (cursorDays.moveToNext()) {
+
+				//Create a new row
+				entry = (LinearLayout) factory.inflate(R.layout.row_festival_price_day, null);
+
+				//Set margins
+				LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
+				layoutParams.setMargins(10, 10, 10, 25);
+				entry.setLayoutParams(layoutParams);
+
+				//Set title
+				TextView tvName = (TextView) entry.findViewById(R.id.tv_row_festival_price_day_name);
+				tvName.setText(cursorDays.getString(1));
+
+				//Set price
+				TextView tvPrice = (TextView) entry.findViewById(R.id.tv_row_festival_price_day_price);
+				String price = cursorDays.getString(2) + " " + getString(R.string.eur);
+				tvPrice.setText(price);
+
+				//Set date
+				TextView tvDate = (TextView) entry.findViewById(R.id.tv_row_festival_price_day_date);
+				tvDate.setText(GM.formatDate(cursorDays.getString(0) + " 00:00:00", lang, false, false, false));
+				/*DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
+				Date date;
+				try {
+					date = format.parse(cursorDays.getString(0));
+					Calendar calendar = Calendar.getInstance();
+					calendar.setTime(date);
+					int day = calendar.get(Calendar.DAY_OF_MONTH);
+					int month = calendar.get(Calendar.MONTH);
+					switch (month){
+						case 6:
+							tvDate.setText(String.format(getString(R.string.lablanca_date_july), String.valueOf(day)));
+							break;
+						case 7:
+							tvDate.setText(String.format(getString(R.string.lablanca_date_august), String.valueOf(day)));
+							break;
+					}
 				}
+				catch(Exception ex){
+					Log.e("Date format error", ex.toString());
+				}*/
+
+				list.addView(entry);
 			}
-			catch(Exception ex){
-				Log.e("Date format error", ex.toString());
-			}*/
 
-			list.addView(entry);
-		}
+			//Get prices for single days
+			Cursor cursorPacks = db.rawQuery("SELECT name_" + lang + ", description_" + lang + ", price FROM festival_offer WHERE year = " + year + " ORDER BY days;", null);
+			list = (LinearLayout) view.findViewById(R.id.ll_lablanca_prices_packs_list);
+			while (cursorPacks.moveToNext()) {
 
-		//Get prices for single days
-		Cursor cursorPacks = db.rawQuery("SELECT name_" + lang + ", description_" + lang + ", price FROM festival_offer WHERE year = " + year + " ORDER BY days;", null);
-		list = (LinearLayout) view.findViewById(R.id.ll_lablanca_prices_packs_list);
-		while (cursorPacks.moveToNext()){
+				//Create a new row
+				entry = (LinearLayout) factory.inflate(R.layout.row_festival_price_pack, null);
 
-			//Create a new row
-			entry = (LinearLayout) factory.inflate(R.layout.row_festival_price_pack, null);
+				//Set margins
+				LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
+				layoutParams.setMargins(10, 10, 10, 25);
+				entry.setLayoutParams(layoutParams);
 
-			//Set margins
-			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
-			layoutParams.setMargins(10, 10, 10, 25);
-			entry.setLayoutParams(layoutParams);
+				//Set title
+				TextView tvName = (TextView) entry.findViewById(R.id.tv_row_festival_price_pack_name);
+				tvName.setText(cursorPacks.getString(0));
 
-			//Set title
-			TextView tvName = (TextView) entry.findViewById(R.id.tv_row_festival_price_pack_name);
-			tvName.setText(cursorPacks.getString(0));
+				//Set text
+				TextView tvText = (TextView) entry.findViewById(R.id.tv_row_festival_price_pack_text);
+				tvText.setText(cursorPacks.getString(1));
 
-			//Set text
-			TextView tvText = (TextView) entry.findViewById(R.id.tv_row_festival_price_pack_text);
-			tvText.setText(cursorPacks.getString(1));
+				//Set price
+				TextView tvPrice = (TextView) entry.findViewById(R.id.tv_row_festival_price_pack_price);
+				String price = cursorPacks.getString(2) + " " + getString(R.string.eur);
+				tvPrice.setText(price);
 
-			//Set price
-			TextView tvPrice = (TextView) entry.findViewById(R.id.tv_row_festival_price_pack_price);
-			String price = cursorPacks.getString(2) + " " + getString(R.string.eur);
-			tvPrice.setText(price);
+				list.addView(entry);
+			}
 
-			list.addView(entry);
+			cursorDays.close();
+			cursorPacks.close();
 		}
 
 		cursor.close();
-		cursorDays.close();
-		cursorPacks.close();
 		db.close();
 
 		//Set listeners for the schedule buttons.

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

@@ -47,7 +47,7 @@ import android.widget.TextView;
 /**
  * Fragment to be inflated showing the festivals schedule.
  * Contains a date selector and a ScrollView with all the activities for the day.
- * 
+ *
  * @author Inigo Valentin
  *
  */
@@ -59,24 +59,22 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 	private int dateCount = 0;
 	private int selected = 0;
 
-	//Indicates official schedule
-	private int schedule;
-
 	//Map stuff for the dialog
 	private MapView mapView;
 	private GoogleMap map;
 	private LatLng location;
+        private int route;
 	private View view;
 	private String markerName = "";
-	
+
 	/**
 	 * Run when the fragment is inflated.
 	 * Assigns views, gets the date and does the first call to the populateSchedule function.
-	 * 
+	 *
 	 * @param inflater A LayoutInflater to manage views
 	 * @param container The container View
 	 * @param savedInstanceState Bundle containing the state
-	 * 
+	 *
 	 * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
 	 */
 	@SuppressLint("InflateParams") //Throws unknown error when done properly.
@@ -89,7 +87,7 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 
 		//Set bundle for the map
 		bund = savedInstanceState;
-		
+
 		//Load the layout
 		view = inflater.inflate(R.layout.fragment_layout_schedule, null);
 		view.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@@ -104,8 +102,8 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 		//Get schedule type
 		TextView title = (TextView) view.findViewById(R.id.tv_schedule_type);
 		Bundle bundle = this.getArguments();
-		schedule = bundle.getInt(GM.SCHEDULE.KEY, GM.SCHEDULE.CITY);
-		
+		final int schedule = bundle.getInt(GM.SCHEDULE.KEY, GM.SCHEDULE.CITY);
+
 		//Set the title
 		if (schedule == GM.SCHEDULE.CITY) {
 			((MainActivity) getActivity()).setSectionTitle(view.getContext().getString(R.string.menu_lablanca_schedule));
@@ -121,10 +119,10 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 		SQLiteDatabase db = SQLiteDatabase.openDatabase(getActivity().getDatabasePath(GM.DB.NAME).getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS | SQLiteDatabase.OPEN_READONLY);
 		Cursor cursor;
 		if (schedule == GM.SCHEDULE.MARGOLARIAK) {
-			cursor = db.rawQuery("SELECT DISTINCT date(start) AS daydate FROM festival_event WHERE strftime('%Y', start) = '" + year + "' AND strftime('%H', start) > '06' AND gm = 1 ORDER BY daydate;", null);
+			cursor = db.rawQuery("SELECT DISTINCT date(start) AS daydate FROM festival_event_gm WHERE strftime('%Y', start) = '" + year + "' AND strftime('%H', start) > '06' ORDER BY daydate;", null);
 		}
 		else{
-			cursor = db.rawQuery("SELECT DISTINCT date(start) AS daydate FROM festival_event WHERE strftime('%Y', start) = '" + year + "' AND strftime('%H', start) > '06' AND gm = 0 ORDER BY daydate;", null);
+			cursor = db.rawQuery("SELECT DISTINCT date(start) AS daydate FROM festival_event_vity WHERE strftime('%Y', start) = '" + year + "' AND strftime('%H', start) > '06' ORDER BY daydate;", null);
 		}
 
 
@@ -152,17 +150,17 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 			@Override
 			public void onClick(View v) {
 				selected --;
-				populateSchedule();
+				populateSchedule(schedule);
 			}
 		});
 		btR.setOnClickListener(new OnClickListener() {
 			@Override
 			public void onClick(View v) {
 				selected ++;
-				populateSchedule();
+				populateSchedule(schedule);
 			}
 		});
-		
+
 		//Assign the filter text
 		EditText etFilter = (EditText) view.findViewById(R.id.et_schedule_filter);
 		etFilter.addTextChangedListener(new TextWatcher() {
@@ -176,25 +174,25 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 	        @Override
 	        public void onTextChanged(CharSequence s, int start, int before, int count) {
 	        	//Repopulate when the text is changed
-	        	populateSchedule();
-	          
+	        	populateSchedule(schedule);
 	        }
 		});
-		
+
 		//Populate the activity list
-		populateSchedule();
-		
+		populateSchedule(schedule);
+
 		//Return the fragment view
 		return view;
 	}
 
 	/**
-	 * Populates the list of activities with the ones n the selected day.
-	 * 
+	 * Populates the list of activities with the ones in the selected day.
+	 *
+	 * @param schedule GM.SCHEDULE.GM or GM.SCHEDULE.CITY
 	 */
 	@SuppressLint({"InflateParams", "SwitchIntDef"})
 	//Views are added from a loop: I can't specify the parent when inflating.
-	private int populateSchedule() {
+	private int populateSchedule(final int schedule) {
 
 		int eventCount = 0;
 
@@ -280,12 +278,13 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 		c.add(Calendar.DATE, 1);  // number of days to add
 		String endDate = sdf.format(c.getTime());
 
-		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 ";
+		String query = "";;
 
 		if (schedule == GM.SCHEDULE.MARGOLARIAK) {
-			query = query + "gm = 1 ";
-		} else {
-			query = query + "gm = 0 ";
+			query = "SELECT festival_event_gm.id, title_" + lang + ", description_" + lang + ", place, start, end, name_" + lang + ", address_" + lang + ", lat, lon FROM festival_event_gm, place WHERE place = place.id AND start >= '" + dates[selected] + " 06:00:00' AND start < '" + endDate + " 05:59:59'";
+		}
+		else {
+			query = "SELECT festival_event_city.id, title_" + lang + ", description_" + lang + ", place, start, end, name_" + lang + ", address_" + lang + ", lat, lon FROM festival_event_city, place WHERE place = place.id AND start >= '" + dates[selected] + " 06:00:00' AND start < '" + endDate + " 05:59:59'";
 		}
 		if (filter.length() > 0) {
 			query = query + "AND (title_" + lang + " like '%" + filter + "%' OR description_" + lang + " like '%" + filter + "%' OR name_" + lang + " like '%" + filter + "%' OR address_" + lang + " like '%" + filter + "%') ";
@@ -348,7 +347,7 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 				public void onClick(View v) {
 					TextView tvId = (TextView) v.findViewById(R.id.tv_row_schedule_id);
 					int id = Integer.parseInt(tvId.getText().toString());
-					showDialog(id);
+					showDialog(id, schedule);
 				}
 			});
 
@@ -371,27 +370,28 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 		return eventCount;
 
 	}
-	
+
 	/**
 	 * Shows a dialog with info about the selected event.
-	 * 
+	 *
 	 * @param id The event id
+	 * @param schedule GM.SCHEDULE.GM or GM.SCHEDULE.CITY
 	 */
 	@SuppressWarnings("ConstantConditions")
-	private void showDialog(final int id){
-		
+	private void showDialog(final int id, final int schedule){
+
 		//Create the dialog
 		final Dialog dialog = new Dialog(getActivity());
-		
+
 		//Set up dialog window
 		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
 		dialog.setContentView(R.layout.dialog_schedule);
-		
+
 		//Date formatters
 		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
 		SimpleDateFormat dayFormat = new SimpleDateFormat("yyyy-MM-dd-", Locale.US);
 		SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.US);
- 
+
 		//Set the custom dialog components - text, image and button
 		TextView tvTitle = (TextView) dialog.findViewById(R.id.tv_dialog_schedule_title);
 		TextView tvDescription = (TextView) dialog.findViewById(R.id.tv_dialog_schedule_description);
@@ -401,18 +401,24 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 		TextView tvPlace = (TextView) dialog.findViewById(R.id.tv_dialog_schedule_place);
 		TextView tvAddress = (TextView) dialog.findViewById(R.id.tv_dialog_schedule_address);
 		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);
 		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);
+		Cursor cursor;
+		if (schedule == GM.SCHEDULE.MARGOLARIAK){
+			cursor = db.rawQuery("SELECT festival_event_gm.id, title_" + lang + ", description_" + lang + ", place, route, start, end, name_" + lang + ", address_" + lang + ", lat, lon, host, sponsor FROM festival_event_gm, place WHERE place = place.id AND festival_event_gm.id = " + id + ";", null);
+		}
+		else{
+			cursor = db.rawQuery("SELECT festival_event_city.id, title_" + lang + ", description_" + lang + ", place, route, start, end, name_" + lang + ", address_" + lang + ", lat, lon, host FROM, sponsor festival_event_city, place WHERE place = place.id AND festival_event_city.id = " + id + ";", null);
+		}
 		if (cursor.getCount() > 0){
 			cursor.moveToNext();
-		
+
 			//Set title
 			tvTitle.setText(cursor.getString(1));
 			markerName = cursor.getString(1);
-			
+
 			//Set description
 			if (cursor.getString(2) != null && cursor.getString(2).length() > 0) {
 				tvDescription.setText(cursor.getString(2));
@@ -420,7 +426,7 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 			else{
 				tvDescription.setVisibility(View.GONE);
 			}
-			
+
 			//Set host
 			if (cursor.getString(10) != null){
 				Cursor hostCursor = db.rawQuery("SELECT name_" + lang + " FROM people WHERE id = " + cursor.getString(10) + ";", null);
@@ -429,11 +435,12 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 					tvHost.setText(String.format(getString(R.string.schedule_host), hostCursor.getString(0)));
 				}
 				hostCursor.close();
+				// TODO. Add sponsor.
 			}
 			else{
 				tvHost.setVisibility(View.GONE);
-			}				
-			
+			}
+
 			//Set date
 			try{
 				Date day = dateFormat.parse(cursor.getString(4));
@@ -441,17 +448,16 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 				//If the event is today, show "Today" instead of the date
 				if (dayFormat.format(day).equals(dayFormat.format(date)))
 					tvDate.setText(dialog.getContext().getString(R.string.today));
-				
 				else{
 					Calendar cal = Calendar.getInstance();
 				    cal.setTime(date);
 				    cal.add(Calendar.HOUR_OF_DAY, 24);
-				    
+
 				    //If the event is tomorrow, show "Tomorrow" instead of the date
 				    if (dayFormat.format(cal.getTime()).equals(dayFormat.format(date))){
 				    	tvDate.setText(dialog.getContext().getString(R.string.tomorrow));
 				    }
-					
+
 				    //Else, show the date
 				    else{
 						SimpleDateFormat printFormat;
@@ -478,7 +484,7 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 			catch (Exception ex){
 				Log.e("Error parsing date", ex.toString());
 			}
-			
+
 			//Set time
 			try{
 				if (cursor.getString(5) == null || cursor.getString(5).length() == 0) {
@@ -492,28 +498,29 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 			catch (ParseException ex){
 				Log.e("Error parsing time", ex.toString());
 			}
-			
+
 			//Set the place
 			tvPlace.setText(cursor.getString(6));
 			tvAddress.setText(cursor.getString(7));
-			
+
 			//Set up map
+			// TODO if route...
 			location = new LatLng(Double.parseDouble(cursor.getString(8)), Double.parseDouble(cursor.getString(9)));
 			mapView = (MapView) dialog.findViewById(R.id.mv_dialog_schedule_map);
 			mapView.onCreate(bund);
-			
+
 			//Close the db connection
 			cursor.close();
 			db.close();
-			
-			//Set close button			
-        	btClose.setOnClickListener(new OnClickListener() {
-    			@Override
-    			public void onClick(View v) {
-    				dialog.dismiss();
-    			}
-    		});
-			
+
+			//Set close button
+	        	btClose.setOnClickListener(new OnClickListener() {
+	    			@Override
+	    			public void onClick(View v) {
+    					dialog.dismiss();
+    				}
+    			});
+
 			//Actions to take when the dialog is cancelled
 			dialog.setOnCancelListener(new OnCancelListener(){
 				@Override
@@ -524,12 +531,12 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 						}
 					}
 					if (mapView != null){
-    					mapView.onResume();
-    					mapView.onDestroy();
-    				}					
+    						mapView.onResume();
+    						mapView.onDestroy();
+    					}
 				}
 			});
-			
+
 			//Show the dialog
 			WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
 			lp.copyFrom(dialog.getWindow().getAttributes());
@@ -541,7 +548,7 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 
 			//Show dialog
 			dialog.show();
-			
+
 			//Start the map
 			startMap();
 			mapView.onResume();
@@ -551,24 +558,24 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 				public void onShow(DialogInterface dialog) {
 					// Gets to GoogleMap from the MapView and does initialization stuff
 					startMap();
-					
+
 				}
-			});		
-			
+			});
+
 		}
 	}
-	
+
 	/**
 	 * Starts the map in the dialog.
 	 */
 	private void startMap(){
 		mapView.getMapAsync(this);
 	}
-	
+
 	/**
-	 * Called when the fragment is brought back into the foreground. 
+	 * Called when the fragment is brought back into the foreground.
 	 * Resumes the map and the location manager.
-	 * 
+	 *
 	 * @see android.app.Fragment#onResume()
 	 */
 	@Override
@@ -584,9 +591,9 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 	}
 
 	/**
-	 * Called when the fragment is destroyed. 
-	 * Finishes the map. 
-	 * 
+	 * Called when the fragment is destroyed.
+	 * Finishes the map.
+	 *
 	 * @see android.app.Fragment#onDestroy()
 	 */
 	@Override
@@ -607,11 +614,11 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 			}
 		}
 	}
-	
+
 	/**
-	 * Called when the fragment is paused. 
-	 * Finishes the map. 
-	 * 
+	 * Called when the fragment is paused.
+	 * Finishes the map.
+	 *
 	 * @see android.app.Fragment#onPause()
 	 */
 	@Override
@@ -640,7 +647,7 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 	/**
 	 * Called in a situation of low memory.
 	 * Lets the map handle this situation.
-	 * 
+	 *
 	 * @see android.app.Fragment#onLowMemory()
 	 */
 	@Override
@@ -653,17 +660,17 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 	}
 
 	/**
-	 * Called when the map is ready to be displayed. 
+	 * Called when the map is ready to be displayed.
 	 * Sets the map options and a marker for the map.
-	 * 
+	 *
 	 * @param googleMap The map to be shown
-	 * 
+	 *
 	 * @see com.google.android.gms.maps.OnMapReadyCallback#onMapReady(com.google.android.gms.maps.GoogleMap)
 	 */
 	@Override
 	public void onMapReady(GoogleMap googleMap) {
 		this.map = googleMap;
-		
+
 		map.getUiSettings().setMyLocationButtonEnabled(false);
 		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)) {
 			map.setMyLocationEnabled(true);
@@ -682,7 +689,7 @@ public class ScheduleLayout extends Fragment implements OnMapReadyCallback{
 		mo.title(markerName);
 		mo.position(location);
 		map.addMarker(mo);
-		
+
 	}
-		
+
 }

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

@@ -435,8 +435,6 @@ class Sync extends AsyncTask<Void, Void, Void> {
 				try {
 					name = str.substring(str.indexOf("\"") + 1, str.indexOf(":") -1);
 					content = str.substring(str.indexOf("[{"), str.indexOf("}]") + 2);
-					Log.e("SYNC3", "Saving data key " + name + " string: " + str);
-
 
 					if (!saveTable(db, name, content)){
 						//Finish the loop if there is an error
@@ -534,8 +532,6 @@ class Sync extends AsyncTask<Void, Void, Void> {
 	 */
 	private boolean saveTableVersion(SQLiteDatabase db, String data) {
 
-		Log.e("SYNC3", "UPDATING versions WITH content: " + data);
-
 		JSONObject jsonObj;
 		String section, row, version;
 		String str = data;
@@ -545,7 +541,6 @@ class Sync extends AsyncTask<Void, Void, Void> {
 		//Process each row
 		while (str.contains("{\"") && str.contains("\"}")) {
 			row = str.substring(str.indexOf("{\""), str.indexOf("\"}") + 2);
-			Log.e("SYNC3", "ROW: " + row);
 			try {
 
 				section = row.substring(row.indexOf("\"section\"") + 11, row.indexOf(",") + -1);
@@ -553,10 +548,8 @@ class Sync extends AsyncTask<Void, Void, Void> {
 				// Check if the value already exists in the database.
 				cursor = db.rawQuery("SELECT section FROM version WHERE version = '" + section + "';", null);
 				if (cursor.getCount() == 0) {
-					Log.e("SYNC3", "INSERT INTO version (section, version) VALUES ('" + section + "', " + version + ");");
 					queries.add("INSERT INTO version (section, version) VALUES ('" + section + "', " + version + ");");
 				} else {
-					Log.e("SYNC3", "UPDATE version SET version = " + version + " WHERE section  ='" + section + "';");
 					queries.add("UPDATE version SET version = " + version + " WHERE section  ='" + section + "';");
 				}
 				cursor.close();
@@ -599,7 +592,6 @@ class Sync extends AsyncTask<Void, Void, Void> {
 	 */
 	private boolean saveTable(SQLiteDatabase db, String table, String data) {
 
-		Log.d("SYNC3", "Saving table " + table + " with data: " + data);
 		//If table, do something else
 		if (GM.DB.TABLE.SETTINGS.equals(table)){
 			Log.d("SYNC", "Got the settings table. Special treatment...");
@@ -623,8 +615,16 @@ class Sync extends AsyncTask<Void, Void, Void> {
 		queries.add("DELETE FROM " + table + ";");
 
 		//Process each row
-		while (str.contains("{\"") && str.contains("\"}")) {
-			row = str.substring(str.indexOf("{\""), str.indexOf("\"}") + 2);
+		str = str.replace(":null", ":\"null\"");
+
+		while (str.contains("{\"") && (str.contains("\"}") || str.contains("null}"))) {
+			if (str.contains("\"}")) {
+				row = str.substring(str.indexOf("{\""), str.indexOf("\"}") + 2);
+			}
+			else{
+				row = str.substring(str.indexOf("{\""), str.indexOf("null}") + 5);
+			}
+
 			i = 0;
 
 			try {
@@ -654,8 +654,8 @@ class Sync extends AsyncTask<Void, Void, Void> {
 				//Loop trough values
 				for (int j = 0; j < i; j++) {
 
-					//If the value is empty, I don't care what type is it, it will be 'null'.
-					if (values[j].length() == 0) {
+					//If the value is empty or null, I don't care what type is it, it will be 'null'.
+					if (values[j].length() == 0 || "null".equalsIgnoreCase(values[j])) {
 						val = "null";
 						q = q + val + ", ";
 					}
@@ -785,17 +785,21 @@ class Sync extends AsyncTask<Void, Void, Void> {
 					publishProgress();
 
 					//If the data is correctly parsed and stored, commit changes to the database.
-					db.beginTransactionNonExclusive();
+					try {
+						db.beginTransactionNonExclusive();
 
 
-					if (saveData(db, strSync)){
-						db.setTransactionSuccessful();
-						Log.d("SYNC", "The sync process finished correctly. Changes to the database will be commited");
+						if (saveData(db, strSync)) {
+							db.setTransactionSuccessful();
+							Log.d("SYNC", "The sync process finished correctly. Changes to the database will be commited");
+						} else {
+							Log.e("SYNC", "The sync process did not finish correctly. Any changes made to the database will be reverted");
+						}
+						db.endTransaction();
 					}
-					else{
-						Log.e("SYNC", "The sync process did not finish correctly. Any changes made to the database will be reverted");
+					catch(SQLiteDatabaseLockedException ex){
+						Log.e("SYNC", "Database is locked . Ending sync now: " + ex.toString());
 					}
-					db.endTransaction();
 
 					break;
 				default: