Search in sources :

Example 41 with CollectionReference

use of com.google.firebase.firestore.CollectionReference in project QR-Game by CMPUT301W22T15.

the class NewUser method createUser.

/**
 * This method is called when the user taps the Create Account button, and it opens the user menu activity
 * if a new user successfully signs up.
 * @param view
 * Expects an object from the View class.
 */
public void createUser(View view) {
    // Obtain variables
    String username = usernameEdit.getText().toString();
    String name = nameEdit.getText().toString();
    String email = emailEdit.getText().toString();
    String cityRegion = cityEdit.getText().toString();
    FirebaseFirestore db;
    // Access a Cloud FireStore instance from Activity
    db = FirebaseFirestore.getInstance();
    SingletonPlayer singletonPlayer = new SingletonPlayer();
    final CollectionReference collectionReference = db.collection("Players");
    singletonPlayer.player = new Player(username, email);
    singletonPlayer.player.setName(name);
    singletonPlayer.player.setRegion(cityRegion);
    if (username.equals("gaethje")) {
        singletonPlayer.player.setOwner(true);
        collectionReference.document(username).set(SingletonPlayer.player).addOnSuccessListener(new OnSuccessListener<Void>() {

            @Override
            public void onSuccess(Void unused) {
                Intent intent = new Intent(getApplicationContext(), OwnerMenu.class);
                startActivity(intent);
            }
        }).addOnFailureListener(new OnFailureListener() {

            @Override
            public void onFailure(@NonNull Exception e) {
            }
        });
    } else {
        // check if username is unique
        DocumentReference playerDocRef = db.collection("Players").document(username);
        playerDocRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {

            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot documentSnapshot = task.getResult();
                    if (documentSnapshot.exists()) {
                        // player already exist
                        Toast.makeText(NewUser.this, "Username already exist", Toast.LENGTH_SHORT).show();
                    } else {
                        // player dont exist
                        // set the player in firebase
                        collectionReference.document(username).set(SingletonPlayer.player).addOnSuccessListener(new OnSuccessListener<Void>() {

                            @Override
                            public void onSuccess(Void unused) {
                                Intent intent = new Intent(getApplicationContext(), UserMenu.class);
                                intent.putExtra("userMenu_act", username);
                                startActivity(intent);
                            }
                        }).addOnFailureListener(new OnFailureListener() {

                            @Override
                            public void onFailure(@NonNull Exception e) {
                            }
                        });
                    }
                }
            }
        });
    }
}
Also used : FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) Intent(android.content.Intent) CollectionReference(com.google.firebase.firestore.CollectionReference) DocumentSnapshot(com.google.firebase.firestore.DocumentSnapshot) NonNull(androidx.annotation.NonNull) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) OnFailureListener(com.google.android.gms.tasks.OnFailureListener) DocumentReference(com.google.firebase.firestore.DocumentReference)

Example 42 with CollectionReference

use of com.google.firebase.firestore.CollectionReference in project QR-Game by CMPUT301W22T15.

the class OtherPlayers method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_other_players);
    // fetch all the document to display them on listview
    db = FirebaseFirestore.getInstance();
    final CollectionReference collectionReference = db.collection("Players");
    // Prepare ListView and Adapter
    playerList = findViewById(R.id.otherPlayerListview);
    allPlayers = new ArrayList<>();
    playerAdapter = new OtherPlayerListAdapter(this, R.layout.other_player_listview_item, allPlayers);
    playerList.setAdapter(playerAdapter);
    collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() {

        @Override
        public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException error) {
            allPlayers.clear();
            for (QueryDocumentSnapshot doc : queryDocumentSnapshots) {
                Player p = doc.toObject(Player.class);
                if (!p.getPlayerHash().equals(singletonPlayer.player.getPlayerHash()) && !p.getOwner()) {
                    allPlayers.add(p);
                }
            }
            playerAdapter.notifyDataSetChanged();
        }
    });
    // Be able to view a profile if we click a user
    playerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            Player clickedPLayer = allPlayers.get(position);
            String playerUserName = clickedPLayer.getUsername();
            String playerHash = clickedPLayer.getPlayerHash();
            Intent intent = new Intent(OtherPlayers.this, OtherPlayerProfile.class);
            intent.putExtra("playerUserName", playerUserName);
            intent.putExtra("playerHash", playerHash);
            startActivity(intent);
        }
    });
    // Be able to search for a player
    Button searchConfirmButton = findViewById(R.id.searchConfirmButton);
    searchConfirmButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // TODO: could cause error when playerlist updates in DB while trying to do this.
            EditText searchbox = findViewById(R.id.searchPlayerEditText);
            String searchedPlayerName = searchbox.getText().toString();
            // TRIM WHITESPACES, IMPORTANT
            searchedPlayerName = searchedPlayerName.trim();
            boolean exist = false;
            // check if entered user exist
            for (int i = 0; i < allPlayers.size(); i++) {
                String thisplayerUsername = allPlayers.get(i).getUsername();
                if (thisplayerUsername.trim().equals(searchedPlayerName)) {
                    // case: if found
                    // go to activity
                    exist = true;
                    searchbox.setText("");
                    String playerHash = allPlayers.get(i).getPlayerHash();
                    Intent intent = new Intent(OtherPlayers.this, OtherPlayerProfile.class);
                    intent.putExtra("playerUserName", thisplayerUsername);
                    intent.putExtra("playerHash", playerHash);
                    startActivity(intent);
                // since startActivity is asynchronous call, i needed to use "exist" loic to toast
                }
            }
            // case: invalid userName
            if (!exist) {
                Toast.makeText(OtherPlayers.this, "Username Don't exist", Toast.LENGTH_SHORT).show();
            }
            searchbox.setText("");
        }
    });
    // Be able to scan a button to search for a user
    Button scanCodeButton = findViewById(R.id.scan_player_code);
    scanCodeButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(OtherPlayers.this, ScannerView2.class);
            intent.putExtra("scanProfileCode", true);
            startActivity(intent);
        }
    });
}
Also used : EditText(android.widget.EditText) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) FirebaseFirestoreException(com.google.firebase.firestore.FirebaseFirestoreException) Intent(android.content.Intent) View(android.view.View) AdapterView(android.widget.AdapterView) ListView(android.widget.ListView) CollectionReference(com.google.firebase.firestore.CollectionReference) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) Button(android.widget.Button) AdapterView(android.widget.AdapterView)

Example 43 with CollectionReference

use of com.google.firebase.firestore.CollectionReference in project QR-Game by CMPUT301W22T15.

the class UserMenu method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_menu);
    // Initialize fusedLocationProviderClient--------------------------------------------------
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
    // TODO: set up location request
    locationRequest = LocationRequest.create().setPriority(// 
    LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationCallback = new LocationCallback() {

        @Override
        public void onLocationResult(LocationResult locationResult) {
            // here is the location
            Log.i("TAG", "incallback");
            if (locationResult == null) {
                Toast.makeText(UserMenu.this, "saved current location", Toast.LENGTH_SHORT).show();
                // deactivate callback so it doesn't loop.
                fusedLocationProviderClient.removeLocationUpdates(locationCallback);
                Toast.makeText(UserMenu.this, "null location", Toast.LENGTH_SHORT).show();
                return;
            }
            // got location.
            Location lastLocation = locationResult.getLastLocation();
            double lat = lastLocation.getLatitude();
            double lon = lastLocation.getLongitude();
            singletonPlayer.lat = lastLocation.getLatitude();
            singletonPlayer.lon = lastLocation.getLongitude();
            Toast.makeText(UserMenu.this, "lat " + lat + " lon " + lon, Toast.LENGTH_SHORT).show();
            fusedLocationProviderClient.removeLocationUpdates(locationCallback);
        }
    };
    db = FirebaseFirestore.getInstance();
    final CollectionReference collectionReference = db.collection("Players");
    menuList = findViewById(R.id.userMenu_list);
    String userName = singletonPlayer.player.getUsername();
    String[] dataList = new String[] { userName, "Scan New Code", "My Scans", "Ranking", "Codes Near Me", "Other Player", "set map spawn point here" };
    menuAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
    menuList.setAdapter(menuAdapter);
    menuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            if (position == 0) {
                Intent intent = new Intent(getApplicationContext(), PlayerProfile.class);
                startActivity(intent);
            } else if (position == 1) {
                Intent intent = new Intent(getApplicationContext(), ScannerView.class);
                startActivity(intent);
            } else if (position == 2) {
                Intent intent = new Intent(getApplicationContext(), MyScans.class);
                // intent.putExtra("scan_new_code", (String) null);
                startActivity(intent);
            } else if (position == 3) {
                Intent intent = new Intent(getApplicationContext(), PlayerRanking.class);
                startActivity(intent);
            } else if (position == 4) {
                // TODO: fetch player here?
                // EL-start
                Intent intent = new Intent(getApplicationContext(), GameMap.class);
                // intent.putExtra("Codes_Near_Me", (String) null);
                startActivity(intent);
            // EL-end
            } else if (position == 5) {
                Intent intent = new Intent(getApplicationContext(), OtherPlayers.class);
                startActivity(intent);
            } else if (position == 6) {
                // save player location
                Log.i("TAG0", "in 153");
                if (ActivityCompat.checkSelfPermission(UserMenu.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(UserMenu.this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    Log.i("TAG1", "in 7");
                    getLocation1();
                } else {
                    ActivityCompat.requestPermissions(UserMenu.this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, 44);
                }
            }
        }
    });
    // FOR the sore purpose to have all the players before going to Gamemap activity.
    collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() {

        @Override
        public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException error) {
            globalAllPlayers.allPlayers.clear();
            for (QueryDocumentSnapshot doc : queryDocumentSnapshots) {
                Player p = doc.toObject(Player.class);
                globalAllPlayers.allPlayers.add(p);
            }
        }
    });
}
Also used : QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) LocationCallback(com.google.android.gms.location.LocationCallback) Intent(android.content.Intent) FirebaseFirestoreException(com.google.firebase.firestore.FirebaseFirestoreException) View(android.view.View) AdapterView(android.widget.AdapterView) ListView(android.widget.ListView) CollectionReference(com.google.firebase.firestore.CollectionReference) SuppressLint(android.annotation.SuppressLint) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) LocationResult(com.google.android.gms.location.LocationResult) AdapterView(android.widget.AdapterView) Location(android.location.Location)

Aggregations

CollectionReference (com.google.firebase.firestore.CollectionReference)43 QuerySnapshot (com.google.firebase.firestore.QuerySnapshot)15 Intent (android.content.Intent)14 QueryDocumentSnapshot (com.google.firebase.firestore.QueryDocumentSnapshot)14 View (android.view.View)13 DocumentSnapshot (com.google.firebase.firestore.DocumentSnapshot)13 NonNull (androidx.annotation.NonNull)10 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)10 DocumentReference (com.google.firebase.firestore.DocumentReference)10 FirebaseFirestoreException (com.google.firebase.firestore.FirebaseFirestoreException)10 ArrayList (java.util.ArrayList)8 Bundle (android.os.Bundle)7 ListView (android.widget.ListView)7 OnSuccessListener (com.google.android.gms.tasks.OnSuccessListener)7 AdapterView (android.widget.AdapterView)6 TextView (android.widget.TextView)6 OnCompleteListener (com.google.android.gms.tasks.OnCompleteListener)5 Task (com.google.android.gms.tasks.Task)5 List (java.util.List)5 RecyclerView (androidx.recyclerview.widget.RecyclerView)4