Search in sources :

Example 21 with CollectionReference

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

the class ownerListPlayers method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_owner_list_players);
    // fetch all the document to display them on listview
    db = FirebaseFirestore.getInstance();
    final CollectionReference collectionReference = db.collection("Players");
    playerList = findViewById(R.id.ownerPlayerListview);
    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.getOwner() == true) {
                // DO nothing
                } else {
                    allPlayers.add(p);
                }
            }
            playerAdapter.notifyDataSetChanged();
        }
    });
    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(ownerListPlayers.this, ownerPlayerProfile.class);
            intent.putExtra("playerUserName", playerUserName);
            intent.putExtra("playerHash", playerHash);
            startActivity(intent);
        }
    });
    playerList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            // Item to be deleted
            final int deletePlayer = i;
            new AlertDialog.Builder(ownerListPlayers.this).setIcon(android.R.drawable.ic_delete).setTitle("Confirm removal").setMessage("Would you like to remove player?").setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    // Delete any players we chose
                    // URL: https://firebase.google.com/docs/firestore/manage-data/delete-data
                    // Date: 2021-11-11 UTC
                    // Update database with the removed data
                    String TAG = "working";
                    collectionReference.document(allPlayers.get(deletePlayer).getUsername()).delete().addOnSuccessListener(new OnSuccessListener<Void>() {

                        @Override
                        public void onSuccess(Void unused) {
                            Log.d(TAG, "message");
                        }
                    }).addOnFailureListener(new OnFailureListener() {

                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.e("MYAPP", "exception: " + e.getMessage());
                            Log.e("MYAPP", "exception: " + e.toString());
                        }
                    });
                // Update ranking again
                }
            }).setNegativeButton("No", null).show();
            return true;
        }
    });
// 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();
// searchedPlayerName = searchedPlayerName.trim(); // TRIM WHITESPACES, IMPORTANT
// 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("");
// }
// });
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) DialogInterface(android.content.DialogInterface) CollectionReference(com.google.firebase.firestore.CollectionReference) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) 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) FirebaseFirestoreException(com.google.firebase.firestore.FirebaseFirestoreException) AdapterView(android.widget.AdapterView) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 22 with CollectionReference

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

the class ownerPlayerProfile method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_owner_player_profile);
    ListView qrCodeListView = findViewById(R.id.ownerPlayerProfileListView);
    // Create list adapter
    qrCodes = new ArrayList<>();
    scanAdapter = new ScanListAdapter(this, R.layout.my_scans_adapter, qrCodes);
    qrCodeListView.setAdapter(scanAdapter);
    db = FirebaseFirestore.getInstance();
    CollectionReference collectionReference = db.collection("Players");
    // Extract from intent
    Intent intent = this.getIntent();
    Bundle extras = intent.getExtras();
    if (extras != null) {
        playerUserName = (String) extras.get("playerUserName");
        playerHash = (String) extras.get("playerHash");
    }
    // Extract Player from database
    DocumentReference playerDocRef = db.collection("Players").document(playerUserName);
    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 = documentSnapshot.toObject(Player.class);
                    qrCodes.clear();
                    for (int i = 0; i < player.numberOfCode(); i++) {
                        qrCodes.add(player.qrCodes.get(i));
                    }
                    scanAdapter.notifyDataSetChanged();
                    Log.d("Success", "12");
                    // display to list view
                    displayPlayerInfo();
                }
            }
        }
    });
    // Delete QRCode on long click
    qrCodeListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
            // Item to be deleted
            final int deleteQRCode = i;
            new AlertDialog.Builder(ownerPlayerProfile.this).setIcon(android.R.drawable.ic_delete).setTitle("Confirm removal").setMessage("Would you like to remove QRCode?").setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    // Delete any QR code we chose
                    // URL: https://firebase.google.com/docs/firestore/manage-data/delete-data
                    // Date: 2021-11-11 UTC
                    player.qrCodes.remove(deleteQRCode);
                    qrCodes.remove(deleteQRCode);
                    scanAdapter.notifyDataSetChanged();
                    // Update database with the removed data
                    String TAG = "working";
                    collectionReference.document(player.getUsername()).set(player).addOnSuccessListener(new OnSuccessListener<Void>() {

                        @Override
                        public void onSuccess(Void unused) {
                            Log.d(TAG, "message");
                        }
                    }).addOnFailureListener(new OnFailureListener() {

                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.e("MYAPP", "exception: " + e.getMessage());
                            Log.e("MYAPP", "exception: " + e.toString());
                        }
                    });
                // Update score again
                }
            }).setNegativeButton("No", null).show();
            return true;
        }
    });
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) DialogInterface(android.content.DialogInterface) CollectionReference(com.google.firebase.firestore.CollectionReference) DocumentSnapshot(com.google.firebase.firestore.DocumentSnapshot) ListView(android.widget.ListView) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) DocumentReference(com.google.firebase.firestore.DocumentReference) Bundle(android.os.Bundle) Intent(android.content.Intent) TextView(android.widget.TextView) View(android.view.View) AdapterView(android.widget.AdapterView) ListView(android.widget.ListView) AdapterView(android.widget.AdapterView) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 23 with CollectionReference

use of com.google.firebase.firestore.CollectionReference in project firebase-android-sdk by firebase.

the class IntegrationTestUtil method testCollectionWithDocs.

public static CollectionReference testCollectionWithDocs(Map<String, Map<String, Object>> docs) {
    CollectionReference collection = testCollection();
    CollectionReference writer = testFirestore().collection(collection.getId());
    writeAllDocs(writer, docs);
    return collection;
}
Also used : CollectionReference(com.google.firebase.firestore.CollectionReference)

Example 24 with CollectionReference

use of com.google.firebase.firestore.CollectionReference in project firebase-android-sdk by firebase.

the class ConformanceRuntime method teardown.

/**
 * Cleans up the database by removing the initialized data.
 */
public void teardown() throws InterruptedException, TimeoutException {
    WriteBatch batch = firestore.batch();
    for (TestCollection collection : initialData) {
        CollectionReference ref = firestore.document(testDocument).collection(collection.path());
        for (TestDocument document : collection.documents()) {
            DocumentReference docRef = ref.document(document.id());
            batch.delete(docRef);
            logger.info("Removing document: " + docRef.getPath());
        }
    }
    waitForBatch(batch);
}
Also used : WriteBatch(com.google.firebase.firestore.WriteBatch) CollectionReference(com.google.firebase.firestore.CollectionReference) DocumentReference(com.google.firebase.firestore.DocumentReference)

Example 25 with CollectionReference

use of com.google.firebase.firestore.CollectionReference in project turtleparties by CMPUT301W22T21.

the class QRInfo method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_qrinfo);
    view = this.findViewById(android.R.id.content);
    Intent intent = getIntent();
    Bundle qrBundle = intent.getBundleExtra(MainActivity.EXTRA_QR);
    thisQr = (ScoreQrcode) qrBundle.getSerializable("qrcode");
    user = (Player) qrBundle.getSerializable("user");
    showDeleteButton = (boolean) qrBundle.getSerializable("showDeleteButton");
    Double lat = (Double) qrBundle.getSerializable("lat");
    Double lon = (Double) qrBundle.getSerializable("lon");
    String qrname = thisQr.getCode();
    thisQr.generateQRimage();
    db = FirebaseFirestore.getInstance();
    final CollectionReference collectionReference = db.collection("QR codes");
    qrImage = view.findViewById(R.id.qr_imageView);
    scoreView = view.findViewById(R.id.score_info_view);
    locationView = view.findViewById(R.id.location_view);
    deleteButton = view.findViewById(R.id.deleteQrButton);
    if (thisQr.isToShow()) {
        qrImage.setImageBitmap(thisQr.getMyBitmap());
    } else {
        qrImage.setImageResource(R.drawable.ic_baseline_qr_code_24);
    }
    scoreView.setText(String.valueOf(thisQr.getScore()));
    if (lat != 0.0) {
        locationView.setText(String.valueOf(lat + "° N " + lon + "° W"));
    } else {
        locationView.setText("n/a");
    }
    if (!showDeleteButton) {
        deleteButton.setVisibility(view.INVISIBLE);
    }
    commentList = findViewById(R.id.comment_list);
    commentDataList = new ArrayList<>();
    commentAdapter = new QRCommentList(this, commentDataList);
    commentList.setAdapter(commentAdapter);
    collectionReference.addSnapshotListener(new EventListener<QuerySnapshot>() {

        @Override
        public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException error) {
            db.collection("QR codes").document(qrname).collection("comments").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {

                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (QueryDocumentSnapshot doc : task.getResult()) {
                            String username = doc.getId();
                            Log.d(TAG, username);
                            db.collection("QR codes").document(qrname).collection("comments").document(username).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {

                                @Override
                                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                                    if (task.isSuccessful()) {
                                        DocumentSnapshot doc = task.getResult();
                                        String userComment = (String) doc.getData().get("comment");
                                        commentDataList.add((new Comment(userComment, username)));
                                        Log.d(TAG, userComment + "  " + username);
                                        commentAdapter.notifyDataSetChanged();
                                    }
                                }
                            });
                        }
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });
            commentAdapter.notifyDataSetChanged();
        }
    });
}
Also used : Task(com.google.android.gms.tasks.Task) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) Bundle(android.os.Bundle) Intent(android.content.Intent) FirebaseFirestoreException(com.google.firebase.firestore.FirebaseFirestoreException) CollectionReference(com.google.firebase.firestore.CollectionReference) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) QueryDocumentSnapshot(com.google.firebase.firestore.QueryDocumentSnapshot) DocumentSnapshot(com.google.firebase.firestore.DocumentSnapshot) NonNull(androidx.annotation.NonNull)

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