Skip to content

Commit

Permalink
Merge branch 'feature/506510-BuscarAPartirDeCoordenadas' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
CanalesRRC committed Nov 19, 2024
2 parents fe1c565 + a112439 commit 086b1e0
Show file tree
Hide file tree
Showing 13 changed files with 236 additions and 37 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -69,5 +69,4 @@ public void testGasolinerasDatosVacios_A4() {


}

}
Original file line number Diff line number Diff line change
Expand Up @@ -36,36 +36,32 @@
@RunWith(AndroidJUnit4.class)
public class OrdenarPorPrecioAscUITest {

@Rule(order = 0) // the Hilt rule must execute first
public HiltAndroidRule hiltRule = new HiltAndroidRule(this);

@Rule(order = 1)
public ActivityScenarioRule<MainView> activityRule = new ActivityScenarioRule<>(MainView.class);

// I need the context to access resources, such as the json with test gas stations
final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();

// Mock repository that provides data from a JSON file instead of downloading it from the internet.
@BindValue
final IGasolinerasRepository repository = getTestRepository(context, R.raw.gasolineras_test);

View decorView;



@Test
public void ordenarPorPrecioAsc() {

Espresso.onView(withId(R.id.menuOrdenButton)).perform(click());
Espresso.onView(withId(R.id.spnOrden)).perform(click());
onView(withText(allOf(is("Ascendente"), instanceOf(String.class))))
.inRoot(isPlatformPopup())
.perform(click());
Espresso.onView(withId(R.id.spnCombustible)).perform(click());
onView(withText(allOf(is("Biodiesel"), instanceOf(String.class))))
.inRoot(isPlatformPopup())
.perform(click());
Espresso.onView(withText("Ordenar")).perform(click());

}
@Rule(order = 0) // the Hilt rule must execute first
public HiltAndroidRule hiltRule = new HiltAndroidRule(this);

@Rule(order = 1)
public ActivityScenarioRule<MainView> activityRule = new ActivityScenarioRule<>(MainView.class);

// I need the context to access resources, such as the json with test gas stations
final Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();

// Mock repository that provides data from a JSON file instead of downloading it from the internet.
@BindValue
final IGasolinerasRepository repository = getTestRepository(context, R.raw.gasolineras_test);

View decorView;

@Test
public void ordenarPorPrecioAsc() {
Espresso.onView(withId(R.id.menuOrdenButton)).perform(click());
Espresso.onView(withId(R.id.spnOrden)).perform(click());
onView(withText(allOf(is("Ascendente"), instanceOf(String.class))))
.inRoot(isPlatformPopup())
.perform(click());
Espresso.onView(withId(R.id.spnCombustible)).perform(click());
onView(withText(allOf(is("Biodiesel"), instanceOf(String.class))))
.inRoot(isPlatformPopup())
.perform(click());
Espresso.onView(withText("Ordenar")).perform(click());
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package es.unican.gasolineras.activities.main;

import java.util.List;

import es.unican.gasolineras.model.Gasolinera;
import es.unican.gasolineras.model.Municipio;
import es.unican.gasolineras.repository.IGasolinerasRepository;
Expand Down Expand Up @@ -79,6 +78,16 @@ public void onSearchStationsWithFilters(String provincia,String municipio, Strin
* @param orden the order (ascending or descending)
*/
public void ordenarGasolinerasPorPrecio(String combustible, String orden);

/**
* Handles the event when the coordinates button is clicked, displaying the coordinates options popup.
*/
public void onCoordinatesButtonClicked();

public void searchWithCoordinates(Double longitud, Double latitud, int distancia);



}

/**
Expand Down Expand Up @@ -154,14 +163,16 @@ public interface View {
*/
public void showOrdenarPopUp();


public void showCoordinatesPopUp();


/**
* Actualiza el spinner de municipios con una lista proporcionada.
* Anhade una opcion por defecto ("-") y establece el municipio previamente guardado si existe.
*
* @param municipios La lista de municipios para poblar el spinner.
*/
public void updateMunicipiosSpinner(List<Municipio> municipios);


}
}
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,64 @@ public void ordenarGasolinerasPorPrecio(String combustible, String orden) {
gasolinerasAOrdenar.sort(comparator);
// Mostramos la lista ordenada
view.showStations(gasolinerasAOrdenar);

}

@Override
public void onCoordinatesButtonClicked() {view.showCoordinatesPopUp();}

@Override
public void searchWithCoordinates(Double longitud, Double latitud, int distancia){

List<Gasolinera> gasolinerasFiltradas = this.gasolineras;

for(Gasolinera g: gasolinerasFiltradas){

String longitudStr = g.getLongitud(); // Obtener longitud como String
String latitudStr = g.getLatitud(); // Obtener latitud como String
// Convertir a Double
Double longitudGasolinera = Double.parseDouble(longitudStr);
Double latitudGasolinera = Double.parseDouble(latitudStr);

if(!estaEnCoordenadas(longitud, latitud, distancia, longitudGasolinera, latitudGasolinera)){
gasolinerasFiltradas.remove(g);
}
}

this.gasolineras = gasolinerasFiltradas;

view.showStations(gasolinerasFiltradas);

view.showLoadCorrect(gasolinerasFiltradas.size());


}

private boolean estaEnCoordenadas(Double longitudSelec, Double latitudSelec, int distancia, Double longitudGasolinera, Double latitudGasolinera){
final double RADIO_TIERRA_KM = 6371.0; // Radio de la Tierra en kilómetros

// Convertir todas las coordenadas a radianes
double latitudSelecRad = Math.toRadians(latitudSelec);
double longitudSelecRad = Math.toRadians(longitudSelec);
double latitudGasolineraRad = Math.toRadians(latitudGasolinera);
double longitudGasolineraRad = Math.toRadians(longitudGasolinera);

// Diferencias entre las coordenadas
double dLat = latitudGasolineraRad - latitudSelecRad;
double dLon = longitudGasolineraRad - longitudSelecRad;

// Fórmula de Haversine
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(latitudSelecRad) * Math.cos(latitudGasolineraRad)
* Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

// Calcular la distancia en kilómetros
double distanciaCalculada = RADIO_TIERRA_KM * c;

// Comprobar si la distancia calculada está dentro del radio especificado
return distanciaCalculada <= distancia;

}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
Expand All @@ -12,6 +11,7 @@
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
Expand All @@ -21,6 +21,9 @@
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.android.material.slider.Slider;

import org.parceler.Parcels;

import java.util.ArrayList;
Expand Down Expand Up @@ -111,6 +114,10 @@ public boolean onOptionsItemSelected(@NonNull MenuItem item) {
presenter.onOrdenarButtonClicked();
return true;
}
if (itemId == R.id.menuCoordenadasButton) {
presenter.onCoordinatesButtonClicked();
return true;
}
return super.onOptionsItemSelected(item);
}

Expand Down Expand Up @@ -278,6 +285,56 @@ public void showOrdenarPopUp() {
.show();
}

@Override
public void showCoordinatesPopUp(){

LayoutInflater inflater = LayoutInflater.from(this);
View view = inflater.inflate(R.layout.activity_distancia_coordenadas_popup, null);

EditText etLongitud = view.findViewById(R.id.etLongitud);
EditText etLatitud = view.findViewById(R.id.etLatitud);
Slider slider = view.findViewById(R.id.main_slider);
TextView tvDistancia = view.findViewById(R.id.tvDistancia);

// Configurar el listener del Slider
slider.addOnChangeListener((slider1, value, fromUser) -> {
// Actualiza el TextView con el valor actual del slider
tvDistancia.setText("Distancia: " + (int) value);
});

new AlertDialog.Builder(this)
.setTitle("Buscar Por Coordenadas")
.setView(view)
.setPositiveButton("Buscar", (dialog, which) -> {
applyCoordinates(etLatitud,etLongitud,tvDistancia);
dialog.dismiss();
})
.setNegativeButton("Cancelar", (dialog, which) -> dialog.dismiss())
.create()
.show();
}

private void applyCoordinates(EditText etLongitud, EditText etLatitud, TextView tvDistancia){
try {
// Obtener los valores de los EditText como String
String longitudStr = etLongitud.getText().toString().trim();
String latitudStr = etLatitud.getText().toString().trim();

// Convertirlos a double
double longitud = Double.parseDouble(longitudStr);
double latitud = Double.parseDouble(latitudStr);

// Obtener el valor del TextView y convertirlo (si se usa como número)
String distanciaStr = tvDistancia.getText().toString().replaceAll("[^\\d]", ""); // Extraer solo números
int distancia = distanciaStr.isEmpty() ? 0 : Integer.parseInt(distanciaStr);

presenter.searchWithCoordinates(longitud, latitud, distancia);
} catch (NumberFormatException e) {
// Manejar casos donde no se pueda convertir
System.err.println("Error: Entrada no válida.");
}
}

/**
* @see IMainContract.View#updateMunicipiosSpinner(List municipios)
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ public class Gasolinera {
@SerializedName("Municipio") protected String municipio;
@SerializedName("Provincia") protected String provincia;
@SerializedName("Horario") protected String horario;
@SerializedName("Latitud") protected String latitud;
@SerializedName("Longitud (WGS84)") protected String longitud;

@SerializedName("Precio Gasoleo A") protected double gasoleoA;
@SerializedName("Precio Gasolina 95 E5") protected double gasolina95E5;
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified AndroidProject/app/src/main/res/drawable/sort.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="top|center">

<EditText
android:id="@+id/etLatitud"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:gravity="center"
android:hint="Latitud"
android:inputType="number|numberDecimal|numberSigned"
android:maxLength="8" />

<EditText
android:id="@+id/etLongitud"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="60dp"
android:gravity="center"
android:hint="Longitud"
android:inputType="number|numberDecimal|numberSigned"
android:maxLength="8" />

<TextView
android:id="@+id/tvDistancia"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:text="0" />

<LinearLayout
android:layout_width="wrap_content"
android:layout_height= "wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="0" />

<com.google.android.material.slider.Slider
android:id="@+id/main_slider"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:stepSize="1.0"
android:valueFrom="0"
android:valueTo="100" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="100"
android:textSize="20sp" />

</LinearLayout>

</LinearLayout>
6 changes: 6 additions & 0 deletions AndroidProject/app/src/main/res/menu/menu.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
android:id="@+id/menuCoordenadasButton"
android:icon="@drawable/ay_lupita"
android:title="Coordenadas"
app:showAsAction="always"/>
<item
android:id="@+id/menuOrdenButton"
android:icon="@drawable/sort"
Expand Down
4 changes: 4 additions & 0 deletions AndroidProject/app/src/main/res/values/arrays.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="initial_slider_values" />
</resources>
1 change: 1 addition & 0 deletions AndroidProject/app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
<string name="loadCorrect">Se han cargado %d gasolineras</string>
<string name="loadError">Ha habido un error cargando las gasolineras</string>
<string name="info_text">Aplicación creada para el Proyecto Integrado Curso 2024-2025</string>
<string name="slider_desc" />
<string name="selecciona_combustibles">Selecciona combustibles</string>
<string name="precio_gasolina">Precio Gasolina:</string>
<string name="precio_diesel">Precio Diesel:</string>
Expand Down

0 comments on commit 086b1e0

Please sign in to comment.