metrocasas.projectsgt.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for metrocasas.projectsgt.MainActivity.java

Source

package metrocasas.projectsgt;

import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferListener;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferObserver;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferState;
import com.amazonaws.mobileconnectors.s3.transferutility.TransferUtility;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends AppCompatActivity
        implements MediaPlayer.OnCompletionListener, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener, OnSimpleDialogListener {

    //<editor-fold desc="Variables Mapas">
    public static final String TAG = MapsActivity.class.getSimpleName();
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    private GoogleMap mMap;
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    //</editor-fold>

    //<editor-fold desc="Views">
    TextView t1, upLoadInfo, nextImg, prevImg, audioNameFile;
    Button grabar, detener, escuchar, tomarFoto, obtenerGaleria, openFile;
    FloatingActionButton enviar;
    EditText title, front, back, unities, developer, phone;
    Spinner licencia, categoria;

    LinearLayout p;
    ScrollView q;
    //</editor-fold>

    //<editor-fold desc="Variables Audio">
    File audioFile;
    MediaRecorder myAudioRecorder;
    MediaPlayer player;
    String audio = "";
    //</editor-fold>

    //<editor-fold desc="Varianes">
    private int currImage = 0;
    private String userid;
    private String pictureImagePath = "";
    private ArrayList<Bitmap> imagenes = new ArrayList<>();
    private ArrayList<File> archivos = new ArrayList<>();
    public final static int RESULT_CAMERA = 1;
    public final static int RESULT_LOAD_IMAGE = 2;
    public final static int FILE_SELECT_CODE = 3;
    ImageSwitcher imageSwitcher;
    String imageListNames = "";
    ImageView header;
    //</editor-fold>

    //<editor-fold desc="Variables Amazon S3">
    public final static String BUCKET_NAME = "projectsgtimages";
    //</editor-fold>

    //<editor-fold desc="Variables Modelo Apartamento">
    private List<Apartamento> listApartamento = new ArrayList<>();
    private ApartamentoAdapter aAdapter;
    //</editor-fold>

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        userid = getIntent().getExtras().getString("id");

        //<editor-fold desc="Setting Map">
        mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(LocationServices.API).build();

        mLocationRequest = LocationRequest.create().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000) // 10 seconds, in milliseconds
                .setFastestInterval(1000); // 1 second, in milliseconds
        //</editor-fold>

        //<editor-fold desc="Setting Views">
        title = (EditText) findViewById(R.id.editTextTitle);
        front = (EditText) findViewById(R.id.editTextFrente);
        back = (EditText) findViewById(R.id.editTextBack);
        unities = (EditText) findViewById(R.id.editTextUnidades);
        developer = (EditText) findViewById(R.id.editTextDesarrollador);
        phone = (EditText) findViewById(R.id.editTextTelefono);

        p = (LinearLayout) findViewById(R.id.layoutprogress);
        q = (ScrollView) findViewById(R.id.layoutinfo);
        myAudioRecorder = new MediaRecorder();
        t1 = (TextView) findViewById(R.id.t1);
        upLoadInfo = (TextView) findViewById(R.id.tvUpload);
        grabar = (Button) findViewById(R.id.btnStart);
        detener = (Button) findViewById(R.id.btnStop);
        escuchar = (Button) findViewById(R.id.btnPlay);
        tomarFoto = (Button) findViewById(R.id.takePicture);
        obtenerGaleria = (Button) findViewById(R.id.getPicture);
        prevImg = (Button) findViewById(R.id.prevImg);
        nextImg = (Button) findViewById(R.id.nxtImg);
        licencia = (Spinner) findViewById(R.id.licencia);
        categoria = (Spinner) findViewById(R.id.categoria);
        enviar = (FloatingActionButton) findViewById(R.id.send_info);
        header = (ImageView) findViewById(R.id.imgHeader);
        Button btn_nuevo = (Button) findViewById(R.id.btnNew);
        openFile = (Button) findViewById(R.id.loadFile);
        audioNameFile = (TextView) findViewById(R.id.audioNameFile);
        //</editor-fold>

        assert btn_nuevo != null;
        btn_nuevo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ApartamentoDialog().show(getFragmentManager(), "");
            }
        });

        initializeImageSwitcher();
        setInitialImage();
        setImageRotateListener();

        header.setFocusableInTouchMode(true);
        header.requestFocus();
        header.requestFocusFromTouch();

        grabar.setEnabled(true);
        detener.setEnabled(false);
        escuchar.setEnabled(false);

        grabar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                grabarAudio(v);
            }
        });

        detener.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                detenerGrabacion(v);
            }
        });

        escuchar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reproducir(v);
                escuchar.setEnabled(false);
            }
        });

        tomarFoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openBackCamera();
            }
        });

        obtenerGaleria.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery();
            }
        });

        prevImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                prevImage();
            }
        });

        nextImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nextImage();
            }
        });

        openFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadFile();
            }
        });

        //<editor-fold desc="Setting Spinners">
        ArrayAdapter<CharSequence> staticAdapter2 = ArrayAdapter.createFromResource(this, R.array.list_license,
                android.R.layout.simple_spinner_item);
        staticAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        licencia.setAdapter(staticAdapter2);

        ArrayAdapter<CharSequence> staticAdapter3 = ArrayAdapter.createFromResource(this, R.array.list_category,
                android.R.layout.simple_spinner_item);
        staticAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        categoria.setAdapter(staticAdapter3);
        //</editor-fold>

        enviar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isNetworkAvailable()) {
                    upLoadFiles();
                } else {
                    Toast.makeText(getApplication(), "No tienes conexin a internet", Toast.LENGTH_LONG).show();
                }
            }
        });

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        aAdapter = new ApartamentoAdapter(listApartamento);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        assert recyclerView != null;
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(aAdapter);
        RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL_LIST);
        recyclerView.addItemDecoration(itemDecoration);
        hello();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.logout) {
            new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_lock_lock).setTitle("Cerrar Sesin")
                    .setMessage("Est seguro que desea cerrar su sesin y salir?")
                    .setPositiveButton("Si", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            SharedPreferences settings = getApplicationContext().getSharedPreferences("User", 0);
                            SharedPreferences.Editor editor = settings.edit();
                            editor.putString("id", null);
                            editor.putString("firstname", null);
                            editor.apply();

                            finish();

                        }

                    }).setNegativeButton("No", null).show();
        }
        return super.onOptionsItemSelected(item);
    }

    public void grabarAudio(View v) {
        myAudioRecorder = new MediaRecorder();
        myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        myAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        File path = new File(Environment.getExternalStorageDirectory().getPath());
        try {
            Long tsLong = System.currentTimeMillis() / 1000;
            audioFile = File.createTempFile("descripcion" + tsLong.toString(), ".3gp", path);
            audio = audioFile.getName();
        } catch (IOException e) {
            Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
        }
        myAudioRecorder.setOutputFile(audioFile.getAbsolutePath());
        try {
            myAudioRecorder.prepare();
        } catch (IOException e) {
            Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
        }
        myAudioRecorder.start();
        grabar.setEnabled(false);
        detener.setEnabled(true);
        escuchar.setEnabled(false);
    }

    public void detenerGrabacion(View v) {
        myAudioRecorder.stop();
        myAudioRecorder.release();
        player = new MediaPlayer();
        player.setOnCompletionListener(this);
        audioNameFile.setText("ARCHIVO: " + audioFile.getName());
        try {
            player.setDataSource(audioFile.getAbsolutePath());
        } catch (IOException e) {
            Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
        }
        try {
            player.prepare();
        } catch (IOException e) {
            Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
        }
        grabar.setEnabled(true);
        detener.setEnabled(false);
        escuchar.setEnabled(true);
    }

    public void reproducir(View v) {
        player.start();
        grabar.setEnabled(false);
    }

    public void loadFile() {
        Intent intent = new Intent();
        intent.setType("*/3gp");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, FILE_SELECT_CODE);
    }

    public void onCompletion(MediaPlayer mp) {
        grabar.setEnabled(true);
        detener.setEnabled(false);
        escuchar.setEnabled(true);
    }

    private void openBackCamera() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = timeStamp + ".jpg";
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        pictureImagePath = storageDir.getAbsolutePath() + "/" + imageFileName;
        File file = new File(pictureImagePath);
        Uri outputFileUri = Uri.fromFile(file);
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        startActivityForResult(cameraIntent, RESULT_CAMERA);
    }

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

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RESULT_CAMERA) {
            File imgFile = new File(pictureImagePath);
            archivos.add(imgFile);
            imageListNames += imgFile.getName() + ";";
            if (imgFile.exists()) {
                Bitmap imageBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                imagenes.add(imageBitmap);
                setCurrentImage();
            }
        }
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            assert cursor != null;
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            imagenes.add(BitmapFactory.decodeFile(picturePath));
            File imgFile = new File(picturePath);
            archivos.add(imgFile);
            imageListNames += imgFile.getName() + ";";
            setCurrentImage();
        }
        if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK && null != data) {
            audioFile = new File(data.getData().getPath());
            audio = audioFile.getName();
            audioNameFile.setText("ARCHIVO: " + audioFile.getName());
        }
    }

    private void initializeImageSwitcher() {
        final ImageSwitcher imageSwitcher = (ImageSwitcher) findViewById(R.id.imgSwitcher);
        assert imageSwitcher != null;
        imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                return new ImageView(MainActivity.this);
            }
        });
        //imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left));
        //imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right));
    }

    private void setImageRotateListener() {

    }

    private void setInitialImage() {
        setCurrentImage();
    }

    private void setCurrentImage() {
        try {
            imageSwitcher = (ImageSwitcher) findViewById(R.id.imgSwitcher);
            Drawable drawable = new BitmapDrawable(imagenes.get(currImage));
            imageSwitcher.setImageDrawable(drawable);
        } catch (Exception ignored) {
            imageSwitcher = (ImageSwitcher) findViewById(R.id.imgSwitcher);
            assert imageSwitcher != null;
            imageSwitcher.setImageResource(0);
        }
    }

    public void nextImage() {
        currImage++;
        if (currImage == imagenes.size()) {
            currImage = 0;
        }
        setCurrentImage();
    }

    public void prevImage() {
        currImage--;
        if (currImage < 0) {
            currImage = imagenes.size() - 1;
        }
        setCurrentImage();
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public CognitoCachingCredentialsProvider amazonCognito() {
        CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
                getApplicationContext(), "us-east-1:66fdcec3-f2c0-4015-80ef-f9efcad31fb3", // Identity Pool ID
                Regions.US_EAST_1 // Region
        );
        return credentialsProvider;
    }

    boolean bandera = true;

    public void upLoadFiles() {
        bandera = true;
        ImageView img = (ImageView) findViewById(R.id.image_load);
        assert img != null;
        img.setBackgroundResource(R.drawable.load_files);

        // Get the background, which has been compiled to an AnimationDrawable object.
        AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();

        // Start the animation (looped playback by default).
        frameAnimation.start();
        if (!title.getText().toString().equals("")) {
            q.setVisibility(View.GONE);
            p.setVisibility(View.VISIBLE);
            if (audioFile != null) {
                archivos.add(audioFile);
            } else {
                audio = "";
            }
            if (!archivos.isEmpty()) {
                try {
                    for (File i : archivos) {
                        AmazonS3 s3Client = new AmazonS3Client(amazonCognito());
                        TransferUtility transferUtility = new TransferUtility(s3Client, this);
                        TransferObserver transferObserver = transferUtility.upload(BUCKET_NAME,
                                "projects/" + i.getName(), i);
                        transferObserver.setTransferListener(new TransferListener() {
                            @Override
                            public void onStateChanged(int id, TransferState state) {
                                if (state == TransferState.COMPLETED) {
                                    if (bandera) {
                                        ingresarDatos();
                                        limpiarCampos();
                                        bandera = false;
                                    }
                                }
                            }

                            @Override
                            public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
                            }

                            @Override
                            public void onError(int id, Exception ex) {
                                Toast.makeText(MainActivity.this, ex.toString(), Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (Exception e) {
                    ingresarDatos();
                    limpiarCampos();
                }
            } else {
                ingresarDatos();
                limpiarCampos();
            }
        } else {
            Toast.makeText(this, "Debe ingresar por lo menos el ttulo", Toast.LENGTH_LONG).show();
            q.scrollTo(0, 0);
            title.setFocusableInTouchMode(true);
            title.setFocusable(true);
            title.requestFocus();
        }
    }

    public void ingresarDatos() {
        q.setVisibility(View.GONE);
        p.setVisibility(View.VISIBLE);

        //<editor-fold desc="Validacion numeros">
        String front1;
        if (!front.getText().toString().equals("")) {
            front1 = front.getText().toString();
        } else {
            front1 = "0.0";
        }
        String back1;
        if (!back.getText().toString().equals("")) {
            back1 = back.getText().toString();
        } else {
            back1 = "0.0";
        }
        String unities1;
        if (!unities.getText().toString().equals("")) {
            unities1 = unities.getText().toString();
        } else {
            unities1 = "0";
        }
        //</editor-fold>

        new DataBaseActivity(this, p, q, listApartamento).execute(userid, title.getText().toString(), front1, back1,
                unities1, developer.getText().toString(), phone.getText().toString(),
                licencia.getSelectedItem().toString(), categoria.getSelectedItem().toString(),
                String.valueOf(mMap.getCameraPosition().target.latitude),
                String.valueOf(mMap.getCameraPosition().target.longitude), audio, imageListNames);
        q.scrollTo(0, 0);
    }

    public void limpiarCampos() {
        title.setText("");
        developer.setText("");
        phone.setText("");
        front.setText("");
        back.setText("");
        unities.setText("");
        aAdapter.notifyDataSetChanged();
        audioFile = null;
        audio = "";
        imagenes = new ArrayList<>();
        archivos = new ArrayList<>();
        imageListNames = "";
        audioNameFile.setText("");
        audio = "";
        setCurrentImage();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            FragmentManager myFragmentManager = getFragmentManager();
            MapFragment myMapFragment = (MapFragment) myFragmentManager.findFragmentById(R.id.map);
            mMap = myMapFragment.getMap();
            mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
                @Override
                public void onCameraChange(CameraPosition cameraPosition) {
                    q.setEnabled(false);
                }
            });
            mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                    q.setEnabled(true);
                }
            });
            if (ContextCompat.checkSelfPermission(this,
                    android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mMap.setMyLocationEnabled(true);
                mMap.getUiSettings().setZoomControlsEnabled(true);
            }
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {
        //mMap.addMarker(new MarkerOptions().position(new LatLng(, 0)).title("Marker"));
    }

    private void handleNewLocation(Location location) {
        Log.d(TAG, location.toString());
        double currentLatitude = location.getLatitude();
        double currentLongitude = location.getLongitude();
        LatLng latLng = new LatLng(currentLatitude, currentLongitude);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 16));
    }

    @Override
    public void onConnected(Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this,
                        android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        } else {
            handleNewLocation(location);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        /*
         * Google Play services can resolve some errors it detects.
         * If the error has a resolution, try sending an Intent to
         * start a Google Play services activity that can resolve
         * error.
         */
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services canceled the original
                 * PendingIntent
                 */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        //handleNewLocation(location);

    }

    @Override
    public void onPossitiveButtonClick(Apartamento apto) {
        listApartamento.add(apto);
        aAdapter.notifyDataSetChanged();
    }

    @Override
    public void onNegativeButtonClick() {
    }

    public boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) this.getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        return activeNetwork.isConnectedOrConnecting();
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    private void hello() {
        SharedPreferences settings = getApplicationContext().getSharedPreferences("User", 0);
        String name = settings.getString("firstname", null);
        String last = settings.getString("lastname", null);

        Snackbar.make(enviar, "Bienvenido(a) " + name + " " + last, Snackbar.LENGTH_LONG).show();
    }
}