package kz.istt.locust;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.FragmentActivity;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;
import java.util.zip.CRC32;

import dbfields.AutoCompleteTextViewDB;
import dbfields.StringDB;
import dbfields.fieldDB;
import dbfields.selectDB;
import tools.LatLonListener;
import tools.OnClickListenerDateTime;

public class LocustActivity extends FragmentActivity implements LocationListener, LatLonListener {
	private LocationManager lm;
	private ScrollView scrollView1 = null;

	public double _lat = 0; // от устройства
	public double _lon = 0; // от устройства

	public String uid = ""; // Идентификатор записи null по умолчанию
	public Integer del = null;
	public Long seq = null; // Дата изменения записи секунд с 1970 года
	public StringDB m_Filled = new StringDB("1"); // 1- все обяз. поля заполнены, 0 - не все обяз. поля заполнены
	//public Long			created						= null; // Дата создания записи секунд с 1970 года (только для не синхронизированных записей на планшете)
	//public Integer			user_id						= null;

	public String ImageName = null; // Название файла рисунка
	public String tmp_ImageName = null; // Временое название рисунка

	public EditText edtImage1 = null; // Фотография
	public EditText edtImage2 = null; // Фотография
	public EditText edtImage3 = null; // Фотография
	public View spiCountry = null; // Страна

	public View spiRegion = null; // Регион
	public EditText edtArea = null; // Район
	public EditText edtDistrict = null; // Сельский округ и/или хозяйство

	public EditText edtVillage = null; // Посёлка
	public EditText edtTerrain = null;    // Название местности либо урочища

	public EditText edtObserver = null; // ФИО наблюдателя

	public EditText edtDate = null; // Дата (передаётся в секундах с 1970 года)
	public EditText edtTimeZone = null;
	// public TimeInput edtTime = null; //Время

	public EditText edtLatCenter	= null;				// Широта
	public EditText edtLonCenter	= null;				// Долгота
	public ListView latlonList	= null;

	public EditText edtBioHectare = null; // обследованная площадь(га)

	public View spiBioBiotope = null; // тип биотопаCIT (степь, залежь, посевы) тип биотопаDMA (равнины, холмы, посевы) тип биотопаLMI
	// (низкие сухие тростники, высокие влажные тростники, другое)
	public View spiBioGreenery = null; // растительность: сухая, всходы, зеленая, засыхающая
	public View spiBioGreeneryCover = null; // растительный покров(Редкий, Ср., Густой)
	public EditText edtBioTemperature = null; // погода: температура воздуха(ºC)
	public EditText edtBioWind = null; // погода: ветер(м/с)
	public View spiLocustType = null; // Вид саранчи

	public View spiLocustHave = null; // Присутствует саранча или нет

	public EditText edtLocustPopulated = null; // Заселённая площадь(га)

	public CheckBox cbEggs = null;
	public EditText edtEggsCapsulesArea = null; // залежь кубышек (площадь в м2)
	public EditText edtEggsCapsulesDensity = null; // кубышки(плотность на м2) от
	public EditText edtEggsCapsulesDensityTo = null; // кубышки(плотность на м2) до
	public EditText edtEggsCapsules = null; // яйца(в среднем в кубышке)
	public EditText edtEggsLive = null; // яйца(% жизнеспособных)
	public View spiEggsEnemies = null; // Естественные враги

	public CheckBox cbHoppers = null;
	public View spiLarvaBorn = null; // отрождение
	public View spiLarvaAge = null; // возраста: Младшие Средние Старшие
	public View spiLarvaPainting = null; // окраска(одиночнаяS, перехoдная Т, стаднаяG)
	public View spiLarvaBehavior = null; // поведение(�?золир., Разреженные, Группы)
	public EditText edtLarvaDensity = null; // плотность на м2
	public EditText edtLarvaDensityTo = null; // плотность на м2

	public CheckBox cbBands = null;
	public EditText edtKuliguliDensity = null; // плотн. в кулиге(на м2)
	public EditText edtKuliguliDensityTo = null; // плотн. в кулиге(на м2) до
	public EditText edtKuliguliSize = null; // размер кулиг(га)
	public EditText edtKuliguliCount = null; // число кулиг
	public View spiKuliguliAction = null; // поведение: миграция, кормёжка, отдых
	public View spiKuliguliAge = null; // возраста: Младшие Средние Старшие

	public CheckBox cbAdults = null;
	public View spiImagoWing = null; // окрыление(начало, массовое)
	public View spiImagoMaturity = null; // половозрелость(- или+)
	public View spiImagoPhase = null; // фаза(одиночнаяS, перехoдная Т, стаднаяG)
	public View spiImagoAction = null; // поведение(�?золир., Разреженные, Группы)
	public EditText edtImagoDensity = null; // плотность(на трансекту или га)
	public EditText edtImagoDensityGa = null; // плотность на га

	public View spiImagoFeeding = null; //Питание и размещение на растениях

	public View spiImagoCopulation = null; // спаривание (да,нет)
	public View spiImagolaying = null; // яйцекладка (да,нет)

	public View spiImagoFlying = null; // полёты(- или+)

	public CheckBox cbSwarms = null;
	public View spiSwarmMaturity = null; // половозрелость(- или+)
	public View spiSwarmDensity = null; // плотность(на м2)
	public EditText edtSwarmSize = null; // размер стаи(на км2)
	public EditText edtSwarmCount = null; // число стай
	public View spiSwarmFlying = null; // полёт(направление, время пролёта)
	public View spiSwarmHeight = null; // высота(Низкая- Средняя- Высокая)

	public EditText edtDescription = null; // КОММЕНТАРИИ
	public CheckBox cbTest; //Тестовая ли анкета

	public View btnOk = null;
	public View btnCancel = null;
	public View btnGetGPSCenter = null;
	public View btnDelGPSCenter	= null;
	public View btnOnMap = null;

	public View btnImage1 = null;
	public View btnImage2 = null;
	public View btnImage3 = null;
	public View btnShowImage1 = null;
	public View btnShowImage2 = null;
	public View btnShowImage3 = null;
	public View btnDelImage1 = null;
	public View btnDelImage2 = null;
	public View btnDelImage3 = null;

	private Uri mImageUri = null;

	private DBGUITable guiTable = null;

	private boolean isInRange(float a, float b, float c) {
		return b > a ? c >= a && c <= b : c >= b && c <= a;
	}

	public String checkMinMaxI(EditText txt, int min, int max) {
		try {
			float input = Float.parseFloat(txt.getText().toString());
			if (isInRange(min, max, input))
				return "";
			else
				return "MIN=" + Float.toString(min) + " MAX=" + Float.toString(max) + " ! ";
		} catch (NumberFormatException nfe) {
		}
		return "";
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_locust);

		//Загрузка сохранёного языка
		Tools.loadLocale(this);

		String sql;
		DbOpenHelper dboh;
		Cursor cursor;

		Intent intent = getIntent();
		uid = intent.getStringExtra("uid");
		guiTable = new DBGUITable(this, "frmlocust");
		guiTable.add(uid, "uid");

		Integer user_id = null;
		/*DbOpenHelper dboh = new DbOpenHelper(this);
		SQLiteDatabase db = dboh.getReadableDatabase();
		Cursor cursor = db.rawQuery("select id from _user where del=0;", null);
		if(cursor.moveToFirst())
		{
			user_id = Integer.valueOf(cursor.getInt(cursor.getColumnIndex("id")));
		}
		cursor.close();
		dboh.close();*/
		guiTable.add(user_id, "user_id");
		String device_id = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
		guiTable.add(device_id, "device_id"); //Идентификатор устройства

		//List<String> list;
		//ArrayAdapter<String> dataAdapter;

		scrollView1 = (ScrollView) findViewById(R.id.scrollView1);

		guiTable.add(m_Filled, "filled");

		edtImage1 = (EditText) findViewById(R.id.edtImage1);
		guiTable.add(edtImage1, "image_name1");
		edtImage2 = (EditText) findViewById(R.id.edtImage2);
		guiTable.add(edtImage2, "image_name2");
		edtImage3 = (EditText) findViewById(R.id.edtImage3);
		guiTable.add(edtImage3, "image_name3");

		spiCountry = findViewById(R.id.spiCountry); // Страна
		guiTable.add(spiCountry, "country_id"); //Для сохранения по id

		((selectDB)spiCountry).addField("", "");
		// Выбираем страны и заполняем поля
		dboh = new DbOpenHelper(this);
		SQLiteDatabase rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select c.id, COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = c.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),c.name) name from countries c where c.del=0 order by c.name", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB) spiCountry).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		//----------------------------------------------------------------------------------------------
		/*spiCountry0 = (AutoCompleteTextView) findViewById(R.id.spiCountry0); // Страна
		spiCountry0.setInputType(InputType.TYPE_NULL);
		List<String> m_lName = new ArrayList<String>(); //Заголовки
		m_lName.add("");
		m_lName.add("India");
		m_lName.add("Usa");
		m_lName.add("Canada");
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, m_lName);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spiCountry0.setAdapter(dataAdapter);*/
		//----------------------------------------------------------------------------------------------


		// Событие чтоб при изменении страны обновлялся список регионов
		((selectDB)spiCountry).setOnChangeValueListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						((selectDB)spiRegion).clearFields();
						((selectDB)spiRegion).addField("", "");

						if (((selectDB)spiCountry).getValue() != null && !((selectDB)spiCountry).getValue().equals("")) {
							String sql = "select id, name, lon_min from countriesregions where del=0 and country_id=" + ((selectDB)spiCountry).getValue() + " order by name";
							DbOpenHelper dboh = new DbOpenHelper(LocustActivity.this);
							SQLiteDatabase rdb = null;
							Cursor cursor = null;
							try {
								rdb = dboh.getReadableDatabase();
								cursor = rdb.rawQuery(sql, null);
								if (cursor.moveToFirst()) {
									do {
										((selectDB)spiRegion).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
									} while (cursor.moveToNext());
								}
							}catch(Exception e){
								e.printStackTrace();
							}finally{
								if(cursor != null) { cursor.close(); }
								if(rdb!=null){ rdb.close(); }
							}
							dboh.close();
						}
					}
				}
		);

		spiRegion = findViewById(R.id.spiRegion); // Регион
		guiTable.add(spiRegion, "region_id");

		edtArea = (EditText) findViewById(R.id.edtArea); // Район
		guiTable.add(edtArea, "area");
		edtDistrict = (EditText) findViewById(R.id.edtDistrict); // Сельский округ и/или хозяйство
		guiTable.add(edtDistrict, "district");

		edtVillage = (EditText) findViewById(R.id.edtVillage); // Посёлок
		guiTable.add(edtVillage, "village");
		edtTerrain = (EditText) findViewById(R.id.edtTerrain); // Местность урощище
		guiTable.add(edtTerrain, "terrain");

		edtObserver = (EditText) findViewById(R.id.edtObserver); // Наблюдатель
		guiTable.add(edtObserver, "observer");
		edtDate = (EditText) findViewById(R.id.edtDate); // Дата
		guiTable.add(edtDate, "date"); //Обязательное поле!

		View btnGetDate = (View) findViewById(R.id.btnGetDate);
		btnGetDate.setOnClickListener(new OnClickListenerDateTime((fieldDB)edtDate,this));

//Закоментил так как создал отдельный класс: OnClickListenerDateTime2
//		View.OnClickListener clk0 = new View.OnClickListener() {
//			public void onClick(View v) {
//				DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
//					@Override
//					public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//
//						//SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy HH:mm");
//						//format.setTimeZone(TimeZone.getTimeZone("UTC"));
//						//LocustActivity.this.edtDate.setText(format.format(curDateTime));
//
//						//Теперь выбираем время
//						OnTimeSetListener myDateListener = new OnTimeSetListener() {
//							@Override
//							public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//								long val = Long.parseLong(((fieldDB)LocustActivity.this.edtDate).getValue());
//								val += (hourOfDay * 60 + minute) * 60;
//								((fieldDB)LocustActivity.this.edtDate).setValue(String.valueOf(val));
//							}
//						};
//
//						if (((fieldDB)LocustActivity.this.edtDate).getValue() != null && !((fieldDB)LocustActivity.this.edtDate).getValue().equals("")) {
//							Date time = new Date(Long.parseLong(((fieldDB)LocustActivity.this.edtDate).getValue()) * 1000);
//							Calendar myCal = new GregorianCalendar();
//							myCal.setTime(time);
//							int hour = myCal.get(Calendar.HOUR_OF_DAY);
//							int minute = myCal.get(Calendar.MINUTE);
//							TimePickerDialog tpd = new TimePickerDialog(LocustActivity.this, R.style.AlertDialogTheme, myDateListener, hour, minute, true);
//							tpd.show();
//						} else {
//							final Calendar myCal = Calendar.getInstance();
//							int hour = myCal.get(Calendar.HOUR_OF_DAY);
//							int minute = myCal.get(Calendar.MINUTE);
//							TimePickerDialog tpd = new TimePickerDialog(LocustActivity.this, R.style.AlertDialogTheme, myDateListener, hour, minute, true);
//							tpd.show();
//						}
//
//						Date date = new Date(year - 1900, monthOfYear, dayOfMonth);
//						((fieldDB)LocustActivity.this.edtDate).setValue(String.valueOf(date.getTime() / 1000));
//					}
//				};
//
//				if (!LocustActivity.this.edtDate.getText().toString().equals("")) {
//					Date date = null;
//					SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy HH:mm");
//					//format.setTimeZone(TimeZone.getTimeZone("UTC"));
//					try {
//						date = format.parse(LocustActivity.this.edtDate.getText().toString());
//					} catch (ParseException e) {
//						e.printStackTrace();
//					}
//					if (date != null) {
//						Calendar myCal = new GregorianCalendar();
//						myCal.setTime(date);
//						int day = myCal.get(Calendar.DAY_OF_MONTH);
//						int month = myCal.get(Calendar.MONTH);
//						int year = myCal.get(Calendar.YEAR);
//						DatePickerDialog dpd = new DatePickerDialog(LocustActivity.this, R.style.AlertDialogTheme, myDateListener, year, month, day);
//						dpd.show();
//					}
//				} else {
//					final Calendar c = Calendar.getInstance();
//					int year = c.get(Calendar.YEAR);
//					int month = c.get(Calendar.MONTH);
//					int day = c.get(Calendar.DAY_OF_MONTH);
//
//					DatePickerDialog dpd = new DatePickerDialog(LocustActivity.this, R.style.AlertDialogTheme, myDateListener, year, month, day);
//					dpd.show();
//				}
//			}
//		};
//		btnGetDate.setOnClickListener(clk0);

		edtTimeZone = (EditText) findViewById(R.id.edtTimeZone);
		guiTable.add(edtTimeZone, "timezone");

		edtLatCenter = (EditText) findViewById(R.id.edtLatCenter); // Широта
		guiTable.add(edtLatCenter, "lat_center");
		edtLonCenter = (EditText) findViewById(R.id.edtLonCenter); // Долгота
		guiTable.add(edtLonCenter, "lon_center");

		ArrayList<LatLon> latlon = new ArrayList<LatLon>();
		if(latlon.size()==0){
			latlon.add(new LatLon(UUID.randomUUID().toString(),0, 0));
		}
		latlonList = findViewById(R.id.latlonList);
		LatLonAdapter adapter = new LatLonAdapter(this, R.layout.list_lat_lon, latlon, this, latlonList,false);
		latlonList.setAdapter(adapter);
		adapter.clc=new OnClickListener() {
			@Override
			public void onClick(View view) {
				Tools.setListViewHeightBasedOnItems(LocustActivity.this.latlonList);
			}
		};

		edtBioHectare = (EditText) findViewById(R.id.edtBioHectare); // обследованная площадь(га)
		guiTable.add(edtBioHectare, "bio_hectare");

		spiBioBiotope = findViewById(R.id.spiBioBiotope); // Тип биотопа
		guiTable.add(spiBioBiotope, "bio_biotope_id");
		((selectDB)spiBioBiotope).addField("", "");
		// Выбираем страны и заполняем поля
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select b.id, COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = b.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),b.name) name from list_biotope b where b.del=0 order by b.name", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiBioBiotope).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		spiBioGreenery = findViewById(R.id.spiBioGreenery); // Растительность
		guiTable.add(spiBioGreenery, "bio_greenery_id");
		((selectDB)spiBioGreenery).addField("", "");
		// Выбираем страны и заполняем поля
		sql = "select g.id, COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = g.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),g.name) name from list_greenery g where g.del=0 order by g.sort";
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery(sql, null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiBioGreenery).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		spiBioGreeneryCover = findViewById(R.id.spiBioGreeneryCover); // Растительный покров
		guiTable.add(spiBioGreeneryCover, "bio_greenery_cover_id");
		((selectDB)spiBioGreeneryCover).addField("", "");
		// Выбираем страны и заполняем поля
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select c.id, COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = c.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),c.name) name from list_cover c where c.del=0 order by c.sort,c.name", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiBioGreeneryCover).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		edtBioTemperature = (EditText) findViewById(R.id.edtBioTemperature); // Температура воздуха
		guiTable.add(edtBioTemperature, "bio_temperature");
		edtBioWind = (EditText) findViewById(R.id.edtBioWind); // погода: ветер(м/с)
		guiTable.add(edtBioWind, "bio_wind");

		spiLocustHave = findViewById(R.id.spiLocustHave); // Присутствует саранча или нет
		guiTable.add(spiLocustHave, "locust_have");
		//spiLocustHave.addField(this, getString(R.string.Yes), "1");
		((selectDB)spiLocustHave).addField(getString(R.string.Absent), "0");
		((selectDB)spiLocustHave).addField(getString(R.string.Egg_pod), "2");
		((selectDB)spiLocustHave).addField(getString(R.string.HOPPERS_SCATTERED), "3");
		((selectDB)spiLocustHave).addField(getString(R.string.Bands), "4");
		((selectDB)spiLocustHave).addField(getString(R.string.Adult), "5");
		((selectDB)spiLocustHave).addField(getString(R.string.Swarms), "6");

		spiLocustType = findViewById(R.id.spiLocustType);
		guiTable.add(spiLocustType, "locust_type_id");
		((selectDB)spiLocustType).addField("", "");
		// Выбираем страны и заполняем поля
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select lt.id, COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = lt.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),lt.name) name from LocustsTypes lt where lt.del=0 order by lt.sort,lt.name", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiLocustType).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		edtLocustPopulated = (EditText) findViewById(R.id.edtLocustPopulated);
		guiTable.add(edtLocustPopulated, "locust_populated");

		//Яйца
		edtEggsCapsulesArea = (EditText) findViewById(R.id.edtEggsCapsulesArea); // залежь кубышек (площадь в м2)
		guiTable.add(edtEggsCapsulesArea, "eggs_capsules_area");
		edtEggsCapsulesDensity = (EditText) findViewById(R.id.edtEggsCapsulesDensity); // кубышки(плотность на м2) от
		guiTable.add(edtEggsCapsulesDensity, "eggs_capsules_density");
		edtEggsCapsulesDensityTo = (EditText) findViewById(R.id.edtEggsCapsulesDensityTo); // кубышки(плотность на м2) до
		guiTable.add(edtEggsCapsulesDensityTo, "eggs_capsules_density_to");
		edtEggsCapsules = (EditText) findViewById(R.id.edtEggsCapsules); // яйца(в среднем в кубышке)
		guiTable.add(edtEggsCapsules, "eggs_capsules");
		edtEggsLive = (EditText) findViewById(R.id.edtEggsLive); // яйца(% жизнеспособных)
		guiTable.add(edtEggsLive, "eggs_live");
		//edtEggsLive.setFilters(new InputFilter[]{ new InputFilterMinMax("0", "100")});

		spiEggsEnemies = findViewById(R.id.spiEggsEnemies); // наличие естественных врагов(каких?)
		guiTable.add(spiEggsEnemies, "eggs_enemies_id");
		((selectDB)spiEggsEnemies).addField("", "");
		// Выбираем отрождение и заполняем поля
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select b.id, COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = b.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),b.name) name from list_enemies b where b.del=0 order by b.sort", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiEggsEnemies).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		// Личинки
		spiLarvaBorn = findViewById(R.id.spiLarvaBorn); // Отрождение
		guiTable.add(spiLarvaBorn, "larva_born_id");
		((selectDB)spiLarvaBorn).addField("", "");
		// Выбираем отрождение и заполняем поля
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select b.id, COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = b.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),b.name) name from Borns b where b.del=0 order by b.sort", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiLarvaBorn).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		spiLarvaAge = findViewById(R.id.spiLarvaAge);
		guiTable.add(spiLarvaAge, "larva_age_id");
		((selectDB)spiLarvaAge).addField("", "");
		// Выбираем отрождение и заполняем поля
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select a.id, COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = a.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),a.name) name from list_age a where a.del=0 order by a.sort", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiLarvaAge).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		spiLarvaPainting = findViewById(R.id.spiLarvaPainting);
		guiTable.add(spiLarvaPainting, "larva_painting_id");
		((selectDB)spiLarvaPainting).addField("", "");
		// Выбираем отрождение и заполняем поля
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select a.id, COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = a.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),a.name) name from list_paintings a where a.del=0 order by a.sort", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiLarvaPainting).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		//Поведение личинок
		spiLarvaBehavior = findViewById(R.id.spiLarvaBehavior);
		guiTable.add(spiLarvaBehavior, "larva_behavior_id");
		((selectDB)spiLarvaBehavior).addField("", "");
		// Выбираем отрождение и заполняем поля
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select a.id, COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = a.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),a.name) name from list_behaviors a where a.del=0 order by a.sort", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiLarvaBehavior).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		edtLarvaDensity = (EditText) findViewById(R.id.edtLarvaDensity); // Плотность
		guiTable.add(edtLarvaDensity, "larva_density");
		edtLarvaDensityTo = (EditText) findViewById(R.id.edtLarvaDensityTo); // Плотность
		guiTable.add(edtLarvaDensityTo, "larva_density_to");

		// Кулигули
		edtKuliguliDensity = (EditText) findViewById(R.id.edtKuliguliDensity); // Кулигули плотность
		guiTable.add(edtKuliguliDensity, "kuliguli_density");
		edtKuliguliDensityTo = (EditText) findViewById(R.id.edtKuliguliDensityTo); // Кулигули плотность
		guiTable.add(edtKuliguliDensityTo, "kuliguli_density_to");

		edtKuliguliSize = (EditText) findViewById(R.id.edtKuliguliSize); // Размер
		guiTable.add(edtKuliguliSize, "kuliguli_size");
		edtKuliguliCount = (EditText) findViewById(R.id.edtKuliguliCount);
		guiTable.add(edtKuliguliCount, "kuliguli_count");

		spiKuliguliAction = findViewById(R.id.spiKuliguliAction);
		guiTable.add(spiKuliguliAction, "kuliguli_action_id");
		((selectDB)spiKuliguliAction).addField("", "");
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select a.id,COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = a.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),a.name) name from list_actions a where a.del=0 order by a.sort", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiKuliguliAction).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		spiKuliguliAge = findViewById(R.id.spiKuliguliAge);
		guiTable.add(spiKuliguliAge, "kuliguli_age_id");
		((selectDB)spiKuliguliAge).addField("", "");
		// Выбираем отрождение и заполняем поля
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select a.id, COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = a.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),a.name) name from list_age a where a.del=0 order by a.sort", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiKuliguliAge).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		// Имаго
		spiImagoWing = findViewById(R.id.spiImagoWing); // окрыления начало массовое
		guiTable.add(spiImagoWing, "imago_wing_id");
		((selectDB)spiImagoWing).addField("", "");
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select f.id,COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = f.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),f.name) name from Fledgling f where f.del=0 order by f.sort", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiImagoWing).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		spiImagoMaturity = findViewById(R.id.spiImagoMaturity);
		guiTable.add(spiImagoMaturity, "imago_maturity");
		((selectDB)spiImagoMaturity).addField("", "");
		((selectDB)spiImagoMaturity).addField(getString(R.string.Yes), "1");
		((selectDB)spiImagoMaturity).addField(getString(R.string.No), "0");

		spiImagoPhase = findViewById(R.id.spiImagoPhase);
		guiTable.add(spiImagoPhase, "imago_phase_id");
		((selectDB)spiImagoPhase).addField("", "");
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select d.id, COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = d.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),d.name) name from list_phase d where d.del=0 order by d.sort,d.name", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiImagoPhase).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		//Поведение Имаго
		spiImagoAction = findViewById(R.id.spiImagoAction);
		guiTable.add(spiImagoAction, "imago_action_id");
		((selectDB)spiImagoAction).addField("", "");
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select f.id,COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = f.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),f.name) name from list_breeding f where f.del=0 order by f.sort", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiImagoAction).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		edtImagoDensity = (EditText) findViewById(R.id.edtImagoDensity);
		guiTable.add(edtImagoDensity, "imago_density");

		edtImagoDensityGa = (EditText) findViewById(R.id.edtImagoDensityGa);
		guiTable.add(edtImagoDensityGa, "imago_density_ga");

		//Для пересчёта значения при сохранении
		/*spiDensityType = findViewById(R.id.spiDensityType);
		guiTable.add(spiDensityType,"imago_density_type");
		spiDensityType.addField(this, getString(R.string.on_m), "1");
		spiDensityType.addField(this, getString(R.string.on_ha), "0");*/

		spiImagoFeeding = findViewById(R.id.spiImagoFeeding);
		guiTable.add(spiImagoFeeding, "imago_feeding");
		((selectDB)spiImagoFeeding).addField("", "");
		((selectDB)spiImagoFeeding).addField(getString(R.string.Yes), "1");
		((selectDB)spiImagoFeeding).addField(getString(R.string.No), "0");

		spiImagoCopulation = findViewById(R.id.spiImagoCopulation);
		guiTable.add(spiImagoCopulation, "imago_copulation");
		((selectDB)spiImagoCopulation).addField("", "");
		((selectDB)spiImagoCopulation).addField(getString(R.string.Yes), "1");
		((selectDB)spiImagoCopulation).addField(getString(R.string.No), "0");

		spiImagolaying = findViewById(R.id.spiImagolaying);
		guiTable.add(spiImagolaying, "imago_laying");
		((selectDB)spiImagolaying).addField("", "");
		((selectDB)spiImagolaying).addField(getString(R.string.Yes), "1");
		((selectDB)spiImagolaying).addField(getString(R.string.No), "0");

		spiImagoFlying = findViewById(R.id.spiImagoFlying);
		guiTable.add(spiImagoFlying, "imago_flying");
		((selectDB)spiImagoFlying).addField("", "");
		((selectDB)spiImagoFlying).addField(getString(R.string.Yes), "1");
		((selectDB)spiImagoFlying).addField(getString(R.string.No), "0");

		// Стаи
		spiSwarmMaturity = findViewById(R.id.spiSwarmMaturity);
		guiTable.add(spiSwarmMaturity, "swarm_maturity");
		((selectDB)spiSwarmMaturity).addField("", "");
		((selectDB)spiSwarmMaturity).addField(getString(R.string.Yes), "1");
		((selectDB)spiSwarmMaturity).addField(getString(R.string.No), "0");

		spiSwarmDensity = findViewById(R.id.spiSwarmDensity);
		guiTable.add(spiSwarmDensity, "swarm_density_id");
		((selectDB)spiSwarmDensity).addField("", "");
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select d.id, COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = d.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),d.name) name from list_density d where d.del=0 order by d.percent,d.name", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiSwarmDensity).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		edtSwarmSize = (EditText) findViewById(R.id.edtSwarmSize);
		guiTable.add(edtSwarmSize, "swarm_size");
		edtSwarmCount = (EditText) findViewById(R.id.edtSwarmCount);
		guiTable.add(edtSwarmCount, "swarm_count");

		// edtSwarmFlying = (EditText) findViewById(R.id.edtSwarmFlying);
		spiSwarmFlying = findViewById(R.id.spiSwarmFlying); // полёт(направление, время пролёта)
		guiTable.add(spiSwarmFlying, "swarm_flying_direction_id");
		((selectDB)spiSwarmFlying).addField("", "");
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select d.id, COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = d.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),d.name) name, d.degree from list_directions d where d.del=0 order by d.degree", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiSwarmFlying).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		spiSwarmHeight = findViewById(R.id.spiSwarmHeight);
		guiTable.add(spiSwarmHeight, "swarm_height_id");
		((selectDB)spiSwarmHeight).addField("", "");
		dboh = new DbOpenHelper(this);
		rdb = null;
		cursor = null;
		try {
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery("select d.id, COALESCE((SELECT translation FROM _translations t JOIN _languages l ON t.language_id=l.id WHERE t.del = 0 AND identifier = d.name AND l.short_name='" + Tools.getLang() + "' LIMIT 1),d.name) name from list_height d where d.del=0 order by d.sort,d.name", null);
			if (cursor.moveToFirst()) {
				do {
					((selectDB)spiSwarmHeight).addField(cursor.getString(cursor.getColumnIndex("name")), cursor.getString(cursor.getColumnIndex("id")));
				} while (cursor.moveToNext());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();

		// public CheckBox cbBoxDescription = null;
		/*cbBoxDescription = (CheckBox) findViewById(R.id.cbBoxDescription);
		OnClickListener oclCbBoxDescription = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (!cbBoxDescription.isChecked())
				{
					edtDescription.setText("");
				}
				updateAlpha();
			}
		};
		cbBoxDescription.setOnClickListener(oclCbBoxDescription);*/
		edtDescription = (EditText) findViewById(R.id.edtDescription);
		guiTable.add(edtDescription, "description");

		cbTest = (CheckBox) findViewById(R.id.cbTest);
		guiTable.add(cbTest, "test");

		// *** Кнопки ***
		btnGetGPSCenter = (View) findViewById(R.id.btnGetGPSCenter);
		OnClickListener oclBtnGetGPSCenter = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				DecimalFormatSymbols custom = new DecimalFormatSymbols(new Locale("en", "US"));
				custom.setDecimalSeparator('.');

				DecimalFormat df = new DecimalFormat("0.0000000");
				df.setDecimalFormatSymbols(custom);

				if(LocustActivity.this._lat!=0 && LocustActivity.this._lon!=0) {
					LocustActivity.this.edtLatCenter.setText(df.format(LocustActivity.this._lat));
					LocustActivity.this.edtLonCenter.setText(df.format(LocustActivity.this._lon));
				}
				//Checking if the GPS is active and if it is inactive, I display a warning about it
				LocationManager locationManager = (LocationManager) LocustActivity.this.getSystemService(Context.LOCATION_SERVICE);;
				if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
					Toast.makeText(LocustActivity.this, LocustActivity.this.getResources().getString(R.string.Please_activate_GPS), Toast.LENGTH_LONG).show();
				}
			}
		};
		btnGetGPSCenter.setOnClickListener(oclBtnGetGPSCenter);

		btnDelGPSCenter = (View) findViewById(R.id.btnDelGPSCenter);
		btnDelGPSCenter.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				LocustActivity.this.edtLatCenter.setText("");
				LocustActivity.this.edtLonCenter.setText("");
			}
		});

		btnOnMap = (View) findViewById(R.id.btnOnMap);
		OnClickListener oclBtnOnMap = new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(LocustActivity.this, MapsActivity.class);
				//intent.putExtra("LatLon", ((LatLonAdapter)latlonList.getAdapter()).latlonList);
				LatLonAdapter adapter = (LatLonAdapter)latlonList.getAdapter();
				ArrayList<LatLon> list = adapter.latlonList;
				intent.putParcelableArrayListExtra("LatLon", list);
				intent.putExtra("uid", uid);
				startActivityForResult(intent,4); ////startActivity(intent);
			}
		};
		btnOnMap.setOnClickListener(oclBtnOnMap);

		// android:id="@+id/btnOk"
		btnOk = (Button) findViewById(R.id.btnOk);
		OnClickListener oclBtnOk = new OnClickListener() {
			@Override
			public void onClick(View v) {
				saveData();
			}
		};
		btnOk.setOnClickListener(oclBtnOk);

		btnCancel = (View) findViewById(R.id.btnCancel);
		OnClickListener oclBtnCancel = new OnClickListener() {
			@Override
			public void onClick(View v) {
				AlertDialog.Builder adb = new AlertDialog.Builder(LocustActivity.this, R.style.AlertDialogTheme);
				adb.setTitle(getString(R.string.Warning));
				adb.setMessage(LocustActivity.this.getResources().getString(R.string.Cancel_filling_form));
				adb.setPositiveButton(LocustActivity.this.getResources().getString(R.string.Yes), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int id) {
						LocustActivity.this.finish();
					}
				});
				adb.setNegativeButton(LocustActivity.this.getResources().getString(R.string.No), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

					}
				});
				AlertDialog ad = adb.show();
				ad.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
				ad.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
			}
		};
		btnCancel.setOnClickListener(oclBtnCancel);


		btnImage1 = (View) findViewById(R.id.btnImage1);
		OnClickListener oclBtnImage = new OnClickListener() {
			@Override
			public void onClick(View v) {
				//Создаём папку если её нет
				File directory = new File(Environment.getExternalStorageDirectory() + File.separator + "Pictures" + File.separator + "Locust");
				directory.mkdirs();

				tmp_ImageName = "locust_" + (System.currentTimeMillis() / 1000L) + ".jpg";

				File file = new File(Environment.getExternalStorageDirectory() + File.separator + "Pictures" + File.separator + "Locust" + File.separator + tmp_ImageName);

				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
					mImageUri = FileProvider.getUriForFile(LocustActivity.this, BuildConfig.APPLICATION_ID + ".provider", file);
				else
					mImageUri = Uri.fromFile(file);

				Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
				startActivityForResult(intent, 1);
			}
		};
		btnImage1.setOnClickListener(oclBtnImage);

		btnImage2 = (View) findViewById(R.id.btnImage2);
		oclBtnImage = new OnClickListener() {
			@Override
			public void onClick(View v) {
				//Создаём папку если её нет
				File directory = new File(Environment.getExternalStorageDirectory() + File.separator + "Pictures" + File.separator + "Locust");
				directory.mkdirs();

				tmp_ImageName = "locust_" + (System.currentTimeMillis() / 1000L) + ".jpg";

				File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/" + tmp_ImageName);

				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
					mImageUri = FileProvider.getUriForFile(LocustActivity.this, BuildConfig.APPLICATION_ID + ".provider", file);
				else
					mImageUri = Uri.fromFile(file);

				Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
				startActivityForResult(intent, 2);
			}
		};
		btnImage2.setOnClickListener(oclBtnImage);


		btnImage3 = (View) findViewById(R.id.btnImage3);
		oclBtnImage = new OnClickListener() {
			@Override
			public void onClick(View v) {
				//Создаём папку если её нет
				File directory = new File(Environment.getExternalStorageDirectory() + File.separator + "Pictures" + File.separator + "Locust");
				directory.mkdirs();

				tmp_ImageName = "locust_" + (System.currentTimeMillis() / 1000L) + ".jpg";

				File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/" + tmp_ImageName);

				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
					mImageUri = FileProvider.getUriForFile(LocustActivity.this, BuildConfig.APPLICATION_ID + ".provider", file);
				else
					mImageUri = Uri.fromFile(file);

				Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
				startActivityForResult(intent, 3);
			}
		};
		btnImage3.setOnClickListener(oclBtnImage);


		btnShowImage1 = (View) findViewById(R.id.btnShowImage1); // Отобразить фотографию 1 в новом окне
		OnClickListener oclBtnShowImage = new OnClickListener() {
			@Override
			public void onClick(View v) {
				File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/" + edtImage1.getText().toString());
				if (!file.isFile())
					file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/_" + edtImage1.getText().toString());

				if (file.isFile()) {
					Intent i = new Intent();
					i.setAction(android.content.Intent.ACTION_VIEW);

					//Uri uri = Uri.fromFile(file);
					Uri uri = FileProvider.getUriForFile(LocustActivity.this, BuildConfig.APPLICATION_ID + ".provider", file);

					i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
					i.setDataAndType(uri, "image/jpg");
					startActivity(i);
				}
			}
		};
		btnShowImage1.setOnClickListener(oclBtnShowImage);

		btnShowImage2 = (View) findViewById(R.id.btnShowImage2); // Отобразить фотографию 1 в новом окне
		oclBtnShowImage = new OnClickListener() {
			@Override
			public void onClick(View v) {
				File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/" + edtImage2.getText().toString());
				if (!file.isFile())
					file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/_" + edtImage2.getText().toString());
				if (file.isFile()) {
					Intent i = new Intent();
					i.setAction(android.content.Intent.ACTION_VIEW);

					//Uri uri = Uri.fromFile(file)
					Uri uri = FileProvider.getUriForFile(LocustActivity.this, BuildConfig.APPLICATION_ID + ".provider", file);

					i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
					i.setDataAndType(uri, "image/jpg");
					startActivity(i);
				}
			}
		};
		btnShowImage2.setOnClickListener(oclBtnShowImage);

		btnShowImage3 = (View) findViewById(R.id.btnShowImage3); // Отобразить фотографию 3 в новом окне
		oclBtnShowImage = new OnClickListener() {
			@Override
			public void onClick(View v) {
				File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/" + edtImage3.getText().toString());
				if (!file.isFile())
					file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/_" + edtImage3.getText().toString());
				if (file.isFile()) {
					Intent i = new Intent();
					i.setAction(android.content.Intent.ACTION_VIEW);

					//Uri uri = Uri.fromFile(file)
					Uri uri = FileProvider.getUriForFile(LocustActivity.this, BuildConfig.APPLICATION_ID + ".provider", file);

					i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
					i.setDataAndType(uri, "image/jpg");
					startActivity(i);
				}
			}
		};
		btnShowImage3.setOnClickListener(oclBtnShowImage);

		btnDelImage1 = (View) findViewById(R.id.btnDelImage1);
		btnDelImage1.setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						edtImage1.setText("");
					}
				}
		);

		btnDelImage2 = (View) findViewById(R.id.btnDelImage2);
		btnDelImage2.setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						edtImage2.setText("");
					}
				}
		);

		btnDelImage3 = (View) findViewById(R.id.btnDelImage3);
		btnDelImage3.setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						edtImage3.setText("");
					}
				}
		);


		// public CheckBox cbBoxDescription = null;
		/*cbBoxDescription = (CheckBox) findViewById(R.id.cbBoxDescription);*/
		OnClickListener oclCB = new OnClickListener() {
			@Override
			public void onClick(View v) {
				CheckBox cbx = (CheckBox) v;
				if (!cbx.isChecked()) {
					AlertDialog.Builder adb = new AlertDialog.Builder(LocustActivity.this, R.style.AlertDialogTheme);
					adb.setTitle(getString(R.string.Warning));
					adb.setMessage(LocustActivity.this.getResources().getString(R.string.Cancel_filling_section));
					adb.setPositiveButton(LocustActivity.this.getResources().getString(R.string.Yes), new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int id) {
							updateAlpha();
						}
					});
					adb.setNegativeButton(LocustActivity.this.getResources().getString(R.string.No), new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
							cbx.setChecked(true);
						}
					});
					AlertDialog ad = adb.show();
					ad.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
					ad.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
				} else {
					updateAlpha();
				}
			}
		};

		cbEggs = (CheckBox) findViewById(R.id.cbEggs);
		guiTable.add(cbEggs, "eggs");
		cbEggs.setOnClickListener(oclCB);

		cbHoppers = (CheckBox) findViewById(R.id.cbHoppers);
		guiTable.add(cbHoppers, "hoppers");
		cbHoppers.setOnClickListener(oclCB);

		cbBands = (CheckBox) findViewById(R.id.cbBands);
		guiTable.add(cbBands, "bands");
		cbBands.setOnClickListener(oclCB);

		cbAdults = (CheckBox) findViewById(R.id.cbAdults);
		guiTable.add(cbAdults, "adults");
		cbAdults.setOnClickListener(oclCB);

		cbSwarms = (CheckBox) findViewById(R.id.cbSwarms);
		guiTable.add(cbSwarms, "swarms");
		cbSwarms.setOnClickListener(oclCB);


		editData(uid);
		adapter.notifyDataSetChanged();
		Tools.setListViewHeightBasedOnItems(latlonList);


		((selectDB)spiLocustHave).setOnChangeValueListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						hideInterfaceByID(((selectDB)spiLocustHave).getValue());
					}
				});

		// Чтоб слушать GPS (в конце метода чтобы успели присвоиться  GUI компоненты локальным переменным)
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
			return;
		}
		lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, this);
	}

	@Override
	public void onResume(){
		super.onResume();
		if(spiCountry.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiCountry).updateAdapter(this);
		if(spiRegion.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiRegion).updateAdapter(this);
		if(spiBioBiotope.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiBioBiotope).updateAdapter(this);

		if(spiBioGreenery.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiBioGreenery).updateAdapter(this);
		if(spiBioGreeneryCover.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiBioGreeneryCover).updateAdapter(this);
		if(spiLocustHave.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiLocustHave).updateAdapter(this);
		if(spiLocustType.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiLocustType).updateAdapter(this);
		if(spiEggsEnemies.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiEggsEnemies).updateAdapter(this);
		if(spiLarvaBorn.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiLarvaBorn).updateAdapter(this);
		if(spiLarvaAge.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiLarvaAge).updateAdapter(this);
		if(spiLarvaPainting.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiLarvaPainting).updateAdapter(this);
		if(spiLarvaBehavior.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiLarvaBehavior).updateAdapter(this);
		if(spiKuliguliAction.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiKuliguliAction).updateAdapter(this);
		if(spiKuliguliAge.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiKuliguliAge).updateAdapter(this);
		if(spiImagoWing.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiImagoWing).updateAdapter(this);
		if(spiImagoMaturity.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiImagoMaturity).updateAdapter(this);
		if(spiImagoPhase.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiImagoPhase).updateAdapter(this);
		if(spiImagoAction.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiImagoAction).updateAdapter(this);
		if(spiImagoFeeding.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiImagoFeeding).updateAdapter(this);
		if(spiImagoCopulation.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiImagoCopulation).updateAdapter(this);
		if(spiImagolaying.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiImagolaying).updateAdapter(this);
		if(spiImagoFlying.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiImagoFlying).updateAdapter(this);
		if(spiSwarmMaturity.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiSwarmMaturity).updateAdapter(this);
		if(spiSwarmDensity.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiSwarmDensity).updateAdapter(this);
		if(spiSwarmFlying.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiSwarmFlying).updateAdapter(this);
		if(spiSwarmHeight.getClass().toString().indexOf("dbfields.AutoCompleteTextViewDB")!=-1) ((AutoCompleteTextViewDB)spiSwarmHeight).updateAdapter(this);

		//Moved here from onCreate because it did not save checkboxes in drop-down lists when rotating the screen
		updateAlpha();
	}

	public void hideInterfaceByID(String id)
	{
		if(id.equals("0")) //Отсутствует (скрываем всё)
		{
			//LinearLayout llEggs = (LinearLayout) findViewById(R.id.llEggs);
			//llEggs.setVisibility(View.GONE);
			//LinearLayout llHoppers = (LinearLayout) findViewById(R.id.llHoppers);
			//llHoppers.setVisibility(View.GONE);
			//LinearLayout llBands = (LinearLayout) findViewById(R.id.llBands);
			//llBands.setVisibility(View.GONE);
			//LinearLayout llAdults = (LinearLayout) findViewById(R.id.llAdults);
			//llAdults.setVisibility(View.GONE);
			//LinearLayout llSwarms = (LinearLayout) findViewById(R.id.llSwarms);
			//llSwarms.setVisibility(View.GONE);
		}else if(id.equals("2")) //EGG-PODS
		{
			CheckBox cbEggs = (CheckBox) findViewById(R.id.cbEggs);
			cbEggs.setChecked(true);

			//LinearLayout llEggs = (LinearLayout) findViewById(R.id.llEggs);
			//llEggs.setVisibility(View.VISIBLE);
			//LinearLayout llHoppers = (LinearLayout) findViewById(R.id.llHoppers);
			//llHoppers.setVisibility(View.GONE);
			//LinearLayout llBands = (LinearLayout) findViewById(R.id.llBands);
			//llBands.setVisibility(View.GONE);
			//LinearLayout llAdults = (LinearLayout) findViewById(R.id.llAdults);
			//llAdults.setVisibility(View.GONE);
			//LinearLayout llSwarms = (LinearLayout) findViewById(R.id.llSwarms);
			//llSwarms.setVisibility(View.GONE);
		}else if(id.equals("3")) //Личинки разряженные
		{
			CheckBox cbHoppers = (CheckBox) findViewById(R.id.cbHoppers);
			cbHoppers.setChecked(true);

			//LinearLayout llEggs = (LinearLayout) findViewById(R.id.llEggs);
			//llEggs.setVisibility(View.GONE);
			//LinearLayout llHoppers = (LinearLayout) findViewById(R.id.llHoppers);
			//llHoppers.setVisibility(View.VISIBLE);
			//LinearLayout llBands = (LinearLayout) findViewById(R.id.llBands);
			//llBands.setVisibility(View.GONE);
			//LinearLayout llAdults = (LinearLayout) findViewById(R.id.llAdults);
			//llAdults.setVisibility(View.GONE);
			//LinearLayout llSwarms = (LinearLayout) findViewById(R.id.llSwarms);
			//llSwarms.setVisibility(View.GONE);
		}else if(id.equals("4")) //Кулиги
		{
			CheckBox cbBands = (CheckBox) findViewById(R.id.cbBands);
			cbBands.setChecked(true);

			//LinearLayout llEggs = (LinearLayout) findViewById(R.id.llEggs);
			//llEggs.setVisibility(View.GONE);
			//LinearLayout llHoppers = (LinearLayout) findViewById(R.id.llHoppers);
			//llHoppers.setVisibility(View.GONE);
			//LinearLayout llBands = (LinearLayout) findViewById(R.id.llBands);
			//llBands.setVisibility(View.VISIBLE);
			//LinearLayout llAdults = (LinearLayout) findViewById(R.id.llAdults);
			//llAdults.setVisibility(View.GONE);
			//LinearLayout llSwarms = (LinearLayout) findViewById(R.id.llSwarms);
			//llSwarms.setVisibility(View.GONE);
		}else if(id.equals("5")) //Имаго
		{
			CheckBox cbAdults = (CheckBox) findViewById(R.id.cbAdults);
			cbAdults.setChecked(true);

			//LinearLayout llEggs = (LinearLayout) findViewById(R.id.llEggs);
			//llEggs.setVisibility(View.GONE);
			//LinearLayout llHoppers = (LinearLayout) findViewById(R.id.llHoppers);
			//llHoppers.setVisibility(View.GONE);
			//LinearLayout llBands = (LinearLayout) findViewById(R.id.llBands);
			//llBands.setVisibility(View.GONE);
			//LinearLayout llAdults = (LinearLayout) findViewById(R.id.llAdults);
			//llAdults.setVisibility(View.VISIBLE);
			//LinearLayout llSwarms = (LinearLayout) findViewById(R.id.llSwarms);
			//llSwarms.setVisibility(View.GONE);
		}else if(id.equals("6")) //Стаи
		{
			CheckBox cbSwarms = (CheckBox) findViewById(R.id.cbSwarms);
			cbSwarms.setChecked(true);

			//LinearLayout llEggs = (LinearLayout) findViewById(R.id.llEggs);
			//llEggs.setVisibility(View.GONE);
			//LinearLayout llHoppers = (LinearLayout) findViewById(R.id.llHoppers);
			//llHoppers.setVisibility(View.GONE);
			//LinearLayout llBands = (LinearLayout) findViewById(R.id.llBands);
			//llBands.setVisibility(View.GONE);
			//LinearLayout llAdults = (LinearLayout) findViewById(R.id.llAdults);
			//llAdults.setVisibility(View.GONE);
			//LinearLayout llSwarms = (LinearLayout) findViewById(R.id.llSwarms);
			//llSwarms.setVisibility(View.VISIBLE);
		}
        updateAlpha();
	}

	// Сохраняются настройки перед уничтожением формы
	@Override
	protected void onSaveInstanceState(Bundle outState)
	{
		super.onSaveInstanceState(outState);
		if (mImageUri != null)
		{
			outState.putString("cameraImageUri", mImageUri.toString());
		}
		// Сохраняем название рисунка (Не знаю почему но автоматом не сохраняет)
		outState.putString("ImageName", edtImage1.getText().toString());
		//Сохраняю список координат LatLon
		LatLonAdapter adapter = (LatLonAdapter)latlonList.getAdapter();
		ArrayList<LatLon> list = adapter.latlonList;
		for(int i=0;i<list.size();i++){
			outState.putParcelableArrayList("LatLon", list);
		}
	}

	// Востанавливаются настройки после созания формы
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState)
	{
		super.onRestoreInstanceState(savedInstanceState);
		if (savedInstanceState.containsKey("cameraImageUri"))
		{
			mImageUri = Uri.parse(savedInstanceState.getString("cameraImageUri"));
			File f = new File("" + mImageUri);
			tmp_ImageName = f.getName();
		}
		edtImage1.setText(savedInstanceState.getString("ImageName")); // Восстанавливаем название рисунка
		//Загружаю список координат LatLon
		LatLonAdapter adapter = (LatLonAdapter)latlonList.getAdapter();
		adapter.latlonList=savedInstanceState.getParcelableArrayList("LatLon");
		adapter.notifyDataSetChanged();
		Tools.setListViewHeightBasedOnItems(latlonList);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.locust, menu);
		return true;
	}

	// Событие нажатия выпадающего меню правый вершний угол
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.action_settings: // Форма настроек

				Intent intent = new Intent(this, SetupActivity.class);
				startActivity(intent);

				break;
			default:
				return false;
		}
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (requestCode == 1 || requestCode == 2 || requestCode == 3)
		{
			switch (resultCode)
			{
				case 0:
					Log.e("Locust", "onActivityResult resultCode == 0");
					break;
				case -1:
					ImageName = tmp_ImageName;
					InputStream file = null;
					try
					{
						//Изменяю разрешение фотографии на 1024 x 768 пикселей
						Bitmap bm = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/" + tmp_ImageName);
						if(Math.max(bm.getWidth(),bm.getHeight())!=1920)
							bm = Tools.getResizeBMP(bm, 1920); //Изменяем размер фото
						FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/" + tmp_ImageName);
						bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
						out.flush();
						out.close();

						//Вычисляю CRC32 файла
						file = new BufferedInputStream(new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/" + tmp_ImageName));
						CRC32 crc = new CRC32();
						crc.reset();
						int cnt;

						while ((cnt = file.read()) != -1)
						{
							crc.update(cnt);
						}
						// ImageName = Long.toHexString(crc.getValue()) + "_" + ImageName;
						ImageName = Long.toHexString(crc.getValue()) + "_" + tmp_ImageName;
						file.close();

						// Переименовываем файл
						File renamed = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/" + tmp_ImageName);
						renamed.renameTo(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/" + ImageName));

						if (requestCode == 1) edtImage1.setText(ImageName);
						if (requestCode == 2) edtImage2.setText(ImageName);
						if (requestCode == 3) edtImage3.setText(ImageName);

					} catch (IOException e)
					{
						Log.e("CCALM", "Error: ", e);
						//e.printStackTrace();
					}
					// Для сохранения названия рисунка в базу
					break;
			}
		}
		if (requestCode == 4)
		{
			switch (resultCode)
			{
				case 0:
					Log.e("Locust", "onActivityResult resultCode == 0");
					break;
				case -1:
					ArrayList<LatLon> points = data.getParcelableArrayListExtra("LatLon");
					LatLonAdapter adapter = (LatLonAdapter)latlonList.getAdapter();
					ArrayList<LatLon> list = adapter.latlonList;
					list.clear();
					for(int i=0;i<points.size();i++){
						if(points.get(i)!=null && points.get(i).lon!=0 && points.get(i).lat!=0) {
							list.add(new LatLon(points.get(i).uid,points.get(i).lat, points.get(i).lon));
						}
					}
					list.add(new LatLon(UUID.randomUUID().toString(),0, 0));
					adapter.notifyDataSetChanged();
					Tools.setListViewHeightBasedOnItems(latlonList);
					break;
			}
		}
	}

	/*
	 * protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { switch (resultCode) { case 0: break;
	 * 	case -1: ImageName = tmp_ImageName;
	 * 	InputStream file = null; try { file = new BufferedInputStream(new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/" + tmp_ImageName)); CRC32 crc = new CRC32(); crc.reset(); int cnt;
	 * 	while ((cnt = file.read()) != -1) { crc.update(cnt); } ImageName = Long.toHexString(crc.getValue()) + "_" + tmp_ImageName; file.close();
	 * 	// Переименовываем файл File renamed = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/" + tmp_ImageName); renamed.renameTo(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Locust/" + ImageName));
	 * 	edtImage.setText(ImageName);
	 * } catch (IOException e) { e.printStackTrace(); } // Для сохранения названия рисунка в базу
	 * break; } } }
	 */

	/*
	 * Задать доступность свойств по поставленным галочкам
	 */
	public void updateAlpha()
	{
		//Яйца
		if (!cbEggs.isChecked())
		{
			edtEggsCapsulesArea.setText("");
			edtEggsCapsulesDensity.setText("");
			edtEggsCapsulesDensityTo.setText("");
			edtEggsCapsules.setText("");
			edtEggsLive.setText("");
			//spiEggsEnemies.setSelection(0);
			((selectDB)spiEggsEnemies).setValue("");
		}
		//Личинки
		if (!cbHoppers.isChecked())
		{
			((selectDB)spiLarvaBorn).setValue("");
			((selectDB)spiLarvaAge).setValue("");
			((selectDB)spiLarvaPainting).setValue("");
			((selectDB)spiLarvaBehavior).setValue("");
			edtLarvaDensity.setText("");
			edtLarvaDensityTo.setText("");
		}
		//Кулиги
		if (!cbBands.isChecked())
		{
			edtKuliguliDensity.setText("");
			edtKuliguliDensityTo.setText("");
			edtKuliguliSize.setText("");
			edtKuliguliCount.setText("");
			((selectDB)spiKuliguliAction).setValue("");
			((selectDB)spiKuliguliAge).setValue("");
		}
		//Имаго
		if (!cbAdults.isChecked())
		{
			((selectDB)spiImagoWing).setValue("");
			((selectDB)spiImagoMaturity).setValue("");
			((selectDB)spiImagoPhase).setValue("");
			((selectDB)spiImagoAction).setValue("");
			edtImagoDensity.setText("");
			edtImagoDensityGa.setText("");
			((selectDB)spiImagoCopulation).setValue("");
			((selectDB)spiImagolaying).setValue("");
			((selectDB)spiImagoFlying).setValue("");
		}
		//Стаи
		if (!cbSwarms.isChecked())
		{
			((selectDB)spiSwarmMaturity).setValue("");
			((selectDB)spiSwarmDensity).setValue("");
			edtSwarmSize.setText("");
			edtSwarmCount.setText("");
			//spiSwarmCopulation.setValue("");
			//spiSwarmLaying.setValue("");
			((selectDB)spiSwarmFlying).setValue("");
			((selectDB)spiSwarmHeight).setValue("");
		}

		boolean f;
		//float a;
		int c;
		if (cbEggs.isChecked())
		{
			//a = 1f;
			f = true;
			c = 0xff000000;

			LinearLayout llEggs = (LinearLayout) findViewById(R.id.llEggs);
			llEggs.setVisibility(View.VISIBLE);
		} else
		{
			//a = 0.5f;
			f = false;
			c = 0xff888888;

			LinearLayout llEggs = (LinearLayout) findViewById(R.id.llEggs);
			llEggs.setVisibility(View.GONE);
		}

		//((TextView) findViewById(R.id.tvEggsCapsulesArea)).setTextColor(c);
		edtEggsCapsulesArea.setTextColor(c);
		edtEggsCapsulesArea.setFocusable(f);
		edtEggsCapsulesArea.setFocusableInTouchMode(f);
		edtEggsCapsulesArea.setClickable(f);
		//((TextView) findViewById(R.id.tvEggsCapsulesDensity)).setTextColor(c);
		edtEggsCapsulesDensity.setTextColor(c); // кубышки(плотность на м2)
		edtEggsCapsulesDensity.setFocusable(f);
		edtEggsCapsulesDensity.setFocusableInTouchMode(f);
		edtEggsCapsulesDensity.setClickable(f);
		//((TextView) findViewById(R.id.tvEggsCapsulesDensityTo)).setTextColor(c);
		edtEggsCapsulesDensityTo.setTextColor(c); // кубышки(плотность на м2)
		edtEggsCapsulesDensityTo.setFocusable(f);
		edtEggsCapsulesDensityTo.setFocusableInTouchMode(f);
		edtEggsCapsulesDensityTo.setClickable(f);
		//((TextView) findViewById(R.id.tvEggsCapsules)).setTextColor(c);
		edtEggsCapsules.setTextColor(c); // яйца(в среднем в кубышке)
		edtEggsCapsules.setFocusable(f);
		edtEggsCapsules.setFocusableInTouchMode(f);
		edtEggsCapsules.setClickable(f);
		//((TextView) findViewById(R.id.tvEggsLive)).setTextColor(c);
		edtEggsLive.setTextColor(c); // яйца(% жизнеспособных)
		edtEggsLive.setFocusable(f);
		edtEggsLive.setFocusableInTouchMode(f);
		edtEggsLive.setClickable(f);
		//((TextView) findViewById(R.id.tvEggsEnemies)).setTextColor(c);
		//spiEggsEnemies.setTextColor(c); // наличие естественных врагов(каких?)
		spiEggsEnemies.setFocusable(f);
		//spiEggsEnemies.setFocusableInTouchMode(f);
		spiEggsEnemies.setClickable(f);

		if (cbHoppers.isChecked())
		{
			//a = 1f;
			f = true;
			c = 0xff000000;

			LinearLayout llHoppers = (LinearLayout) findViewById(R.id.llHoppers);
			llHoppers.setVisibility(View.VISIBLE);
		} else
		{
			//a = 0.5f;
			f = false;
			c = 0xff888888;

			LinearLayout llHoppers = (LinearLayout) findViewById(R.id.llHoppers);
			llHoppers.setVisibility(View.GONE);
		}

		//((TextView) findViewById(R.id.tvLarvaBorn)).setTextColor(c);
		// spiLarvaBorn.setTextColor(c); // Отрождение
		//spiLarvaBorn.setFocusable(f);
		//spiLarvaBorn.setFocusableInTouchMode(f);
		spiLarvaBorn.setClickable(f);
		//((TextView) findViewById(R.id.tvLarvaAge)).setTextColor(c);
		// spiLarvaAge.setTextColor(c);
		spiLarvaAge.setFocusable(f);
		// spiLarvaAge.setFocusableInTouchMode(f);
		spiLarvaAge.setClickable(f);
		//((TextView) findViewById(R.id.tvLarvaPainting)).setTextColor(c);
		// spiLarvaPainting.setTextColor(c);
		spiLarvaPainting.setFocusable(f);
		// spiLarvaPainting.setFocusableInTouchMode(f);
		spiLarvaPainting.setClickable(f);
		//((TextView) findViewById(R.id.tvLarvaBehavior)).setTextColor(c);
		// spiLarvaBehavior.setTextColor(c);
		spiLarvaBehavior.setFocusable(f);
		// spiLarvaBehavior.setFocusableInTouchMode(f);
		spiLarvaBehavior.setClickable(f);
		//((TextView) findViewById(R.id.tvLarvaDensity)).setTextColor(c);
		edtLarvaDensity.setTextColor(c);
		edtLarvaDensity.setFocusable(f);
		edtLarvaDensity.setFocusableInTouchMode(f);
		edtLarvaDensity.setClickable(f);
		//((TextView) findViewById(R.id.tvLarvaDensityTo)).setTextColor(c);
		edtLarvaDensityTo.setTextColor(c);
		edtLarvaDensityTo.setFocusable(f);
		edtLarvaDensityTo.setFocusableInTouchMode(f);
		edtLarvaDensityTo.setClickable(f);

		if (cbBands.isChecked())
		{
			f = true;
			c = 0xff000000;

			LinearLayout llBands = (LinearLayout) findViewById(R.id.llBands);
			llBands.setVisibility(View.VISIBLE);
		} else
		{
			f = false;
			c = 0xff888888;

			LinearLayout llBands = (LinearLayout) findViewById(R.id.llBands);
			llBands.setVisibility(View.GONE);
		}

		//((TextView) findViewById(R.id.tvKuliguliAge)).setTextColor(c);
		//spiKuliguliAge.setTextColor(c);
		spiKuliguliAge.setFocusable(f);
		//spiKuliguliAge.setFocusableInTouchMode(f);
		spiKuliguliAge.setClickable(f);

		//((TextView) findViewById(R.id.tvKuliguliDensity)).setTextColor(c);
		edtKuliguliDensity.setTextColor(c);
		edtKuliguliDensity.setFocusable(f);
		edtKuliguliDensity.setFocusableInTouchMode(f);
		edtKuliguliDensity.setClickable(f);

		//((TextView) findViewById(R.id.tvKuliguliDensityTo)).setTextColor(c);
		edtKuliguliDensityTo.setTextColor(c);
		edtKuliguliDensityTo.setFocusable(f);
		edtKuliguliDensityTo.setFocusableInTouchMode(f);
		edtKuliguliDensityTo.setClickable(f);

		//((TextView) findViewById(R.id.tvKuliguliSize)).setTextColor(c);
		edtKuliguliSize.setTextColor(c);
		edtKuliguliSize.setFocusable(f);
		edtKuliguliSize.setFocusableInTouchMode(f);
		edtKuliguliSize.setClickable(f);

		//((TextView) findViewById(R.id.tvKuliguliCount)).setTextColor(c);
		edtKuliguliCount.setTextColor(c);
		edtKuliguliCount.setFocusable(f);
		edtKuliguliCount.setFocusableInTouchMode(f);
		edtKuliguliCount.setClickable(f);

		//((TextView) findViewById(R.id.tvKuliguliAction)).setTextColor(c);
		// spiKuliguliAction.setTextColor(c);
		spiKuliguliAction.setFocusable(f);
		// spiKuliguliAction.setFocusableInTouchMode(f);
		spiKuliguliAction.setClickable(f);

		if (cbAdults.isChecked())
		{
			f = true;
			c = 0xff000000;

			LinearLayout llAdults = (LinearLayout) findViewById(R.id.llAdults);
			llAdults.setVisibility(View.VISIBLE);
		} else
		{
			f = false;
			c = 0xff888888;

			LinearLayout llAdults = (LinearLayout) findViewById(R.id.llAdults);
			llAdults.setVisibility(View.GONE);
		}
		//((TextView) findViewById(R.id.tvImagoWing)).setTextColor(c);
		// spiImagoWing.setTextColor(c);
		//spiImagoWing.setFocusable(f);
		//spiImagoWing.setFocusableInTouchMode(f);
		spiImagoWing.setClickable(f);
		//((TextView) findViewById(R.id.tvImagoMaturity)).setTextColor(c);
		// spiImagoMaturity.setTextColor(c);
		spiImagoMaturity.setFocusable(f);
		// spiImagoMaturity.setFocusableInTouchMode(f);
		spiImagoMaturity.setClickable(f);
		//((TextView) findViewById(R.id.tvImagoPhase)).setTextColor(c);
		// spiImagoPhase.setTextColor(c);
		spiImagoPhase.setFocusable(f);
		// spiImagoPhase.setFocusableInTouchMode(f);
		spiImagoPhase.setClickable(f);
		//((TextView) findViewById(R.id.tvImagoAction)).setTextColor(c);
		// spiImagoAction.setTextColor(c);
		spiImagoAction.setFocusable(f);
		// spiImagoAction.setFocusableInTouchMode(f);
		spiImagoAction.setClickable(f);

		//((TextView) findViewById(R.id.tvImagoDensity)).setTextColor(c);
		edtImagoDensity.setTextColor(c);
		edtImagoDensity.setFocusable(f);
		edtImagoDensity.setFocusableInTouchMode(f);
		edtImagoDensity.setClickable(f);

		//((TextView) findViewById(R.id.tvImagoDensityGa)).setTextColor(c);
		edtImagoDensityGa.setTextColor(c);
		edtImagoDensityGa.setFocusable(f);
		edtImagoDensityGa.setFocusableInTouchMode(f);
		edtImagoDensityGa.setClickable(f);
		
		//((TextView) findViewById(R.id.tvImagoFeeding)).setTextColor(c);
		spiImagoFeeding.setFocusable(f);
		spiImagoFeeding.setClickable(f);
		//((TextView) findViewById(R.id.tvImagoCopulation)).setTextColor(c);
		spiImagoCopulation.setFocusable(f);
		spiImagoCopulation.setClickable(f);
		//((TextView) findViewById(R.id.tvImagolaying)).setTextColor(c);
		spiImagolaying.setFocusable(f);
		spiImagolaying.setClickable(f);
		//((TextView) findViewById(R.id.tvImagoFlying)).setTextColor(c);
		spiImagoFlying.setFocusable(f);
		spiImagoFlying.setClickable(f);

		if (cbSwarms.isChecked())
		{
			f = true;
			c = 0xff000000;

			LinearLayout llSwarms = (LinearLayout) findViewById(R.id.llSwarms);
			llSwarms.setVisibility(View.VISIBLE);
		} else
		{
			f = false;
			c = 0xff888888;

			LinearLayout llSwarms = (LinearLayout) findViewById(R.id.llSwarms);
			llSwarms.setVisibility(View.GONE);
		}
		//((TextView) findViewById(R.id.tvSwarmMaturity)).setTextColor(c);
		//spiSwarmMaturity.setTextColor(c);
		spiSwarmMaturity.setFocusable(f);
		//spiSwarmMaturity.setFocusableInTouchMode(f);
		spiSwarmMaturity.setClickable(f);
		//((TextView) findViewById(R.id.tvSwarmDensity)).setTextColor(c);
		//spiSwarmDensity.setTextColor(c);
		//spiSwarmDensity.setFocusable(f);
		//spiSwarmDensity.setFocusableInTouchMode(f);
		spiSwarmDensity.setClickable(f);

		//((TextView) findViewById(R.id.tvSwarmSize)).setTextColor(c);
		edtSwarmSize.setTextColor(c);
		edtSwarmSize.setFocusable(f);
		edtSwarmSize.setFocusableInTouchMode(f);
		edtSwarmSize.setClickable(f);
		//((TextView) findViewById(R.id.tvSwarmCount)).setTextColor(c);
		edtSwarmCount.setTextColor(c);
		edtSwarmCount.setFocusable(f);
		edtSwarmCount.setFocusableInTouchMode(f);
		edtSwarmCount.setClickable(f);
		//((TextView) findViewById(R.id.tvSwarmCopulation)).setTextColor(c);
		// spiSwarmCopulation.setTextColor(c);
		//spiSwarmCopulation.setFocusable(f);
		// spiSwarmCopulation.setFocusableInTouchMode(f);
		//spiSwarmCopulation.setClickable(f);

		//((TextView) findViewById(R.id.tvSwarmLaying)).setTextColor(c);
		// spiSwarmLaying.setTextColor(c);
		//spiSwarmLaying.setFocusable(f);
		// spiSwarmLaying.setFocusableInTouchMode(f);
		//spiSwarmLaying.setClickable(f);

		//((TextView) findViewById(R.id.tvSwarmFlying)).setTextColor(c);
		// spiSwarmFlying.setTextColor(c);
		spiSwarmFlying.setFocusable(f);
		// spiSwarmFlying.setFocusableInTouchMode(f);
		spiSwarmFlying.setClickable(f);
		//((TextView) findViewById(R.id.tvSwarmHeight)).setTextColor(c);
		// spiSwarmHeight.setTextColor(c);
		spiSwarmHeight.setFocusable(f);
		// spiSwarmHeight.setFocusableInTouchMode(f);
		spiSwarmHeight.setClickable(f);

		/*if (cbBoxDescription.isChecked())
		{
			f = true;
			c = 0xff000000;
		} else
		{
			f = false;
			c = 0xff888888;
		}
		((TextView) findViewById(R.id.tvDescription)).setTextColor(c);
		edtDescription.setTextColor(c);
		edtDescription.setFocusable(f);
		edtDescription.setFocusableInTouchMode(f);
		edtDescription.setClickable(f);
		edtDescription.setEnabled(f);*/
	}

	public void updateAlphaByData()
	{
		/*
		 * boolean ch;
		 * ch=false; ch=ch || !edtEggsCapsulesArea.getText().toString().equals(""); ch=ch || !edtEggsCapsulesDensity.getText().toString().equals(""); ch=ch || !edtEggsCapsules.getText().toString().equals(""); ch=ch || !edtEggsLive.getText().toString().equals(""); ch=ch || !edtEggsEnemies.getText().toString().equals("");
		 * cbBoxEggs.setChecked(ch);
		 * ch=false; ch=ch || !edtLarvaBorn.getText().toString().equals(""); ch=ch || !(spiLarvaAge.getSelectedItemPosition()==0); ch=ch || !(spiLarvaPainting.getSelectedItemPosition()==0); ch=ch || !(spiLarvaBehavior.getSelectedItemPosition()==0); ch=ch || !edtLarvaDensity.getText().toString().equals("");
		 * cbBoxHoppers.setChecked(ch);
		 * ch=false; ch=ch || !(spiKuliguliAge.getSelectedItemPosition()==0);; ch=ch || !edtKuliguliDensity.getText().toString().equals(""); ch=ch || !edtKuliguliSize.getText().toString().equals(""); ch=ch || !edtKuliguliCount.getText().toString().equals(""); ch=ch || !(spiKuliguliAction.getSelectedItemPosition()==0);;
		 * cbBoxBands.setChecked(ch);
		 * ch=false; ch=ch || !spiImagoWing.getText().toString().equals(""); ch=ch || !(spiImagoMaturity.getSelectedItemPosition()==0);; ch=ch || !(spiImagoPhase.getSelectedItemPosition()==0);; ch=ch || !(spiImagoAction.getSelectedItemPosition()==0);; ch=ch || !edtImagoDensity.getText().toString().equals(""); ch=ch || !(spiImagoCopulation.getSelectedItemPosition()==0); ch=ch || !(spiImagoFlying.getSelectedItemPosition()==0);;
		 * cbBoxAdults.setChecked(ch);
		 * ch=false; ch=ch || !(spiSwarmMaturity.getSelectedItemPosition()==0);; ch=ch || !edtSwarmDensity.getText().toString().equals(""); ch=ch || !edtSwarmSize.getText().toString().equals(""); ch=ch || !edtSwarmCount.getText().toString().equals(""); ch=ch || !(spiSwarmCopulation.getSelectedItemPosition()==0); ch=ch || !(spiSwarmFlying.getSelectedItemPosition()==0); ch=ch || !(spiSwarmHeight.getSelectedItemPosition()==0);;
		 * cbBoxSwarms.setChecked(ch);
		 * ch=false; ch=ch || !edtDescription.getText().toString().equals("");
		 * cbBoxDescription.setChecked(ch);
		 */
		updateAlpha();
	}

	/*
	 * public Bitmap setupImage(Intent data) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 2;//SAMPLE_SIZE; // SAMPLE_SIZE = 2
	 * 
	 * Bitmap tempBitmap = null; Bitmap bm = null; try { tempBitmap = (Bitmap) data.getExtras().get("data"); bm = tempBitmap;
	 * 
	 * Log.v("ManageImage-hero", "the data.getData seems to be valid");
	 * 
	 * FileOutputStream out = new FileOutputStream(outputFileUri.getPath()); tempBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
	 * 
	 * } catch (NullPointerException ex) { Log.v("ManageImage-other", "another phone type"); bm = otherImageProcessing(options); } catch(Exception e) { Log.e("ManageImage-setupImage", "problem setting up the image", e); }
	 * 
	 * return bm; }
	 */

	/*
	 * private File createImageFile() throws IOException { String JPEG_FILE_PREFIX = "Locust"; String JPEG_FILE_SUFFIX = "L";
	 * 
	 * // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
	 * 
	 * File image = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, getAlbumDir()); String mCurrentPhotoPath = image.getAbsolutePath(); return image; }
	 */

	/**
	 * Редактирование данных по uid Если null то создание иначе редактирование
	 */
	public void editData(String uid)
	{
		if(uid==null || uid.equals(""))
		{
			((fieldDB)LocustActivity.this.edtDate).setValue(String.valueOf((new Date()).getTime()/1000));
            edtTimeZone.setText(Tools.getTimezone());
		}
		guiTable.read(uid);
		//Читаю список координат из базы данных
		if (uid != null)
		{
			LatLonAdapter adapter = (LatLonAdapter)latlonList.getAdapter();
			ArrayList<LatLon> list = adapter.latlonList;
			list.clear();
			DbOpenHelper dboh = new DbOpenHelper(this);
			SQLiteDatabase rdb = null;
			Cursor cursor = null;
			try {
				rdb = dboh.getReadableDatabase();
				cursor = rdb.rawQuery("select uid,lat,lon from frmlocust_locations where del=0 and frmlocust_uid='" + uid + "' order by pos", null);
				if (cursor.moveToFirst())
				{
					do
					{
						list.add(new LatLon(cursor.getString(0), cursor.getDouble(1), cursor.getDouble(2)));
					} while (cursor.moveToNext());
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				if(cursor != null) { cursor.close(); }
				if(rdb!=null){ rdb.close(); }
			}
			dboh.close();
			list.add(new LatLon(UUID.randomUUID().toString(),0, 0));
		}
	}

	/***
	 * Переместить и сфокусировать на переданном элементе
	 */
	public void scrollTo(View item)
	{
		int top = 0;
		View tmp = item;
		while (tmp != null)
		{
			if (tmp == scrollView1)
			{
				scrollView1.scrollTo(0, top);
				item.requestFocus();
				break;
			}

			top += tmp.getTop();
			tmp = (View) tmp.getParent();
		}
	}

	public void alert(String text)
	{
		AlertDialog.Builder adb = new AlertDialog.Builder(this,R.style.AlertDialogTheme);
		adb.setTitle(getString(R.string.Warning));
		adb.setMessage(text);
		adb.setPositiveButton("OK", new DialogInterface.OnClickListener() //Кнопка открыть
		{
			@Override
			public void onClick(DialogInterface arg0, int arg1)
			{}
		});
		AlertDialog ad = adb.show();
		ad.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
	}

	public boolean isGONE(View view)
	{
		if (!view.isClickable())
			return true;
		try {
			while (view != null) {
				if (view.getVisibility() == View.GONE)
					return true;

				view = (View) view.getParent();
				if(view==getWindow().getDecorView().getRootView())
					break;
			}
		}catch (Exception e)
		{}
		return false;
	}

	/**
	 * Сохранить в базу данных (если есть то перезаписать в качестве идентификатора дата создания)
	 */
	public void saveData()
	{
		// Проверка на заполненость полей
		String atxt = getString(R.string.Not_filled); //Текст для алерта: "Не заполнено поле".
		boolean eFields = false; //У анкеты 2 состояния 1) Заполнены все обяз поля 2) Не заполнены все обяз поля

		//Проверка на заполнение обязательных полей для выделения цветом
		if(isGONE(spiCountry)) ((selectDB)spiCountry).setValue(null);
		//if(!eFields && !isGONE(spiCountry) && spiCountry.getSelectedItem().toString().isBlank())
		if(!eFields && !isGONE(spiCountry) && ((selectDB)spiCountry).getText().toString().isBlank())
		{
			scrollTo(spiCountry);
			atxt = atxt + ": \"" + getResources().getString(R.string.Country) + "\"!";
			eFields = true;
		}
		if(isGONE(spiRegion)) ((selectDB)spiRegion).setValue(null);
		//if(!eFields && !isGONE(spiRegion) && spiRegion.getSelectedItem().toString().isBlank())
		if(!eFields && !isGONE(spiRegion) && ((selectDB)spiRegion).getText().toString().isBlank())
		{
			scrollTo(spiRegion);
			atxt = atxt + ": \"" + getResources().getString(R.string.Region) + "\"!";
			eFields = true;
		}
		if(isGONE(edtArea)) edtArea.setText(null);
		if(!eFields && !isGONE(edtArea) && edtArea.getText().toString().isBlank())
		{
			scrollTo(edtArea);
			atxt = atxt + ": \"" + getResources().getString(R.string.Area) + "\"!";
			eFields = true;
		}
/*		if(isGONE(edtVillage)) edtVillage.setValue(null);
		if (!eFields && edtVillage.isClickable() && edtVillage.getText().toString().isBlank())
		{
			scrollTo(edtVillage);
			atxt = atxt + ": \"" + getResources().getString(R.string.Village) + "\"!";
			eFields = true;
		}*/
/*		if(isGONE(edtDistrict)) edtDistrict.setValue(null);
		if(!eFields && edtDistrict.isClickable() && edtDistrict.getText().toString().isBlank())
		{
			scrollTo(edtDistrict);
			atxt = atxt + ": \"" + getResources().getString(R.string.District) + "\"!";
			eFields = true;
		}*/
		if(isGONE(edtObserver)) edtObserver.setText(null);
		if(!eFields && !isGONE(edtObserver) && edtObserver.getText().toString().isBlank())
		{
			scrollTo(edtObserver);
			atxt = atxt + ": \"" + getResources().getString(R.string.Name_of_survey_team_leader) + "\"!";
			eFields = true;
		}
		if(isGONE(edtDate)) {
			((fieldDB) LocustActivity.this.edtDate).setValue(null);
		}

		if(!eFields && !isGONE(edtDate) && edtDate.getText().toString().isBlank())
		{
			scrollTo(edtDate);
			atxt = atxt + ": \"" + getResources().getString(R.string.Date) + "\"!";
			eFields = true;
		}
		//TODO Не забыть раскоментировать при публикации новой версии
		if(isGONE(edtLatCenter)) edtLatCenter.setText(null);
		if(!eFields && (!isGONE(edtLatCenter) && edtLatCenter.getText().toString().isBlank() || Tools.getDouble(edtLatCenter.getText().toString(),0.0) == 0))
		{
			scrollTo(edtLatCenter);
			atxt = atxt + ": \"" + getResources().getString(R.string.Lat) + "\"!";
			eFields = true;
		}
		if(isGONE(edtLonCenter)) edtLonCenter.setText(null);
		if(!eFields && (!isGONE(edtLonCenter) && edtLonCenter.getText().toString().isBlank() || Tools.getDouble(edtLonCenter.getText().toString(),0.0) == 0))
		{
			scrollTo(edtLonCenter);
			atxt = atxt + ": \"" + getResources().getString(R.string.Lon) + "\"!";
			eFields = true;
		}

		if(isGONE(edtBioHectare)) edtBioHectare.setText(null);
		if(!eFields && !isGONE(edtBioHectare))
		{
			float  vErr1=0;
			float  vErr2=0;
			try{
				vErr1= Float.parseFloat(edtBioHectare.getText().toString());
				vErr2= Float.parseFloat(edtLocustPopulated.getText().toString());
			} catch (NumberFormatException nfe) { }

			if(edtBioHectare.getText().toString().isBlank())
			{
				scrollTo(edtBioHectare);
				atxt = atxt + ": \"" + getResources().getString(R.string.Surveyed_area_ha) + "\"!";
				eFields = true;
			}else
			if(!checkMinMaxI(edtBioHectare,0,1000).isEmpty())
			{
				scrollTo(edtBioHectare);
				atxt = checkMinMaxI(edtBioHectare,0,1000) + " \"" + getResources().getString(R.string.Surveyed_area_ha) + "\"!";
				eFields = true;
			}else
			if(vErr2 > vErr1) //Обследованной площади не может быть меньше заселённой
			{
				scrollTo(edtBioHectare);
				atxt = getResources().getString(R.string.Area_infested_ha) + " > " + getResources().getString(R.string.Surveyed_area_ha);
				eFields = true;
			}
		}
		if(isGONE(spiBioBiotope)) ((selectDB)spiBioBiotope).setValue(null);
		//if(!eFields && !isGONE(spiBioBiotope) && spiBioBiotope.getSelectedItem().toString().isBlank())
		if(!eFields && !isGONE(spiBioBiotope) && ((selectDB)spiBioBiotope).getText().toString().isBlank())
		{
			scrollTo(spiBioBiotope);
			atxt = atxt + ": \"" + getResources().getString(R.string.Type_of_biotope) + "\"!";
			eFields = true;
		}
		if(isGONE(spiBioGreenery)) ((selectDB)spiBioGreenery).setValue(null);
		//if(!eFields && !isGONE(spiBioGreenery) && spiBioGreenery.getSelectedItem().toString().isBlank())
		if(!eFields && !isGONE(spiBioGreenery) && ((selectDB)spiBioGreenery).getText().toString().isBlank())
		{
			scrollTo(spiBioGreenery);
			atxt = atxt + ": \"" + getResources().getString(R.string.Vegetation) + "\"!";
			eFields = true;
		}
		if(isGONE(spiBioGreeneryCover)) ((selectDB)spiBioGreeneryCover).setValue(null);
		//if(!eFields && !isGONE(spiBioGreeneryCover) && spiBioGreeneryCover.getSelectedItem().toString().isBlank()) //Обратно раскоментил было не обязательным
		if(!eFields && !isGONE(spiBioGreeneryCover) && ((selectDB)spiBioGreeneryCover).getText().toString().isBlank()) //Обратно раскоментил было не обязательным
		{
			scrollTo(spiBioGreeneryCover);
			atxt = atxt + ": \"" + getResources().getString(R.string.Vegetation_cover) + "\"!";
			eFields = true;
		}
		if(isGONE(edtBioTemperature)) edtBioTemperature.setText(null);
		if(!eFields && !isGONE(edtBioTemperature))
		{
			if(!checkMinMaxI(edtBioTemperature,0,50).isEmpty())
			{
				scrollTo(edtBioTemperature);
				atxt = checkMinMaxI(edtBioTemperature,0,50) + " \"" + getResources().getString(R.string.Air_temperature) + "\"!";
				eFields = true;
			}
		}
		if(isGONE(edtBioWind)) edtBioWind.setText(null);
		if(!eFields && !isGONE(edtBioWind))
		{
			if(!checkMinMaxI(edtBioWind,0,20).isEmpty()) //Проверка на интервалы
			{
				scrollTo(edtBioWind);
				atxt = checkMinMaxI(edtBioWind,0,20) + " \"" + getResources().getString(R.string.Wind_m_s) + "\"!";
				eFields = true;
			}
		}
		if(isGONE(spiLocustHave)) ((selectDB)spiLocustHave).setValue(null);
		if(!eFields && !isGONE(spiLocustHave) && ((selectDB)spiLocustHave).getText().toString().isBlank())
		{
			scrollTo(spiLocustHave);
			atxt = atxt + ": \"" + getResources().getString(R.string.Are_locusts_present) + "\"!";
			eFields = true;
		}
		if(isGONE(spiLocustType)) ((selectDB)spiLocustType).setValue(null);
		if(!eFields && !isGONE(spiLocustType) && ((selectDB)spiLocustType).getText().toString().isBlank())
		{
			scrollTo(spiLocustType);
			atxt = atxt + ": \"" + getResources().getString(R.string.Locust_species) + "\"!";
			eFields = true;
		}
		if(isGONE(edtLocustPopulated)) edtLocustPopulated.setText(null);
		if(!eFields && !isGONE(edtLocustPopulated))
		{
			if(edtLocustPopulated.getText().toString().isBlank())
			{
				scrollTo(edtLocustPopulated);
				atxt = atxt + ": \"" + getResources().getString(R.string.Area_infested_ha) + "\"!";
				eFields = true;
			}else
			if(!checkMinMaxI(edtLocustPopulated,0,1000).isEmpty())
			{
				scrollTo(edtLocustPopulated);
				atxt = checkMinMaxI(edtLocustPopulated,0,1000) + " \"" + getResources().getString(R.string.Area_infested_ha) + "\"!";
				eFields = true;
			}
		}
		//**************************************************
		// залежь кубышек (площадь в м2)
		if(isGONE(edtEggsCapsulesArea)) edtEggsCapsulesArea.setText(null);
		if(!eFields && !isGONE(edtEggsCapsulesArea))
		{
			/*if(edtEggsCapsulesArea.getText().toString().isBlank())
			{
				scrollTo(edtEggsCapsulesArea);
				atxt = atxt + ": \"" + getResources().getString(R.string.Egg_bed_surface_in_ha) + "\"!";
				eFields = true;
			}else*/
			if(!checkMinMaxI(edtEggsCapsulesArea,0,10000).isEmpty())
			{
				scrollTo(edtEggsCapsulesArea);
				atxt = checkMinMaxI(edtEggsCapsulesArea,0,10000) + " \"" + getResources().getString(R.string.Egg_bed_surface_in_ha) + "\"!";
				eFields = true;
			}
		}
		// кубышки(плотность на м2) от
		if(isGONE(edtEggsCapsulesDensity)) edtEggsCapsulesDensity.setText(null);
		if(!eFields && !isGONE(edtEggsCapsulesDensity))
		{
			if(edtEggsCapsulesDensity.getText().toString().isBlank())
			{
				scrollTo(edtEggsCapsulesDensity);
				atxt = atxt + ": \"" + getResources().getString(R.string.Egg_pods_density_m2) + "\"!";
				eFields = true;
			}else
			if(!checkMinMaxI(edtEggsCapsulesDensity,0,1000).isEmpty())
			{
				scrollTo(edtEggsCapsulesDensity);
				atxt = checkMinMaxI(edtEggsCapsulesDensity,0,1000) + " \"" + getResources().getString(R.string.Egg_pods_density_m2) + "\"!";
				eFields = true;
			}				
		}
		// кубышки(плотность на м2) до
		if(isGONE(edtEggsCapsulesDensityTo)) edtEggsCapsulesDensityTo.setText(null);
		if(!eFields && !isGONE(edtEggsCapsulesDensityTo) && edtEggsCapsulesDensityTo.getText().toString().isBlank())
		{
			if(edtEggsCapsulesDensityTo.getText().toString().isBlank())
			{
				scrollTo(edtEggsCapsulesDensityTo);
				atxt = atxt + ": \"" + getResources().getString(R.string.Egg_pods_density_m2) + " "+ getResources().getString(R.string.to) + "\"!";
				eFields = true;
			}else
			if(!checkMinMaxI(edtEggsCapsulesDensityTo,0,5000).isEmpty())
			{
				scrollTo(edtEggsCapsulesDensityTo);
				atxt = checkMinMaxI(edtEggsCapsulesDensityTo,0,5000) + " \"" + getResources().getString(R.string.Egg_pods_density_m2) + " "+ getResources().getString(R.string.to) + "\"!";
				eFields = true;
			}
		}
		// яйца(в среднем в кубышке)
		if(isGONE(edtEggsCapsules)) edtEggsCapsules.setText(null);
		if(!eFields && !isGONE(edtEggsCapsules))
		{
			if(!checkMinMaxI(edtEggsCapsules,0,150).isEmpty())
			{
				scrollTo(edtEggsCapsules);
				atxt = checkMinMaxI(edtEggsCapsules,0,150) + " \"" + getResources().getString(R.string.Eggs_average_number_egg_pod) + "\"!";
				eFields = true;
			}
		}
		// яйца(% жизнеспособных)
		if(isGONE(edtEggsLive)) edtEggsLive.setText(null);
		if(!eFields && !isGONE(edtEggsLive))
		{
			if(edtEggsLive.getText().toString().isBlank())
			{
				scrollTo(edtEggsLive);
				atxt = atxt + ": \"" + getResources().getString(R.string.Eggs_viable) + "\"!";
				eFields = true;
			}else
			if(!checkMinMaxI(edtEggsLive,0,100).isEmpty())
			{
				scrollTo(edtEggsLive);
				atxt = checkMinMaxI(edtEggsLive,0,100) + " \"" + getResources().getString(R.string.Eggs_viable) + "\"!";
				eFields = true;
			}				
		}
		// Естественные враги
		if(isGONE(spiEggsEnemies)) ((selectDB)spiEggsEnemies).setValue(null);
		if(!eFields && !isGONE(spiEggsEnemies) && ((selectDB)spiEggsEnemies).getText().toString().isBlank())
		{
			scrollTo(spiEggsEnemies);
			atxt = atxt + ": \"" + getResources().getString(R.string.Natural_enemies) + "\"!";
			eFields = true;
		}
		// отрождение
		if(isGONE(spiLarvaBorn)) ((selectDB)spiLarvaBorn).setValue(null);
		if(!eFields && !isGONE(spiLarvaBorn) && ((selectDB)spiLarvaBorn).getText().toString().isBlank())
		{
			scrollTo(spiLarvaBorn);
			atxt = atxt + ": \"" + getResources().getString(R.string.Hatching) + "\"!";
			eFields = true;
		}
		// возраста: Младшие Средние Старшие
		if(isGONE(spiLarvaAge)) ((selectDB)spiLarvaAge).setValue(null);
		if(!eFields && !isGONE(spiLarvaAge) && ((selectDB)spiLarvaAge).getText().toString().isBlank())
		{
			scrollTo(spiLarvaAge);
			atxt = atxt + ": \"" + getResources().getString(R.string.Hopper_stages) + "\"!";
			eFields = true;
		}
		//Фаза окраска(одиночнаяS, перехoдная Т, стаднаяG)
		//if(isGONE(spiLarvaAge)) spiLarvaAge.setValue(null); земем это было здесь?

		// поведение(�?золир., Разреженные, Группы)
		if(isGONE(spiLarvaBehavior)) ((selectDB)spiLarvaBehavior).setValue(null);
		if(!eFields && !isGONE(spiLarvaBehavior) && ((selectDB)spiLarvaBehavior).getText().toString().isBlank())
		{
			scrollTo(spiLarvaBehavior);
			atxt = atxt + ": \"" + getResources().getString(R.string.Spatial_distribution) + "\"!";
			eFields = true;
		}
		// плотность на м2
		if(isGONE(edtLarvaDensity)) edtLarvaDensity.setText(null);
		if(!eFields && !isGONE(edtLarvaDensity))
		{
			if(edtLarvaDensity.getText().toString().isBlank())
			{
				scrollTo(edtLarvaDensity);
				atxt = atxt + ": \"" + getResources().getString(R.string.Hopper_density_m2) + "\"!";
				eFields = true;
			}else
			if(!checkMinMaxI(edtLarvaDensity,0,80000).isEmpty())
			{
				scrollTo(edtLarvaDensity);
				atxt = checkMinMaxI(edtLarvaDensity,0,80000) + " \"" + getResources().getString(R.string.Hopper_density_m2) + "\"!";
				eFields = true;
			}
		}
		// Плотность на м2
		if(isGONE(edtLarvaDensityTo)) edtLarvaDensityTo.setText(null);
		if(!eFields && !isGONE(edtLarvaDensityTo) && edtLarvaDensityTo.getText().toString().isBlank())
		{
			scrollTo(edtLarvaDensityTo);
			atxt = atxt + ": \"" + getResources().getString(R.string.Hopper_density_m2) + "" + getResources().getString(R.string.to) + "\"!";
			eFields = true;
		}
		//**************************************************
		// плотн. в кулиге(на м2)
		if(isGONE(edtKuliguliDensity)) edtKuliguliDensity.setText(null);
		if(!eFields && !isGONE(edtKuliguliDensity))
		{
			if(edtKuliguliDensity.getText().toString().isBlank())
			{
				scrollTo(edtKuliguliDensity);
				atxt = atxt + ": \"" + getResources().getString(R.string.Minimum_density_in_the_band_in_m2) + "\"!";
				eFields = true;
			}else
			if(!checkMinMaxI(edtKuliguliDensity,0,80000).isEmpty())
			{
				scrollTo(edtKuliguliDensity);
				atxt = checkMinMaxI(edtKuliguliDensity,0,80000) + " \"" + getResources().getString(R.string.Minimum_density_in_the_band_in_m2) + "\"!";
				eFields = true;
			}
		}
		// плотн. в кулиге(на м2) до
		if(isGONE(edtKuliguliDensityTo)) edtKuliguliDensityTo.setText(null);
		if(!eFields && !isGONE(edtKuliguliDensityTo))
		{
			if(edtKuliguliDensityTo.getText().toString().isBlank())
			{
				scrollTo(edtKuliguliDensityTo);
				atxt = atxt + ": \"" + getResources().getString(R.string.Minimum_density_in_the_band_in_m2) + " " + getResources().getString(R.string.to) + "\"!";
				eFields = true;
			}else
			if(!checkMinMaxI(edtKuliguliDensityTo,0,80000).isEmpty())
			{
				scrollTo(edtKuliguliDensityTo);
				atxt = checkMinMaxI(edtKuliguliDensityTo,0,80000) + " \"" + getResources().getString(R.string.Minimum_density_in_the_band_in_m2) + " " + getResources().getString(R.string.to) + "\"!";
				eFields = true;
			}
		}
		// размер кулиг(га)
		if(isGONE(edtKuliguliSize)) edtKuliguliSize.setText(null);
		if(!eFields && !isGONE(edtKuliguliSize))
		{
			if(edtKuliguliSize.getText().toString().isBlank())
			{
				scrollTo(edtKuliguliSize);
				atxt = atxt + ": \"" + getResources().getString(R.string.Band_sizes_m2) + "\"!";
				eFields = true;
			}else
			if(!checkMinMaxI(edtKuliguliSize,0,10000).isEmpty())
			{
				scrollTo(edtKuliguliSize);
				atxt = checkMinMaxI(edtKuliguliSize,0,10000) + " \"" + getResources().getString(R.string.Band_sizes_m2) + "\"!";
				eFields = true;
			}
		}
		// число кулиг
		if(isGONE(edtKuliguliCount)) edtKuliguliCount.setText(null);
		if(!eFields && !isGONE(edtKuliguliCount))
		{
			/*if(edtKuliguliCount.getText().toString().isBlank())
			{
				scrollTo(edtKuliguliCount);
				atxt = atxt + ": \"" + getResources().getString(R.string.Number_of_bands_ha) + "\"!";
				eFields = true;
			}else*/
			if(!checkMinMaxI(edtKuliguliCount,1,50).isEmpty())
			{
				scrollTo(edtKuliguliCount);
				atxt = checkMinMaxI(edtKuliguliCount,1,50) + " \"" + getResources().getString(R.string.Number_of_bands) + "\"!";
				eFields = true;
			}
		}
		// поведение: миграция, кормёжка, отдых
		if(isGONE(spiKuliguliAction)) ((selectDB)spiKuliguliAction).setValue(null);
		if(!eFields && !isGONE(spiKuliguliAction) && ((selectDB)spiKuliguliAction).getText().toString().isBlank())
		{
			scrollTo(spiKuliguliAction);
			atxt = atxt + ": \"" + getResources().getString(R.string.Action) + "\"!";
			eFields = true;
		}
		// возраста: Младшие Средние Старшие
		if(isGONE(spiKuliguliAge)) ((selectDB)spiKuliguliAge).setValue(null);
		if(!eFields && !isGONE(spiKuliguliAge) && ((selectDB)spiKuliguliAge).getText().toString().isBlank())
		{
			scrollTo(spiKuliguliAge);
			atxt = atxt + ": \"" + getResources().getString(R.string.Hopper_stages) + "\"!";
			eFields = true;
		}
		//**************************************************
		// окрыление(начало, массовое)
		if(isGONE(spiImagoWing)) ((selectDB)spiImagoWing).setValue(null);
		if(!eFields && !isGONE(spiImagoWing) && ((selectDB)spiImagoWing).getText().toString().isBlank())
		{
			scrollTo(spiImagoWing);
			atxt = atxt + ": \"" + getResources().getString(R.string.Fledging) + "\"!";
			eFields = true;
		}
		// половозрелость(- или+)
		if(isGONE(spiImagoMaturity)) ((selectDB)spiImagoMaturity).setValue(null);
		if(!eFields && !isGONE(spiImagoMaturity) && ((selectDB)spiImagoMaturity).getText().toString().isBlank())
		{
			scrollTo(spiImagoMaturity);
			atxt = atxt + ": \"" + getResources().getString(R.string.Maturity) + "\"!";
			eFields = true;
		}
		// фаза(одиночнаяS, перехoдная Т, стаднаяG)
		if(isGONE(spiImagoPhase)) ((selectDB)spiImagoPhase).setValue(null);
		if(!eFields && !isGONE(spiImagoPhase) && ((selectDB)spiImagoPhase).getText().toString().isBlank())
		{
			scrollTo(spiImagoPhase);
			atxt = atxt + ": \"" + getResources().getString(R.string.Phase) + "\"!";
			eFields = true;
		}
		// поведение(�?золир., Разреженные, Группы)
		if(isGONE(spiImagoAction)) ((selectDB)spiImagoAction).setValue(null);
		if(!eFields && !isGONE(spiImagoAction) && ((selectDB)spiImagoAction).getText().toString().isBlank())
		{
			scrollTo(spiImagoAction);
			atxt = atxt + ": \"" + getResources().getString(R.string.Spatial_distribution) + "\"!";
			eFields = true;
		}
		// плотность(на трансекту или га)
		if(isGONE(edtImagoDensity)) edtImagoDensity.setText(null);
		if(!eFields && !isGONE(edtImagoDensity))
		{
			if(edtImagoDensity.getText().toString().isBlank())
			{
				scrollTo(edtImagoDensity);
				atxt = atxt + ": \"" + getResources().getString(R.string.Adult_density_m2) + "\"!";
				eFields = true;
			}else
			if(!checkMinMaxI(edtImagoDensity,0,3000).isEmpty())
			{
				scrollTo(edtImagoDensity);
				atxt = checkMinMaxI(edtImagoDensity,0,3000) + " \"" + getResources().getString(R.string.Adult_density_m2) + "\"!";
				eFields = true;
			}
		}
		// плотность на га
		if(isGONE(edtImagoDensityGa)) edtImagoDensityGa.setText(null);
		if(!eFields && !isGONE(edtImagoDensityGa))
		{
			if(!checkMinMaxI(edtImagoDensityGa,0,50000).isEmpty())
			{
				scrollTo(edtImagoDensityGa);
				atxt = checkMinMaxI(edtImagoDensityGa,0,50000) + " \"" + getResources().getString(R.string.Adult_density_ha) + "\"!";
				eFields = true;
			}
		}
		//Питание и размещение на растениях
		if(isGONE(spiImagoFeeding)) ((selectDB)spiImagoFeeding).setValue(null);
		if(!eFields && !isGONE(spiImagoFeeding) && ((selectDB)spiImagoFeeding).getText().toString().isBlank())
		{
			scrollTo(spiImagoFeeding);
			atxt = atxt + ": \"" + getResources().getString(R.string.Feeding_and_roosting) + "\"!";
			eFields = true;
		}
		// спаривание (да,нет)
		if(isGONE(spiImagoCopulation)) ((selectDB)spiImagoCopulation).setValue(null);
		if(!eFields && !isGONE(spiImagoCopulation) && ((selectDB)spiImagoCopulation).getText().toString().isBlank())
		{
			scrollTo(spiImagoCopulation);
			atxt = atxt + ": \"" + getResources().getString(R.string.Copulating) + "\"!";
			eFields = true;
		}
		// яйцекладка (да,нет)
		if(isGONE(spiImagolaying)) ((selectDB)spiImagolaying).setValue(null);
		if(!eFields && !isGONE(spiImagolaying) && ((selectDB)spiImagolaying).getText().toString().isBlank())
		{
			scrollTo(spiImagolaying);
			atxt = atxt + ": \"" + getResources().getString(R.string.Laying) + "\"!";
			eFields = true;
		}
		// полёты(- или+)
		if(isGONE(spiImagoFlying)) ((selectDB)spiImagoFlying).setValue("");
		if(!eFields && !isGONE(spiImagoFlying) && ((selectDB)spiImagoFlying).getText().toString().isBlank())
		{
			scrollTo(spiImagoFlying);
			atxt = atxt + ": \"" + getResources().getString(R.string.Flying) + "\"!";
			eFields = true;
		}
		//**************************************************
		//Половозрелость
		if (isGONE(spiSwarmMaturity)) ((selectDB)spiSwarmMaturity).setValue(null);
		if (!eFields && !isGONE(spiSwarmMaturity) && ((selectDB)spiSwarmMaturity).getText().toString().isBlank()) {
			scrollTo(spiSwarmMaturity);
			atxt = atxt + ": \"" + getResources().getString(R.string.Maturity) + "\"!";
			eFields = true;
		}
		//Плотность в стае
		if (isGONE(spiSwarmDensity)) ((selectDB)spiSwarmDensity).setValue(null);
		if (!eFields && !isGONE(spiSwarmDensity) && ((selectDB)spiSwarmDensity).getText().toString().isBlank()) {
			scrollTo(spiSwarmDensity);
			atxt = atxt + ": \"" + getResources().getString(R.string.Density_of_swarm) + "\"!";
			eFields = true;
		}
		//Размер стаи
		if (isGONE(edtSwarmSize)) edtSwarmSize.setText(null);
		if (!eFields && !isGONE(edtSwarmSize)) {
			if (!checkMinMaxI(edtSwarmSize, 0, 100000).isEmpty()) {
				scrollTo(edtSwarmSize);
				atxt = checkMinMaxI(edtSwarmSize, 0, 100000) + " \"" + getResources().getString(R.string.Swarm_size_ha) + "\"!";
				eFields = true;
			}
		}
		//Число стай
		if (isGONE(edtSwarmCount)) edtSwarmCount.setText(null);
		if (!eFields && !isGONE(edtSwarmCount)) {
			if (!checkMinMaxI(edtSwarmCount, 0, 10).isEmpty()) {
				scrollTo(edtSwarmCount);
				atxt = checkMinMaxI(edtSwarmCount, 0, 10) + " \"" + getResources().getString(R.string.Number_of_swarms) + "\"!";
				eFields = true;
			}
		}
		// полёт(направление, время пролёта)
		if (isGONE(spiSwarmFlying)) ((selectDB)spiSwarmFlying).setValue(null);
		// высота(Низкая- Средняя- Высокая)
		if (isGONE(spiSwarmHeight)) ((selectDB)spiSwarmHeight).setValue(null);

		
		if(eFields) //Если не заполнены все обязательные поля
		{
			m_Filled.setValue("0");
			
			AlertDialog.Builder adb = new AlertDialog.Builder(this,R.style.AlertDialogTheme);
			adb.setTitle(getString(R.string.Warning));
			
			adb.setMessage(atxt+"\n" + getString(R.string.not_filled_fields));
			adb.setPositiveButton(getString(R.string.Yes), new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface arg0, int arg1)
				{
					//Ничего не делаем
				}
			});
			adb.setNegativeButton(getString(R.string.No), new DialogInterface.OnClickListener()
			{
				@Override
				public void onClick(DialogInterface arg0, int arg1)
				{
					//Сохраняем и выходим
					String uid=guiTable.write(); //Добавляем либо сохраняем данные
					saveLocations(uid);

					LocustActivity.this.finish(); // Закрываем форму
				}
			});
			AlertDialog ad = adb.show();
			ad.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
			ad.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);

		}else //Если все обязательные поля заполнены
		{
			m_Filled.setValue("1");
			String uid=guiTable.write(); //Добавляем либо сохраняем данные
			saveLocations(uid);

			startService(new Intent(this, MainService.class).putExtra(MainService.PARAM_ACTION, "1")); // Чтоб вызвать событие таймера в сервисе
			LocustActivity.this.finish(); // Закрываем форму
		}
	}

	//Сохраняем список координат в базу
	public void saveLocations(String uid){
		if(uid==null) return;
		DbOpenHelper dboh = new DbOpenHelper(LocustActivity.this);
		SQLiteDatabase rdb = null;
		try {
			rdb = dboh.getReadableDatabase();
			rdb.execSQL("delete from frmlocust_locations where frmlocust_uid=\'" + uid+"\'");
			ArrayList<LatLon> list = ((LatLonAdapter)latlonList.getAdapter()).latlonList;
			for(int i=0;i<list.size();i++)
			{
				if(list.get(i)!=null && list.get(i).lon!=0 && list.get(i).lat!=0){
					SQLiteDatabase wdb = null;
					try {
						wdb = dboh.getWritableDatabase();
						SQLiteStatement stmt = wdb.compileStatement("insert into frmlocust_locations(uid,frmlocust_uid,pos,lat,lon)values(?,?,?,?,?)");
						stmt.bindString(1, UUID.randomUUID().toString());
						stmt.bindString(2, uid);
						stmt.bindLong(3, i);
						stmt.bindDouble(4, list.get(i).lat);
						stmt.bindDouble(5, list.get(i).lon);
						stmt.executeInsert();
					}catch(Exception e){
						e.printStackTrace();
					}finally{
						if(wdb!=null){ wdb.close(); }
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();
	}

	@Override
	public void onLocationChanged(Location location)
	{
		_lat = location.getLatitude(); // от устройства
		_lon = location.getLongitude(); // от устройства
		if(_lat!=0 && _lon!=0){
			if((((selectDB)spiCountry).getValue() == null || ((selectDB)spiCountry).getValue().equals("")) && (((selectDB)spiRegion).getValue()==null || ((selectDB)spiRegion).getValue().equals(""))){
				String prefName = "Identify";
				SharedPreferences prefs = getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
				String checked = prefs.getString(prefName, "");
				if(checked.equals("") || checked.equals("1")) {
					//Пытаюсь найти какому региону принадлежит точка
					DbOpenHelper dboh = new DbOpenHelper(this);
					Integer i1 = new Integer(0);
					int[] ids = dboh.inPerimeter((float) _lon, (float) _lat);
					if (ids[0] != 0 && ids[1] != 0) {
						((selectDB)spiCountry).setValue(String.valueOf(ids[0]));
						((selectDB)spiRegion).setValue(String.valueOf(ids[1]));
					}
					dboh.close();
				}
			}
		}
	}

	@Override
	public void onProviderDisabled(String provider)
	{
		// Log.e("CCALM", "provider disabled " + provider);
	}

	@Override
	public void onProviderEnabled(String provider)
	{
		// Log.e("CCALM", "provider enabled " + provider);
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras)
	{
		// Log.e("CCALM", "status changed to " + provider + " [" + status + "]");
	}

	/**
	 * СМ. http://developer.android.com/reference/android/app/Activity.html Событие происходит при старте и при возврате на этот Activity
	 * */
	@Override
	public void onStart() {
		super.onStart();
		DbOpenHelper dboh = new DbOpenHelper(this);
		String sql="select * from terminals where del=0 and serial='"+ Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID)+"';";
		SQLiteDatabase rdb = null;
		Cursor cursor = null;
		try{
			rdb = dboh.getReadableDatabase();
			cursor = rdb.rawQuery(sql, null);
			if(!cursor.moveToFirst())
			{
				Toast toast = Toast.makeText(getApplicationContext(),
						getResources().getString(R.string.Please_authorize_the_tablet), Toast.LENGTH_LONG);
				toast.show();
			}
		} catch (Exception e) {
			Log.e("CCALM", "Database error occurred", e);
		}finally{
			if(cursor != null) { cursor.close(); }
			if(rdb!=null){ rdb.close(); }
		}
		dboh.close();
	}

	@Override
	public double getLat() {
		return this._lat;
	}

	@Override
	public double getLon() {
		return this._lon;
	}
}
