How to use livedata location result in another livedata web request?

I´m using two different livedata classes. One of these is a livedata location class and the other one is a livedata class which do a server request. First of all both work perfect and I got the location as a result and the web request as a result which is also displayed in a recyclerview.

My problem is that the server request need params which include the location of the user. I want to use the latitude and longitude I receive from my location livedata and use them in livedata class where I do the server request.

I got a server request and a location also in the onchange methods and tried to use the longitude and latitude values of the location in a method of my live data which do the server request but on this way it couldn´t do the server request cause the values are null when it start. Im also struggling how my livedata noticed when the database change. I don´t know how to trigger the live data to do a new server request and got new data if the database changed.

My Fragment where I got the livedata and reuse them:

public class Home_Fragment_All extends Fragment implements LifecycleOwner {
LinearLayoutManager linearLayoutManager;
private static final String TAG = "Home_Fragment";
BottomNavigationView bottomNav;
private int scrolledDistance = 0;
private static final int HIDE_THRESHOLD = 1;
private boolean controlsVisible = true;
EventHolder eventHolder=new EventHolder();
Home_Fragment_All context;
newLiveData viewModel;
public RecyclerView recyclerView;
Recyclerheader recyclerViewAdapter;
Fragment active=this;
String Account;




@Override
public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,
                         @NotNull Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_home_all, container, false);


    Log.d(TAG, "onCreateView: createview");
    // Inflate the layout for this fragment
    context=this;
    viewModel = ViewModelProviders.of(context).get(newLiveData.class);
    viewModel.getLocation().observe(this.getViewLifecycleOwner(), LocationObserver);
    viewModel.getData().observe(this.getViewLifecycleOwner(), userListUpdateObserver);
    linearLayoutManager = new LinearLayoutManager(getActivity());
    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    bottomNav=((MainActivity) requireActivity()).findViewById(R.id.navigation);
    //Configuration Button
    Button configuration_button = view.findViewById(R.id.configuration_button);
    configuration_button.setOnClickListener(view1 -> openDialog());
    Button button = view.findViewById(R.id.menu_button);
    button.setOnClickListener(v -> ((MainActivity) getActivity()).hamMenu(view));
    recyclerView = view.findViewById(R.id.recyclerview);
    recyclerView.setNestedScrollingEnabled(true);
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NotNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }
        @Override
        public void onScrolled(@NotNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            scrolledDistance = dy;
            if (scrolledDistance > HIDE_THRESHOLD && controlsVisible) {
                hideViews();
                controlsVisible = false;
            } else if (scrolledDistance < -HIDE_THRESHOLD && !controlsVisible) {
                showViews();
                controlsVisible = true;
            }
        }
    });
    return view;
}
Observer<ArrayList<Data>> userListUpdateObserver = new Observer<ArrayList<Data>>() {
    @Override
    public void onChanged(ArrayList<Data> DATA) {
        recyclerViewAdapter = new Recyclerheader(getContext(), DATA, new OnClickListenerEvent() {
            @Override
            public void respond(int position, String EventName, String Location, String Eventhost, String Genre, String Artist, String City, String Adress, String Information, String Date, String StartTime, String EndTime, String Price) {

                Bundle bundle=new Bundle();
                bundle.putString("name", Name);
                bundle.putString("Event", Location);
                bundle.putString("host",host);
                bundle.putString("Genre",Genre);
                bundle.putString("Artist",Artist);
                bundle.putString("City",City);
                bundle.putString("Adress",Adress);
                bundle.putString("Information",Information);
                bundle.putString("Date",Date);
                bundle.putString("StartTime",StartTime);
                bundle.putString("EndTime",EndTime);
                bundle.putString("Price",Price);
                eventHolder.setArguments(bundle);
                FragmentTransaction transaction= requireActivity().getSupportFragmentManager().beginTransaction();
                bottomNav=((MainActivity) requireActivity()).findViewById(R.id.navigation);
                ((MainActivity) requireActivity()).hideBottomNavigationView(bottomNav);
                requireActivity().getSupportFragmentManager().beginTransaction().add(R.id.main_container, eventHolder, "4").hide(eventHolder).addToBackStack("4").commit();
                transaction.setCustomAnimations( R.animator.fragmentsliderightout,R.animator.leftslideout,
                        R.animator.leftslidein,R.animator.fragementslideinright).hide(active).show(eventHolder).addToBackStack("4").commit();
                active = eventHolder;

            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setAdapter(recyclerViewAdapter);
        recyclerViewAdapter.notifyDataSetChanged();
    }
};
private void openDialog()
{
    Config_Fragment.display(getActivity().getSupportFragmentManager());
}
private void hideViews() {
   bottomNav.animate().translationY(bottomNav.getHeight()).setInterpolator(new AccelerateInterpolator(2));
}
private void showViews() {
    bottomNav.animate().translationY(0).setInterpolator(new DecelerateInterpolator(2));
}
@Override
public void onResume() {
    new MainActivity().showBottomNavigationView(bottomNav);
    super.onResume();
}

        Observer<Location> LocationObserver = new Observer<Location>() {
        @Override
        public void onChanged(@Nullable Location location) {
            Log.d(TAG, "onChanged: location updated " + location);
            String lat1= String.valueOf(location.getLatitude());
            String lng1= String.valueOf(location.getLongitude());
            String Account=getGE.getEmail(getContext());
            Log.d(TAG, "onChanged: "+lat1+lng1);
            LiveDataEvents liveDataEvents=new LiveDataEvents(getContext());
            liveDataEvents.getLocationData(lat1,lng1,Account);
        Log.d(TAG, "onChanged: worked?");
        viewModel.getData().observe(context.getViewLifecycleOwner(), userListUpdateObserver);

        }
};
}

My ViewModel:

public class newLiveData extends AndroidViewModel {
    private final LiveDataEvents data;
    LocationLiveData locationLiveData;

    public newLiveData(Application application) {
        super(application);
        data = new LiveDataEvents(application);
        locationLiveData= new LocationLiveData(application);
    }
    public LiveData<ArrayList<Data>> getData() {
        return data;
    }

    public LocationLiveData getLocation(){
        return locationLiveData;
    }
}

My LiveData for Serverrequest:

public class LiveDataEvents extends LiveData<ArrayList<Data>> {
private final Context context;
private final FileObserver fileObserver;
ArrayList<Data> DATA;
String lat1;
String lng1;
String Account;

public void getLocationData(String lat, String lng, String account){
    lat1=lat;
    lng1=lng;
    Account=account;
}


public LiveDataEvents(Context context) {
    this.context = context;
    String path = new File(context.getFilesDir(),
            Config.URL_ADD).getPath();
    fileObserver = new FileObserver(path) {
        @Override
        public void onEvent(int event, String path) {
            // The file has changed, so let’s reload the data
            loadData();
        }
    };
    loadData();

}
@Override
protected void onActive() {
    fileObserver.startWatching();
}
@Override
protected void onInactive() {
    fileObserver.stopWatching();
}

public void loadData() {
    StringRequest request = new StringRequest(Request.Method.POST, Config.URL_ADD, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            DATA=new ArrayList<>();
            try {
                JSONArray responsearray = new JSONArray(response);
                //Populate the EmployeeDetails list from response
                for (int i = 0; i < responsearray.length(); i++) {
                    JSONObject event = responsearray.getJSONObject(i);
                    Data events = new Data();
                    events.setId(event.getInt("ID"));
                    events.setName(event.getString("name"));
                    events.setEvent(event.getString("Event"));
                    events.setHost(event.getString("host"));
                    events.setGENRE(event.getString("Genre"));
                    events.setArt(event.getString("Art"));
                    events.setArtist(event.getString("Artist"));
                    events.setFloor(event.getString("Floor"));
                    events.setInformation(event.getString("Information"));
                    events.setDATE(event.getString("Date"));
                    events.setCITY(event.getString("City"));
                    events.setAdress(event.getString("Adress"));
                    events.setStartTIME(event.getString("StartTime"));
                    events.setEndTIME(event.getString("EndTime"));
                    events.setPRICE(event.getString("Price"));
                    events.setUserLikedState(event.getInt("State"));
                    events.setId(event.getInt("Likes"));
                    DATA.add(events);
                }
                setValue(DATA);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {

            HashMap<String,String> params = new HashMap<>();
            params.put(Config.KEY_EMP_LAT,lat1 );
            params.put(Config.KEY_EMP_LNG, lng1);
            params.put(Config.KEY_UserEmail, Account);
            return params;
        }
    };
    request.setRetryPolicy(new DefaultRetryPolicy(30000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    MySingelton.getmInstance(context).addToRequestQueue(request);
}
}

My Location LiveData:

   private LocationManager locationManager;
private Context context;

public LocationLiveData(Context context) {
    this.context = context;
    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}

private LocationListener locationListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        setValue(location);
    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
};

@Override
protected void onActive() {
    super.onActive();
    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, 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;
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}

@Override
protected void onInactive() {
    super.onInactive();
    locationManager.removeUpdates(locationListener);
}
}


Read more here: https://stackoverflow.com/questions/66280531/how-to-use-livedata-location-result-in-another-livedata-web-request

Content Attribution

This content was originally published by jayjohn at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: