October 28, 2024
Chicago 12, Melborne City, USA
java

Firestore collection rearrange and API adjustment


i am trying to change the firestore structure from this:

Root: events/{selectedSport}/leagues/{selectedLeague}/seasons/{selectedSeason}/matchdays/{idEvent} (idEvent, strEvent, strSeason, dateEvent, strTime, idHomeTeam, idAwayTeam, strHomeTeam, strAwayTeam, intHomeScore, intAwayScore, strVenue, strStatus, strPostponed, strThumb, strVideo)

to this

Root: events/{LeagueName: league name, selectedLeagueId}/seasons/{SeasonName: seasonID}/matchdays/{Matchday: matchdayID}/matches/{Match: matchID} (idEvent, strEvent, strSeason, dateEvent, strTime, idHomeTeam, idAwayTeam, strHomeTeam, strAwayTeam, intHomeScore, intAwayScore, strVenue, strStatus, strPostponed, strThumb, strVideo, order of arrival)`

but API from https://www.thesportsdb.com/ does not call matchday. But to make a matchday I want to add strMatchday as an additional parameter in my API call, assuming TheSportsDB API endpoint supports filtering by matchday. This isn’t always standard, but you can add it to this:

String url = "https://www.thesportsdb.com/api/v1/json/xxx/eventsseason.php?id=" 
             + selectedLeagueId + "&s=" + season + "&round=" + strMatchday;

therefore I got a call "Event"

public class Event {
    private String sport;
    private String league;
    private String season;
    private String matchday;

from the below java

// Default constructor required for Firestore
public Event() {}

public Event(String sport, String league, String season, String matchday) {
    this.sport = sport;
    this.league = league;
    this.season = season;
    this.matchday = matchday;
}

public String getSport() {
    return sport;
}

public void setSport(String sport) {
    this.sport = sport;
}

public String getLeague() {
    return league;
}

public void setLeague(String league) {
    this.league = league;
}

public String getSeason() {
    return season;
}

public void setSeason(String season) {
    this.season = season;
}

public String getMatchday() {
    return matchday;
}

public void setMatchday(String matchday) {
    this.matchday = matchday;
}

}

and this is the code I currently have that needs to be modified as per the beginning of the question. are you able to help?

import android.os.Bundle;
import android.util.Log;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.Request;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

import com.google.firebase.firestore.FirebaseFirestore;


public class PullingActivity extends AppCompatActivity {

    private Spinner spinnerSports;
    private Spinner spinnerLeagues;
    private Spinner spinnerSeasons;
    private Button btnConfirmLeague;
    private Button btnFetchData;


    private FirebaseFirestore db;

    private ArrayList<String> sportsList = new ArrayList<>();
    private ArrayList<String> leaguesList = new ArrayList<>();
    private ArrayList<String> filteredLeaguesList = new ArrayList<>();
    private ArrayList<String> seasonsList = new ArrayList<>();
    private ArrayList<String> leagueIDsList = new ArrayList<>();

    private static final String TAG = "PullingActivity";
    private static final String BASE_URL = "https://www.thesportsdb.com/api/v1/json/xxx/";

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

        spinnerSports = findViewById(R.id.spinner_sports);
        spinnerLeagues = findViewById(R.id.spinner_leagues);
        spinnerSeasons = findViewById(R.id.spinner_seasons);
        btnConfirmLeague = findViewById(R.id.btn_confirm_league);
        btnFetchData = findViewById(R.id.btn_fetch_data);


        // Initialize Firebase Firestore
        db = FirebaseFirestore.getInstance();
        if (db == null) {
            Toast.makeText(this, "Failed to initialize Firebase Firestore", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "Firebase Firestore instance is null.");
            return; // Exit the onCreate method if Firestore initialization failed
        }


        loadSports();

        // Fetch data button action
        btnFetchData.setOnClickListener(v -> {
            String selectedSport = (String) spinnerSports.getSelectedItem();
            String selectedLeague = (String) spinnerLeagues.getSelectedItem();
            String selectedSeason = (String) spinnerSeasons.getSelectedItem();
            String selectedLeagueID = leagueIDsList.get(spinnerLeagues.getSelectedItemPosition());

            if (selectedSport != null && selectedLeague != null && selectedSeason != null) {
                fetchEvents(selectedLeagueID, selectedSeason);
            } else {
                Toast.makeText(PullingActivity.this, "Please select sport, league, and season first", Toast.LENGTH_SHORT).show();
            }
        });


        spinnerSports.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, android.view.View view, int position, long id) {
                String selectedSport = sportsList.get(position);
                loadLeagues(selectedSport);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });

        btnConfirmLeague.setOnClickListener(v -> {
            int selectedLeaguePosition = spinnerLeagues.getSelectedItemPosition();
            if (selectedLeaguePosition >= 0) {
                String selectedLeagueID = leagueIDsList.get(selectedLeaguePosition);
                Log.d(TAG, "Selected League ID: " + selectedLeagueID); // Log selected league ID
                loadSeasons(selectedLeagueID); // Pass the league ID to loadSeasons
            } else {
                Toast.makeText(PullingActivity.this, "Please select a league first", Toast.LENGTH_SHORT).show();
            }
        });
    }



    private void loadSports() {
        String url = BASE_URL + "all_sports.php";

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                response -> {
                    try {
                        JSONArray sportsArray = response.getJSONArray("sports");
                        for (int i = 0; i < sportsArray.length(); i++) {
                            JSONObject sport = sportsArray.getJSONObject(i);
                            String sportName = sport.getString("strSport");
                            sportsList.add(sportName);
                        }
                        ArrayAdapter<String> adapter = new ArrayAdapter<>(PullingActivity.this,
                                android.R.layout.simple_spinner_item, sportsList);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinnerSports.setAdapter(adapter);
                    } catch (JSONException e) {
                        Toast.makeText(PullingActivity.this, "Error loading sports", Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "JSON parsing error in loadSports: ", e);
                    }
                }, error -> {
            Toast.makeText(PullingActivity.this, "Network Error in loadSports", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "Volley error in loadSports: ", error);
        });

        Volley.newRequestQueue(this).add(jsonObjectRequest);
    }

    private void loadLeagues(String sport) {
        leaguesList.clear();
        filteredLeaguesList.clear();
        leagueIDsList.clear();
        String url = BASE_URL + "all_leagues.php";

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                response -> {
                    try {
                        JSONArray leaguesArray = response.getJSONArray("leagues");
                        for (int i = 0; i < leaguesArray.length(); i++) {
                            JSONObject league = leaguesArray.getJSONObject(i);
                            if (league.has("strSport") && league.getString("strSport").equals(sport)) {
                                String leagueName = league.getString("strLeague");
                                String leagueID = league.getString("idLeague");

                                leaguesList.add(leagueName);
                                filteredLeaguesList.add(leagueName);
                                leagueIDsList.add(leagueID); // Store the league ID
                                Log.d(TAG, "Added League: " + leagueName + " with ID: " + leagueID);
                            }
                        }
                        ArrayAdapter<String> adapter = new ArrayAdapter<>(PullingActivity.this,
                                android.R.layout.simple_spinner_item, leaguesList);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        spinnerLeagues.setAdapter(adapter);
                    } catch (JSONException e) {
                        Toast.makeText(PullingActivity.this, "Error loading leagues", Toast.LENGTH_SHORT).show();
                        Log.e(TAG, "JSON parsing error in loadLeagues: ", e);
                    }
                }, error -> {
            Toast.makeText(PullingActivity.this, "Network Error in loadLeagues", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "Volley error in loadLeagues: ", error);
        }
        );

        Volley.newRequestQueue(this).add(jsonObjectRequest);
    }

    private void loadSeasons(String leagueID) {
        seasonsList.clear();
        String url = BASE_URL + "search_all_seasons.php?id=" + leagueID;

        Log.d(TAG, "Fetching seasons from URL: " + url); // Log the URL being requested

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                response -> {
                    Log.d(TAG, "Seasons API Response: " + response.toString()); // Log the full response

                    try {
                        if (response.has("seasons") && response.get("seasons") instanceof JSONArray) {
                            JSONArray seasonsArray = response.getJSONArray("seasons");
                            if (seasonsArray.length() == 0) {
                                Log.w(TAG, "No seasons found for league ID: " + leagueID);
                                Toast.makeText(PullingActivity.this, "No seasons available for the selected league", Toast.LENGTH_SHORT).show();
                            } else {
                                for (int i = 0; i < seasonsArray.length(); i++) {
                                    JSONObject season = seasonsArray.getJSONObject(i);
                                    String seasonName = season.getString("strSeason");
                                    seasonsList.add(seasonName);
                                }
                                ArrayAdapter<String> adapter = new ArrayAdapter<>(PullingActivity.this,
                                        android.R.layout.simple_spinner_item, seasonsList);
                                adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                                spinnerSeasons.setAdapter(adapter);
                            }
                        } else {
                            Log.e(TAG, "Invalid or unexpected seasons array for league ID: " + leagueID);
                            Toast.makeText(PullingActivity.this, "No seasons available for the selected league", Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, "JSON parsing error in loadSeasons: ", e);
                        Toast.makeText(PullingActivity.this, "Error loading seasons", Toast.LENGTH_SHORT).show();
                    }
                }, error -> {
            Log.e(TAG, "Network error in loadSeasons: ", error);
            Toast.makeText(PullingActivity.this, "Network Error in loadSeasons", Toast.LENGTH_SHORT).show();
        }
        );

        Volley.newRequestQueue(this).add(jsonObjectRequest);
    }


    private void fetchEvents(String leagueID, String season) {
        String url = BASE_URL + "eventsseason.php?id=" + leagueID + "&s=" + season;

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                response -> {
                    try {
                        JSONArray eventsArray = response.getJSONArray("events");
                        for (int i = 0; i < eventsArray.length(); i++) {
                            JSONObject event = eventsArray.getJSONObject(i);

                            // Parse the fields
                            String idEvent = event.optString("idEvent");
                            String strEvent = event.optString("strEvent");
                            String strSeason = event.optString("strSeason");
                            String dateEvent = event.optString("dateEvent");
                            String strTime = event.optString("strTime");
                            String idHomeTeam = event.optString("idHomeTeam");
                            String idAwayTeam = event.optString("idAwayTeam");
                            String strHomeTeam = event.optString("strHomeTeam");
                            String strAwayTeam = event.optString("strAwayTeam");
                            String intHomeScore = event.optString("intHomeScore");
                            String intAwayScore = event.optString("intAwayScore");
                            String strVenue = event.optString("strVenue");
                            String strStatus = event.optString("strStatus");
                            String strPostponed = event.optString("strPostponed");
                            String strThumb = event.optString("strThumb");
                            String strVideo = event.optString("strVideo");

                            // Create a map for the event data
                            HashMap<String, Object> eventMap = new HashMap<>();
                            eventMap.put("idEvent", idEvent);
                            eventMap.put("strEvent", strEvent);
                            eventMap.put("strSeason", strSeason);
                            eventMap.put("dateEvent", dateEvent);
                            eventMap.put("strTime", strTime);
                            eventMap.put("idHomeTeam", idHomeTeam);
                            eventMap.put("idAwayTeam", idAwayTeam);
                            eventMap.put("strHomeTeam", strHomeTeam);
                            eventMap.put("strAwayTeam", strAwayTeam);
                            eventMap.put("intHomeScore", intHomeScore);
                            eventMap.put("intAwayScore", intAwayScore);
                            eventMap.put("strVenue", strVenue);
                            eventMap.put("strStatus", strStatus);
                            eventMap.put("strPostponed", strPostponed);
                            eventMap.put("strThumb", strThumb);
                            eventMap.put("strVideo", strVideo);

                            // Store event in Firestore under the appropriate path
                            String selectedSport = (String) spinnerSports.getSelectedItem(); // Get the selected sport's name
                            String selectedLeague = (String) spinnerLeagues.getSelectedItem(); // Get the selected league's name

                            db.collection("events").document(selectedSport)
                                    .collection("leagues").document(selectedLeague)
                                    .collection("seasons").document(season)
                                    .collection("matchdays")
                                    .document(idEvent) // Use unique ID to avoid overwriting
                                    .set(eventMap) // Store the event data
                                    .addOnSuccessListener(aVoid ->
                                            Log.d(TAG, "Event saved successfully"))
                                    .addOnFailureListener(e ->
                                            Log.e(TAG, "Error saving event data", e));
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, "JSON parsing error in fetchEvents: ", e);
                    }
                }, error -> {
            Log.e(TAG, "Network error in fetchEvents: ", error);
        }
        );

        Volley.newRequestQueue(this).add(jsonObjectRequest);
    }




}

I change the API key with "xxx" for protection.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video