Передача элементов ArrayList в метод привязки данных Android Java - PullRequest
0 голосов
/ 26 апреля 2020

У меня есть метод вычисления значений с использованием объектов, хранящихся в ArrayList. Используется текущий элемент и следующий элемент. Затем я использую другой метод, используя результат этого первого метода. Это работает, как и ожидалось, но мне нужно установить результат на расстояние TextView в planner_item. xml, который использует привязку данных. Но я не уверен, как это реализовать, поскольку мне нужно использовать оба метода, а также передавать ArrayList в xml.

Метод

public double calculateDistance(double lat1, double lat2, double lon1, double lon2) {
        lon1 = Math.toRadians(lon1);
        lon2 = Math.toRadians(lon2);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);

        double dlon = lon2 - lon1;
        double dlat = lat2 - lat1;
        double a = Math.pow(Math.sin(dlat / 2), 2)
                + Math.cos(lat1) * Math.cos(lat2)
                * Math.pow(Math.sin(dlon / 2), 2);

        double c = 2 * Math.asin(Math.sqrt(a));

        double r = 3963;

        return (c * r);
    }

    public void calculateTime(double distance) {
        double hours = distance / 3;
        int hours2 = (int) hours;
        double minutes = hours * 60;
        int minutes2 = (int) minutes;
        System.out.println("Distance: " + formatter.format(distance) + " Miles");
        System.out.println("Hours: " + hours2 + " Minutes: " + minutes2);
    }

Используя метод

double lat1 = cities.get(i).getCoordinates().getLat();
double lat2 = cities.get(i + 1).getCoordinates().getLat();
double long1 = cities.get(i).getCoordinates().getLng();
double long2 = cities.get(i).getCoordinates().getLng();

distance = calculateDistance(lat1, lat2, long1, long2);
calculateTime(distance);

PlannerResultsFragment. java

public class PlannerResultsFragment extends Fragment {

    private PlannerAdapter plannerAdapter = new PlannerAdapter();
    FragmentPlannerResultsBinding fragmentPlannerResultsBinding;
    private ArrayList<Country> cities = new ArrayList<>();
    private MutableLiveData<List<List<Country>>> mutableLiveData = new MutableLiveData<>();
    private View view;

    ArrayList<Country> updatedList = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        fragmentPlannerResultsBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_planner_results, container, false);

        view = inflater.inflate(R.layout.fragment_planner_results, container, false);

        getAllCities();
        setUpRecyclerView();

        return fragmentPlannerResultsBinding.getRoot();
    }

    private void getAllCities() {
        getPopularCountries().observe(getViewLifecycleOwner(), new Observer<List<List<Country>>>() {
            @Override
            public void onChanged(@Nullable List<List<Country>> cities) {
                plannerAdapter.setCityList(cities);
            }
        });
    }

    public LiveData<List<List<Country>>> getPopularCountries() {
        return getMutableCountryLiveData();
    }

    public MutableLiveData<List<List<Country>>> getMutableCountryLiveData() {
        final TriposoAPI userDataService = RetrofitClient.getService();
        Call<InitialResponse> call = userDataService.getPlannerResults(city_input, persona, count);
        call.enqueue(new Callback<InitialResponse>() {
            @Override
            public void onResponse(Call<InitialResponse> call, Response<InitialResponse> response) {
                InitialResponse cityResponse = response.body();
                if (cityResponse != null && cityResponse.getResults() != null) {
                    cities = (ArrayList<Country>) cityResponse.getResults();


                    for(int i = 0; i < cities.size(); i++) {
                        double lat1 = cities.get(i).getCoordinates().getLat();
                        double lat2 = cities.get(i + 1).getCoordinates().getLat();
                        double long1 = cities.get(i).getCoordinates().getLng();
                        double long2 = cities.get(i).getCoordinates().getLng();

                        distance = calculateDistance(lat1, lat2, long1, long2);
                        calculateTime(distance);
                        System.out.println(cities.get(i));
                    }

                    setUpButton();

                    mutableLiveData.setValue(partitions);

                }

            }

            @Override
            public void onFailure(Call<InitialResponse> call, Throwable t) {
            }
        });
        return mutableLiveData;
    }

    private void setUpRecyclerView() {
        RecyclerView recyclerView = fragmentPlannerResultsBinding.viewCities;
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        recyclerView.setAdapter(plannerAdapter);
    }

    private void setUpButton() {
        RecyclerView recyclerView = fragmentPlannerResultsBinding.plannerDay;
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        PlannerDayAdapter adapter = new PlannerDayAdapter(days);
        recyclerView.setAdapter(adapter);
    }

    public double calculateDistance(double lat1, double lat2, double lon1, double lon2) {
        lon1 = Math.toRadians(lon1);
        lon2 = Math.toRadians(lon2);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);

        double dlon = lon2 - lon1;
        double dlat = lat2 - lat1;
        double a = Math.pow(Math.sin(dlat / 2), 2)
                + Math.cos(lat1) * Math.cos(lat2)
                * Math.pow(Math.sin(dlon / 2), 2);

        double c = 2 * Math.asin(Math.sqrt(a));

        double r = 3963;

        return (c * r);
    }

    public void calculateTime(double distance) {
        double hours = distance / 3;
        int hours2 = (int) hours;
        double minutes = hours * 60;
        int minutes2 = (int) minutes;
        System.out.println("Distance: " + formatter.format(distance) + " Miles");
        System.out.println("Minutes: " + minutes2);
    }


}

PlannerAdapter. java

public class PlannerAdapter extends RecyclerView.Adapter<PlannerAdapter.MyViewHolder> {

    private List<List<Country>> cities;
    private Integer position;
    private static PlannerAdapter instance;
    private View view;

    public void setPosition(int position) {
        this.position = position;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {

        PlannerItemBinding plannerItemBinding =
                DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()), R.layout.planner_item, viewGroup, false);

        view = viewGroup;

        instance = this;

        return new MyViewHolder(plannerItemBinding);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int i) {
        if (position == null){
            position = 0;
        }

        try {
            myViewHolder.bindTo(cities.get(position).get(i));

        }
        catch (IndexOutOfBoundsException e){
            e.printStackTrace();
        }
        myViewHolder.plannerItemBinding.setItemClickListener(this);

    }

    @Override
    public int getItemCount() {
        if (cities != null) {
            return cities.get(0).size();
        } else {
            return 0;
        }
    }

    public void setCityList(List<List<Country>> cities) {
        this.cities = cities;
        notifyDataSetChanged();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        private PlannerItemBinding plannerItemBinding;

        public MyViewHolder(@NonNull PlannerItemBinding plannerItemBinding) {
            super(plannerItemBinding.getRoot());

            this.plannerItemBinding = plannerItemBinding;

        }

        void bindTo(Country country) {
            plannerItemBinding.setVariable(com.example.planner.BR.city, country);
            plannerItemBinding.setVariable(com.example.planner.BR.adapterPosition, getLayoutPosition());
            plannerItemBinding.setVariable(com.example.planner.BR.countryImageMedium, country.getImages().get(0).getSizes().getMedium());
            plannerItemBinding.executePendingBindings();

        }
    }

    public static PlannerAdapter getInstance() {
        return instance;
    }


    }

}

planner_item. xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:bind="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/tools">
    <data>
        <variable
            name="city"
            type="com.example.planner.model.remote.country.Country"/>
        <variable
            name="itemClickListener"
            type="com.example.planner.CustomClickListener" />
        <variable
        name="adapterPosition"
        type="Integer" />

    </data>


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            >

            <androidx.cardview.widget.CardView
                android:id="@+id/city"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:layout_margin="5dp"
                android:onClick="@{() -> itemClickListener.cardClicked(city)}"
                >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:onClick="@{() -> itemClickListener.cardClicked(city)}"
                    android:id="@+id/card"
                    >
                    <FrameLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:layout_margin="8dp">

                    </FrameLayout>
                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:layout_marginStart="8dp"
                        android:layout_marginBottom="8dp">
                        <RelativeLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content">
                            <TextView
                                android:id="@+id/cityName"
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="@{city.name}"
                                android:textStyle="bold"
                                android:textSize="18sp"
                                android:textColor="@color/black"
                                android:layout_alignParentLeft="true"
                                />



                        </RelativeLayout>
                        <TextView
                            android:id="@+id/citySnippet"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:padding="4dp"
                            android:textColor="@color/black"
                            android:text="@{city.snippet}"
                            android:textSize="16sp"
                            />
                    </LinearLayout>
                </LinearLayout>
            </androidx.cardview.widget.CardView>
            <TextView
                android:id="@+id/distance"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="4dp"
                android:textColor="@color/black"
                android:textSize="16sp"
                />
        </LinearLayout>


</layout>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...