public interface VespappApi {

    @GET("sightings/{sightingId}/questions/")
    Call<List<Question>> getQuestions(@Path("sightingId") String sightingId);

    @GET("sightings/{sightingId}/photos/")
    Call <List<Picture>> getPhotos(@Path("sightingId") String sightingId);

    @GET("locations/")
    Call<List<Location>> getLocations();

    @GET("sightings/")
    Call<List<Sighting>> getSightings();

    @GET("info/")
    Call<List<Info>> getInfo();

    @POST("sightings/")
    Call<Sighting> createSighting(@Body Sighting sighting);

    @PUT("sightings/{sightingId}/")
    Call<Sighting> updateSighting(@Body Sighting sighting, @Path("sightingId") String sightingId);

    /**
     * @see VespappApiHelper#buildPhotoApiParameter(File)
     */
    @Multipart
    @POST("sightings/{sightingId}/photos/")
    Call<Void> addPhoto(@Path("sightingId") String sightingId, @Part("file\"; filename=\"photo.png\" ") RequestBody photo);
} public class Task {
    public static <T> void doInBackground(final TaskCallback<T> taskCallback) {
        new AsyncTask<Void, Void, T>() {
            @Override protected T doInBackground(Void... params) {
                try {
                    return taskCallback.executeInBackground();
                } catch (Throwable t) {
                    taskCallback.onError(t);
                    return null;
                }
            }

            @Override protected void onPostExecute(T t) {
                if (t != null) {
                    taskCallback.onCompleted(t);
                }
            }
        }.execute((Void) null);
    }
} public interface TaskCallback<T> {
    T executeInBackground();

    void onError(Throwable t);

    void onCompleted(T t);
} public class Database {
    private SharedPreferences preferences;
    private Gson gson;

    public Database(Context context, Gson gson) {
        this.gson = gson;
        preferences = context.getSharedPreferences("database", Context.MODE_PRIVATE);
    }

    public static Database get(Context context) {
        return Vespapp.get(context).getDatabase();
    }

    public static Database get(Controller controller) {
        return get(controller.getContext());
    }

    private SharedPreferences getPrefs() {
        return preferences;
    }

    public void save(String key, Object obj) {
        save(key, gson.toJson(obj));
    }

    public void save(String key, String value) {
        getStringPref(key).set(value);
    }

    public void save(String key, int value) {
        getIntPref(key).set(value);
    }

    public void delete(String key) {
        getStringPref(key).delete();
    }

    public String load(String key) {
        return getStringPref(key).get();
    }

    public <T> T load(String key, Class<T> cls) {
        return gson.fromJson(load(key), cls);
    }

    public int loadInt(String key) {
        return getIntPref(key).get();
    }

    public void saveInt(String key, int value) {
        getIntPref(key).set(value);
    }

    @NonNull private StringPreference getStringPref(String key) {
        return new StringPreference(getPrefs(), key);
    }

    @NonNull private IntPreference getIntPref(String key) {
        return new IntPreference(getPrefs(), key);
    }
} public class Info implements Serializable {

    private String title;
    private String body;
    private String image;

    public Info(String title, String body, String image) {
        this.title = title;
        this.body = body;
        this.image = image;
    }

    public String getTitle() {
        return title;
    }

    public String getBody() {
        return body;
    }

    public String getImage() {
        return image;
    }
} public class InfoDescriptionActivity extends AppCompatActivity {

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

        initToolbar();

        Intent i = getIntent();
        Info info = (Info) i.getSerializableExtra("infoObject");
        String title = info.getTitle();
        String body = info.getBody();
        String imageUrl = info.getImage();

        setNameToolbar(title);

        TextView textBody = (TextView) findViewById(R.id.info_body);
        textBody.setText(body);

        try {/*
            ImageView imageInfo = (ImageView)findViewById(R.id.info_image);
            Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageUrl).getContent());
            imageInfo.setImageBitmap(bitmap);*/

            ImageView imageInfo = (ImageView)findViewById(R.id.info_image);
            Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageUrl).getContent());
            Display display = getWindowManager().getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            int widthDisplay = size.x;
            int heightDisplay = size.y;
            double heightFinal = widthDisplay*0.6;
            int heightFinal1 =  (int) heightFinal;

            bitmap = resizeBitmap(bitmap, widthDisplay, heightFinal1);
            imageInfo.setImageBitmap(bitmap);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
        }
    }

    public static Bitmap resizeBitmap(Bitmap bitmap, int width, int height) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) width / w);
        float scaleHeight = ((float) height / h);
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
        return newbmp;
    }

    private void initToolbar() {
        // Set a toolbar to replace the action bar.
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_info_description);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void setNameToolbar (String s){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle(s);
    }

} public class Map {

    private GoogleMap Gmap;

    public Map(GoogleMap Gmap) {
        this.Gmap = Gmap;
    }


   /* public void getCurrentPosition() {
        // Search my position
        LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener locListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {
                //Toast.makeText(getApplicationContext(), "Gps enabled.", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onProviderDisabled(String provider) {
                //Toast.makeText(getApplicationContext(), "Gps disabled.", Toast.LENGTH_SHORT).show();
            }
        };
        String locationProvider = LocationManager.NETWORK_PROVIDER;
        locManager.requestLocationUpdates(locationProvider, 0, 0, locListener);

        // Display my position in the map
        Location currentLocation = locManager.getLastKnownLocation(locationProvider);
        LatLng myLocation = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
        CameraPosition camPos = new CameraPosition.Builder().target(myLocation).zoom(14).build();
        CameraUpdate camUpd3 = CameraUpdateFactory.newCameraPosition(camPos);

        Gmap.animateCamera(camUpd3);
        Gmap.addMarker(new MarkerOptions().position(myLocation));
    }*/


    public void moveCamera(double lat, double lng, int zoom) {
        //First Vision, center on teh Balearic Islands
        LatLng cameraFocus = new LatLng(lat, lng);
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(cameraFocus, zoom);
        Gmap.animateCamera(cameraUpdate);
    }


    public void removeMap() {
        Gmap.clear();
    }
} public class ContributorsActivity extends AppCompatActivity {


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

        initToolbar();
    }

    private void initToolbar() {
        // Set a toolbar to replace the action bar.
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_menu_contributors);
        setSupportActionBar(toolbar);
        toolbar.setTitleTextColor(getResources().getColor(R.color.colorTitle));
        toolbar.setBackgroundColor(getResources().getColor(R.color.brandPrimary));
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle(R.string.title_activity_menu_contributors);
    }
} public class AboutUsActivity extends AppCompatActivity {

    /**
     * The number of pages (wizard steps) to show in this demo.
     */
    private static final int NUM_PAGES = 4;

    /**
     * The pager widget, which handles animation and allows swiping horizontally to access previous
     * and next wizard steps.
     */
    private ViewPager mPager;

    /**
     * The pager adapter, which provides the pages to the view pager widget.
     */
    private PagerAdapter mPagerAdapter;

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


        initToolbar();

        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
        mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // When changing pages, reset the action bar actions since they are dependent
                // on which page is currently active. An alternative approach is to have each
                // fragment expose actions itself (rather than the activity exposing actions),
                // but for simplicity, the activity provides the actions in this sample.

              Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_menu_about_us);
                TextView progressQuestionText = (TextView) toolbar.findViewById(R.id.progress_text_about_us);
                position += 1;
                progressQuestionText.setText(position + "/" + NUM_PAGES);

                invalidateOptionsMenu();

            }
        });
    }

    private void initToolbar() {
        // Set a toolbar to replace the action bar.
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_menu_about_us);
        setSupportActionBar(toolbar);
        toolbar.setTitleTextColor(getResources().getColor(R.color.colorTitle));
        toolbar.setBackgroundColor(getResources().getColor(R.color.brandPrimary));
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        TextView progressQuestionText = (TextView) toolbar.findViewById(R.id.progress_text_about_us);
        progressQuestionText.setText("1/" + NUM_PAGES);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle(R.string.title_activity_menu_about_us);
    }

    private class ScreenSlidePagerAdapter extends FragmentPagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return ScreenSlidePageFragment.create(position);
        }


        @Override
        public int getCount() {
            return NUM_PAGES;
        }
    }
} public class ContactActivity extends AppCompatActivity {

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

        initToolbar();

        ((Button) findViewById(R.id.sendButton_contact)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText name = (EditText) findViewById(R.id.name_contact);
                EditText subject = (EditText) findViewById(R.id.subject_contact);
                EditText body = (EditText) findViewById(R.id.body_contact);
                EditText phone = (EditText) findViewById(R.id.phone_contact);

                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("message/rfc822");
                i.putExtra(Intent.EXTRA_EMAIL, new String[]{"vespapp.uib@gmail.com"});
                i.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString());
                i.putExtra(Intent.EXTRA_TEXT, "Enviado por: " + name.getText().toString() + "\n\nNúmero de teléfono: " + phone.getText().toString() + "\n\nMensaje: " + body.getText().toString());
                try {
                    startActivity(Intent.createChooser(i, "Escoje la que quieras..."));
                } catch (android.content.ActivityNotFoundException ex) {
                    System.out.println("There are no email clients installed");
                }
            }
        });

    }

    private void initToolbar() {
        // Set a toolbar to replace the action bar.
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_menu_contact);
        setSupportActionBar(toolbar);
        toolbar.setTitleTextColor(getResources().getColor(R.color.colorTitle));
        toolbar.setBackgroundColor(getResources().getColor(R.color.brandPrimary));
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle(R.string.title_activity_menu_contact);
    }


} public class PicturesActions {

    private List<String> list = new ArrayList<>();


    public PicturesActions() {
    }


    public List<String> getList() {
        return list;
    }

    public static File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
    }



    public void resize(File photo, int width, int height) {
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(photo.getAbsolutePath(), bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        int scaleFactor = Math.min(photoW / width, photoH / height);

        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(photo.getAbsolutePath(), bmOptions);

        saveBitmapToFile(bitmap, photo);
    }

    private void saveBitmapToFile(Bitmap bitmap, File photo) {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(photo.getAbsolutePath());
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
            // PNG is a lossless format, the compression factor (100) is ignored
        } catch (Exception e) {
            throw new RuntimeException("Could not save bitmap into file(" + photo.getAbsolutePath() + "): " + e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                throw new RuntimeException("Could not save bitmap into file(" + photo.getAbsolutePath() + "): " + e);
            }
        }
    }


    public int getImageSize(File photo) {
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = false;
        Bitmap image = BitmapFactory.decodeFile(photo.getAbsolutePath(), bmOptions);
        return image.getByteCount();
    }
} public class Sighting implements Serializable {

    private static final int STATUS_PENDING = 0;
    private static final int STATUS_PROCESSING = 1;
    private static final int STATUS_PROCESSED = 2;
    //private static final int STATUS_UNSENT = -1;

    public static final int TYPE_WASP = 1;
    public static final int TYPE_NEST = 2;


    private int id;
    private int status;
    private String free_text = "";
    private int type;
    private String contact;
    private String created_at;

    private String source = "app";

    @SerializedName("public")
    private boolean _public;
    private Boolean is_valid;

    private int location;

    private float lat;
    private float lng;

    private List<Picture> pictures = null;
    private List<Integer> answers = null;

    public Sighting() {

    }

    public Sighting(int id, int status, String free_text, int type,
                    String contact, String source, boolean _public, boolean is_valid,
                    int location, float lat, float lng) {
        this.id = id;
        this.status = status;
        this.free_text = free_text;
        this.type = type;
        this.contact = contact;
        this.source = source;
        this._public = _public;
        this.is_valid = is_valid;
        this.location = location;
        this.lat = lat;
        this.lng = lng;
    }

    public int getId() {
        return id;
    }

    public int getStatus() {
        return status;
    }

    public String getFree_text() {
        return free_text;
    }

    public int getType() {
        return type;
    }

    public String getContact() {
        return contact;
    }

    public String getSource() {
        return source;
    }

    public boolean is_public() {
        return _public;
    }

    public int getLocation() {
        return location;
    }

    public float getLat() {
        return lat;
    }

    public float getLng() {
        return lng;
    }

    public List<Picture> getPictures() {
        return pictures;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public void setFree_text(String free_text) {
        this.free_text = free_text;
    }

    public void setType(int type) {
        this.type = type;
    }

    public void setContact(String contact) {
        this.contact = contact;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public void set_public(boolean _public) {
        this._public = _public;
    }

    public void setLocation(int location) {
        this.location = location;
    }

    public void setLat(float lat) {
        this.lat = lat;
    }

    public void setLng(float lng) {
        this.lng = lng;
    }

    public void setPictures(List<Picture> pictures) {
        this.pictures = pictures;
    }

    public Boolean is_valid() {
        return is_valid;
    }

    public void set_valid(Boolean is_valid) {
        this.is_valid = is_valid;
    }

    public List<Integer> getAnswers() {
        return answers;
    }

    public void setAnswers(List<Integer> answers) {
        this.answers = answers;
    }

    public String getCreated_at() {
        return created_at;
    }

    public void setCreated_at(String created_at) {
        this.created_at = created_at;
    }

} public class NewSightingDataActivity extends AppCompatActivity {

    private static final int TAKE_CAPTURE_REQUEST = 0;
    private static final int PICK_IMAGE_REQUEST = 1;
    private File photoFile;

    RecyclerViewAdapter rcAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_sighting_data);
        ButterKnife.bind(this);

        initToolbar();
        initAlbum();
        initAddBtn();
        initSelectBtn();
    }

    private void initToolbar() {
        // Set a toolbar to replace the action bar.
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_sigthing_data);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle(R.string.confirm_cap_titulo);
    }

    private void initAlbum() {
        PicturesActions picturesActions = getPicturesList();

        GridLayoutManager gridLayout = new GridLayoutManager(this, 2);

        RecyclerView rView = (RecyclerView) findViewById(R.id.recycle_pictures);
        rView.setHasFixedSize(true);
        rView.setLayoutManager(gridLayout);

        rcAdapter = new RecyclerViewAdapter(this, picturesActions.getList());
        rView.setAdapter(rcAdapter);
    }

    private void initAddBtn() {
        Button btn = (Button) findViewById(R.id.btn_add_picture);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    takePhoto();
                } catch (IOException e) {
                }
            }
        });
    }

    private void initSelectBtn() {
        Button btn = (Button) findViewById(R.id.btn_select_picture);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectPicture();
            }
        });
    }

    private void takePhoto() throws IOException {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        photoFile = PicturesActions.createImageFile();
        savePicturePathToDatabase(photoFile.getAbsolutePath());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        startActivityForResult(intent, TAKE_CAPTURE_REQUEST);
    }

    private void selectPicture() {
        Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, PICK_IMAGE_REQUEST);
    }

    @OnClick(R.id.btn_nido)
    void onNestPressed() {
        onTypeOfSightPressed(Sighting.TYPE_NEST);
    }

    @OnClick(R.id.btn_avispa)
    void onWaspPressed() {
        onTypeOfSightPressed(Sighting.TYPE_WASP);
    }



    private void onTypeOfSightPressed(int type) {
        Sighting sighting = new Sighting();
        sighting.setType(type);
        Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
        Account[] accounts = AccountManager.get(getApplicationContext()).getAccounts();
        for (Account account : accounts) {
            if (emailPattern.matcher(account.name).matches()) {
                String userEmail = account.name;
                sighting.setContact(userEmail);
            }
        }

       // sighting.set_valid(null);

        Intent i = new Intent(this, NewSightingLocationsActivity.class);
        i.putExtra("sightingObject", sighting);
        startActivity(i);
    }



    private PicturesActions getPicturesList() {
        return Database.get(this).load(Constants.PICTURES_LIST, PicturesActions.class);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            String picturePath = null;

            switch (requestCode) {
                case TAKE_CAPTURE_REQUEST:
                    picturePath = getPicturePathFromDatabase();
                    //photoFile = new File(picturePath);
                    //picturesActions.resize(photoFile, 640, 480);
                    break;
                case PICK_IMAGE_REQUEST:
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    break;
            }

            savePictureToDatabase(picturePath);
        }
    }

    private void savePicturePathToDatabase(String picturePath) {
        Database.get(this).save(Constants.KEY_CAPTURE, picturePath);
    }

    private String getPicturePathFromDatabase() {
        return Database.get(this).load(Constants.KEY_CAPTURE);
    }

    private void savePictureToDatabase(String picturePath) {
        PicturesActions picturesActions = Database.get(this).load(Constants.PICTURES_LIST, PicturesActions.class);

        if (picturesActions == null) {
            picturesActions = new PicturesActions();
        }

        if (picturesActions.getList().size() == 5) {
            Toast.makeText(this, "No se pueden subir más de 5 imágenes", Toast.LENGTH_LONG).show();
        } else {
            picturesActions.getList().add(picturePath);
            Database.get(this).save(Constants.PICTURES_LIST, picturesActions);
            rcAdapter.addPhoto(picturePath);
        }
    }
} public class SightingViewActivity extends AppCompatActivity {

    private static Sighting sighting;

    private Map map;
    private Marker marker;

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

        initToolbar();

        Intent i = getIntent();
        sighting = (Sighting) i.getSerializableExtra("sightingObject");

        initTabs();

        getInfo();
        getPictures();
        initMap();
    }

    private void initToolbar() {
        // Set a toolbar to replace the action bar.
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_sigthing_view);
        setSupportActionBar(toolbar);
        toolbar.setTitleTextColor(getResources().getColor(R.color.colorTitle));
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle(R.string.confirm_cap_map_sight);
    }

    private void initTabs() {
        final TabHost tabs = (TabHost) findViewById(R.id.tabs_sighting_view);
        tabs.setup();

        TabHost.TabSpec spec = tabs.newTabSpec("PicsTab");
        spec.setContent(R.id.layout_pictures_sighting_tab);
        spec.setIndicator("Fotos");

        tabs.addTab(spec);

        spec = tabs.newTabSpec("MainTab");
        spec.setContent(R.id.layout_info_sighting_tab);
        spec.setIndicator("Info");
        tabs.addTab(spec);

        spec = tabs.newTabSpec("MapTab");
        spec.setContent(R.id.map);
        spec.setIndicator("Mapa");
        tabs.addTab(spec);

        //Add color initial
        tabs.getTabWidget().getChildAt(1).setBackgroundColor(getResources().getColor(R.color.brandPrimary));

        //Set color text
        int totalTabs = tabs.getTabWidget().getTabCount();

        for (int i=0; i<totalTabs; i++){
            TextView tv = (TextView) tabs.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
            tv.setTextColor(getResources().getColor(R.color.colorTitle));
        }

        tabs.setCurrentTab(1);

        tabs.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            public void onTabChanged(String tabId) {
                int i = tabs.getCurrentTab();
                if (i == 0) {
                    tabs.getTabWidget().getChildAt(i).setBackgroundColor(getResources().getColor(R.color.orange));
                    tabs.getTabWidget().getChildAt(1).setBackgroundColor(getResources().getColor(R.color.brandPrimary));
                    tabs.getTabWidget().getChildAt(2).setBackgroundColor(getResources().getColor(R.color.brandPrimary));

                } else if (i == 1) {
                    tabs.getTabWidget().getChildAt(i).setBackgroundColor(getResources().getColor(R.color.orange));
                    tabs.getTabWidget().getChildAt(0).setBackgroundColor(getResources().getColor(R.color.brandPrimary));
                    tabs.getTabWidget().getChildAt(2).setBackgroundColor(getResources().getColor(R.color.brandPrimary));

                } else if (i == 2) {
                    tabs.getTabWidget().getChildAt(i).setBackgroundColor(getResources().getColor(R.color.orange));
                    tabs.getTabWidget().getChildAt(0).setBackgroundColor(getResources().getColor(R.color.brandPrimary));
                    tabs.getTabWidget().getChildAt(1).setBackgroundColor(getResources().getColor(R.color.brandPrimary));

                }
            }
        });
    }


    @TargetApi(Build.VERSION_CODES.M)
    private void getInfo() {
        TextView lSource = (TextView) findViewById(R.id.sighting_source_label);
        lSource.setText("Notificado por:");
        TextView tSource = (TextView) findViewById(R.id.sighting_source);
        String source = sighting.getSource();
        tSource.setText(source);

        if (source.equals("web")) {
            ImageView myImage = (ImageView) findViewById(R.id.sighting_source_image);
            myImage.setImageResource(R.mipmap.ic_computer);
        } else if (source.equals("app")) {
            ImageView myImage = (ImageView) findViewById(R.id.sighting_source_image);
            myImage.setImageResource(R.mipmap.ic_movile);
        } else { //Twitter
            ImageView myImage = (ImageView) findViewById(R.id.sighting_source_image);
            myImage.setImageResource(R.mipmap.ic_twitter);
        }

        TextView lLat = (TextView) findViewById(R.id.sighting_lat_label);
        lLat.setText("Latitud:");
        TextView tLat = (TextView) findViewById(R.id.sighting_lat);
        tLat.setText(String.valueOf(sighting.getLat()));

        TextView lLng = (TextView) findViewById(R.id.sighting_lng_label);
        lLng.setText("Longitud:");
        TextView tLng = (TextView) findViewById(R.id.sighting_lng);
        tLng.setText(String.valueOf(sighting.getLng()));

        TextView lType = (TextView) findViewById(R.id.sighting_type_label);
        lType.setText("Tipo:");
        TextView tType = (TextView) findViewById(R.id.sighting_type);
        int type = sighting.getType();
        if (type == 1) {
            tType.setText(String.valueOf("Avispa"));
        } else if(type == 2){
            tType.setText(String.valueOf("Nido"));
        }else {
            tType.setText("-");
        }


        TextView lStatus = (TextView) findViewById(R.id.sighting_status_label);
        lStatus.setText("Estado:");
        TextView tStatus = (TextView) findViewById(R.id.sighting_status);
        int status = sighting.getStatus();
        if (status == 0) {
            tStatus.setText(String.valueOf("Pendiente"));
            tStatus.setBackgroundColor(getResources().getColor(R.color.statusPending));
        } else if (status == 1) {
            tStatus.setText(String.valueOf("Procesando"));
            tStatus.setBackgroundColor(getResources().getColor(R.color.statusProcessing));
        } else if (status == 2) {
            tStatus.setText(String.valueOf("Procesado"));
            tStatus.setBackgroundColor(getResources().getColor(R.color.statusValidated));
        }

        TextView lResult = (TextView) findViewById(R.id.sighting_result_label);
        lResult.setText("Resultado:");
        TextView tResult = (TextView) findViewById(R.id.sighting_result);
        Boolean result = sighting.is_valid();
        if (result == null) {
            tResult.setText(String.valueOf("Desconocido"));
            tResult.setBackgroundColor(getResources().getColor(R.color.resultUnknown));
        } else if (result == false) {
            tResult.setText(String.valueOf("Negativo"));
            tResult.setBackgroundColor(getResources().getColor(R.color.resultNo));
        } else if (result == true) {
            tResult.setText(String.valueOf("Positivo"));
            tResult.setBackgroundColor(getResources().getColor(R.color.resultYes));
        }

/*        TextView lData = (TextView) findViewById(R.id.sighting_data_label);
        lData.setText("Fecha:");
        TextView tData = (TextView) findViewById(R.id.sighting_data);

        tData.setText(sighting.getCreated_at());*/


        TextView lDescription = (TextView) findViewById(R.id.sighting_description_label);
        lDescription.setText("Descripción:");
        TextView tDescription = (TextView) findViewById(R.id.sighting_description);
        if(!sighting.getFree_text().isEmpty()){
            tDescription.setText(sighting.getFree_text());
        }else{
            tDescription.setText("-");
        }


    }


    private void getPictures() {
        final VespappApi api = Vespapp.get(this).getApi();

        final Callback<List<Picture>> callback = new Callback<List<Picture>>() {
            @Override
            public void onResponse(Call<List<Picture>> call, Response<List<Picture>> response) {
                List<Picture> pictureList = response.body();
                sighting.setPictures(pictureList);
                printPictures(pictureList);
            }

            @Override
            public void onFailure(Call<List<Picture>> call, Throwable t) {
                System.out.println("onFailure " + t);
            }
        };
        Task.doInBackground(new TaskCallback<List<Picture>>() {
            @Override
            public List<Picture> executeInBackground() {
                Call<List<Picture>> call = api.getPhotos(String.valueOf(sighting.getId()));
                call.enqueue(callback);
                return null;
            }

            @Override
            public void onError(Throwable t) {
                callback.onFailure(null, t);
            }

            @Override
            public void onCompleted(List<Picture> locations) {
                callback.onResponse(null, Response.success((List<Picture>) null));

            }
        });
    }

    public String parseDateToddMMyyyy(String time) {
        System.out.println(time);
        String inputPattern = "yyyy-MM-dd'T'HH:mm:ss'Z'";
        String outputPattern = "dd-MMM-yyyy h:mm a";
        SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
        SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);

        Date date = null;
        String str = null;

        try {
            date = inputFormat.parse(time);
            str = outputFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return str;
    }


    private void printPictures(List<Picture> picturesList) {
        for (Picture picture : picturesList) {
            addItemList(picture);
        }
    }

    private void addItemList(final Picture picture) {
        Bitmap bitmap = null;
        ImageView imageInfo = null;
        try {
            LinearLayout ll = (LinearLayout) findViewById(R.id.layout_pictures_sighting_tab);

            imageInfo = new ImageView(this);
            LinearLayout.LayoutParams vp =
                    new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.MATCH_PARENT);
            imageInfo.setLayoutParams(vp);

            imageInfo.setAdjustViewBounds(true); //Adjust the height to size photo
            imageInfo.setCropToPadding(true);
            vp.setMargins(0, 35, 0, 0); //(left, top, right, bottom);

            bitmap = BitmapFactory.decodeStream((InputStream) new URL(picture.getFile()).getContent());
            Display display = getWindowManager().getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            int widthDisplay = size.x;
            int heightDisplay = size.y;
            double heightFinal = widthDisplay*0.5;
            int i =  (int) heightFinal;

            bitmap = resizeBitmap(bitmap, widthDisplay, i);
            imageInfo.setImageBitmap(bitmap);

            ll.addView(imageInfo);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
        }
    }

    public static Bitmap resizeBitmap(Bitmap bitmap, int width, int height) {
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        Matrix matrix = new Matrix();
        float scaleWidth = ((float) width / w);
        float scaleHeight = ((float) height / h);
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
        return newbmp;
    }

    private void initMap() {
        final GoogleMap Gmap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        Gmap.setMyLocationEnabled(true);
        map = new Map(Gmap);

        double lat = sighting.getLat();
        double lng = sighting.getLng();
        int zoom = 15;

        LatLng myLocation = new LatLng(lat, lng);
        marker = Gmap.addMarker(new MarkerOptions().position(myLocation));
        map.moveCamera(lat, lng, zoom);
    }
}
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.habitissimo.vespapp.api.VespappApi;
import com.habitissimo.vespapp.async.Task;
import com.habitissimo.vespapp.async.TaskCallback;
import com.habitissimo.vespapp.database.Database;
import com.habitissimo.vespapp.info.Info;
import com.habitissimo.vespapp.info.InfoDescriptionActivity;
import com.habitissimo.vespapp.map.Map;
import com.habitissimo.vespapp.menu.ContributorsActivity;
import com.habitissimo.vespapp.menu.AboutUsActivity;
import com.habitissimo.vespapp.menu.ContactActivity;
import com.habitissimo.vespapp.sighting.PicturesActions;
import com.habitissimo.vespapp.sighting.Sighting;
import com.habitissimo.vespapp.sighting.NewSightingDataActivity;
import com.habitissimo.vespapp.sighting.SightingViewActivity;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

                    tabs.getTabWidget().getChildAt(i).setBackgroundColor(getResources().getColor(R.color.orange));
                    tabs.getTabWidget().getChildAt(0).setBackgroundColor(getResources().getColor(R.color.brandPrimary));
                    tabs.getTabWidget().getChildAt(1).setBackgroundColor(getResources().getColor(R.color.brandPrimary));
                    tabs.getTabWidget().getChildAt(3).setBackgroundColor(getResources().getColor(R.color.brandPrimary));

                    initMap();
                } else if (i == 3) {
                    if (map != null) {
                        map.removeMap();
                    }
                    LinearLayout ll = (LinearLayout) findViewById(R.id.layout_info_tab);
                    ll.removeAllViews();

                    tabs.getTabWidget().getChildAt(i).setBackgroundColor(getResources().getColor(R.color.orange));
                    tabs.getTabWidget().getChildAt(0).setBackgroundColor(getResources().getColor(R.color.brandPrimary));
                    tabs.getTabWidget().getChildAt(1).setBackgroundColor(getResources().getColor(R.color.brandPrimary));
                    tabs.getTabWidget().getChildAt(2).setBackgroundColor(getResources().getColor(R.color.brandPrimary));

                    initMenuOptions();
                }
            }
        });
    }

    private void initCamBtn() {
        ImageButton btn = (ImageButton) findViewById(R.id.btn_cam);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    takePhoto();
                } catch (IOException e) {
                }
            }
        });
    }

    private void initMenuOptions() {
        ((RelativeLayout) findViewById(R.id.layout_menu_tab_contact)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), ContactActivity.class);
                startActivity(i);
            }
        });
        ((RelativeLayout) findViewById(R.id.layout_menu_tab_about_us)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), AboutUsActivity.class);
                startActivity(i);
            }
        });
        ((RelativeLayout) findViewById(R.id.layout_menu_tab_contributors)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(), ContributorsActivity.class);
                startActivity(i);
            }
        });
    }

    private void initSelectPicturesBtn() {
        Button btn = (Button) findViewById(R.id.btn_selFotos);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectPicture();
            }
        });
    }


    public void takePhoto() throws IOException {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        photoFile = PicturesActions.createImageFile();
        savePicturePathToDatabase(photoFile.getAbsolutePath());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        startActivityForResult(intent, TAKE_CAPTURE_REQUEST);
    }

    public void selectPicture() {
        Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, PICK_IMAGE_REQUEST);
    }

    private void getInfo() {
        final VespappApi api = Vespapp.get(this).getApi();

        final Callback<List<Info>> callback = new Callback<List<Info>>() {
            @Override
            public void onResponse(Call<List<Info>> call, Response<List<Info>> response) {
                LinearLayout ll = (LinearLayout) findViewById(R.id.layout_info_tab);
                final List<Info> infoList = response.body();
                for (final Info info : infoList) {
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                            ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT);
                    params.setMargins(15, 50, 20, 20);
                    Button btn = new Button(getApplicationContext());
                    btn.setText(info.getTitle());
                    btn.setBackgroundResource(R.drawable.button_selector);
                    btn.setTextSize((int) getResources().getDimension(R.dimen.text_info_button));
                    btn.setLayoutParams(params);
                    btn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent i = new Intent(getApplicationContext(), InfoDescriptionActivity.class);
                            i.putExtra("infoObject", info);
                            startActivity(i);
                        }
                    });
                    ll.addView(btn);
                }
            }

            @Override
            public void onFailure(Call<List<Info>> call, Throwable t) {
                System.out.println("onFailure " + t);
            }
        };
        Task.doInBackground(new TaskCallback<List<Info>>() {