Search in sources :

Example 11 with FirebaseFirestore

use of com.google.firebase.firestore.FirebaseFirestore in project QRHunt by CMPUT301W22T00.

the class FragmentAddQrCode method onCreateView.

/**
 * After scanning QR code - Handles the displaying and saving of the QR code values (score, number of scans, location)
 * and is responsible for attaching the user's photo in the proper position
 *
 * @param inflater           Inflater
 * @param container          Where the fragment is contained
 * @param savedInstanceState SavedInstanceState
 * @return view
 */
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_qr_profile_after_scan, container, false);
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    FirebaseStorage storage = FirebaseStorage.getInstance();
    PlayableQrCode qrCode = (PlayableQrCode) getArguments().getSerializable(PlayableQrCode.TAG);
    ImageView imageView = view.findViewById(R.id.qr_scan_profile_image_holder);
    ActivityResultLauncher<Intent> pickPhotoResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
        if (result.getResultCode() == Activity.RESULT_OK) {
            bitmap = (Bitmap) result.getData().getExtras().get("data");
            Log.d(TAG, String.format("found image with %d bytes", bitmap.getRowBytes() * bitmap.getHeight()));
            imageView.setImageBitmap(bitmap);
        }
    });
    // Display score
    ((TextView) view.findViewById(R.id.qr_scan_profile_score)).setText(String.format("%d points", qrCode.getScore()));
    numScannedTextView = view.findViewById(R.id.qr_scan_profile_num_scanned);
    numScannedTextView.setText("0 Scans");
    db.collection("users").document(qrCode.getPlayerId()).get().addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
            DocumentSnapshot res = task.getResult();
            if (res != null && res.exists()) {
                Double numScanned = res.getDouble("numScanned");
                int intNumScanned;
                if (numScanned != null) {
                    intNumScanned = numScanned.intValue();
                } else {
                    intNumScanned = 0;
                }
                numScannedTextView.setText(String.format("%d Scans", intNumScanned));
            }
        }
    });
    // Display location
    TextView showLatLong = view.findViewById(R.id.qr_scan_profile_location);
    QrLocation qrLocation = qrCode.getLocation();
    if (qrLocation != null && qrLocation.exists()) {
        String strLatitude = Location.convert(qrLocation.getLatitude(), Location.FORMAT_DEGREES);
        String strLongitude = Location.convert(qrLocation.getLongitude(), Location.FORMAT_DEGREES);
        showLatLong.setText(strLatitude + ", " + strLongitude);
    } else {
        showLatLong.setText("No Location");
    }
    addPicButton = view.findViewById(R.id.qr_scan_profile_take_photo_button);
    addPicButton.setOnClickListener(__ -> {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        pickPhotoResultLauncher.launch(intent);
        addPicButton.setVisibility(View.GONE);
        addPicButton.setClickable(false);
    });
    Button okButton = view.findViewById(R.id.qr_scan_profile_save_button);
    okButton.setOnClickListener(__ -> {
        LinearLayout overlay = view.findViewById(R.id.qr_scan_profile_fader_layout);
        overlay.setVisibility(View.VISIBLE);
        if (bitmap != null) {
            StorageReference ref = storage.getReference(String.format("qrCodes/%s/%s.jpg", qrCode.getPlayerId(), qrCode.getId()));
            ByteArrayOutputStream compressedBitmap = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, compressedBitmap);
            UploadTask uploadTask = ref.putBytes(compressedBitmap.toByteArray());
            uploadTask.addOnFailureListener(exception -> Log.d(TAG, "Image upload failed: " + exception)).addOnSuccessListener(taskSnapshot -> ref.getDownloadUrl().addOnCompleteListener(uriTask -> {
                if (uriTask.isSuccessful() && uriTask.getResult() != null) {
                    qrCode.setImageUrl(uriTask.getResult().toString());
                    Log.d(TAG, "Image upload succeeded to " + uriTask.getResult().toString());
                }
                qrCode.addToDb();
                overlay.setVisibility(View.INVISIBLE);
                dismiss();
            }));
        } else {
            qrCode.addToDb();
            overlay.setVisibility(View.INVISIBLE);
            dismiss();
        }
    });
    Button cancelButton = view.findViewById(R.id.qr_scan_profile_cancel_button);
    cancelButton.setOnClickListener(__ -> dismiss());
    return view;
}
Also used : LinearLayout(android.widget.LinearLayout) Bundle(android.os.Bundle) ByteArrayOutputStream(java.io.ByteArrayOutputStream) NonNull(androidx.annotation.NonNull) ImageView(android.widget.ImageView) Intent(android.content.Intent) Player(com.bigyoshi.qrhunt.player.Player) MediaStore(android.provider.MediaStore) View(android.view.View) Button(android.widget.Button) Log(android.util.Log) DocumentSnapshot(com.google.firebase.firestore.DocumentSnapshot) FirebaseStorage(com.google.firebase.storage.FirebaseStorage) ActivityResultLauncher(androidx.activity.result.ActivityResultLauncher) LayoutInflater(android.view.LayoutInflater) ViewGroup(android.view.ViewGroup) FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) TextView(android.widget.TextView) Nullable(androidx.annotation.Nullable) Bitmap(android.graphics.Bitmap) StorageReference(com.google.firebase.storage.StorageReference) ActivityResultContracts(androidx.activity.result.contract.ActivityResultContracts) Location(android.location.Location) Activity(android.app.Activity) DialogFragment(androidx.fragment.app.DialogFragment) R(com.bigyoshi.qrhunt.R) UploadTask(com.google.firebase.storage.UploadTask) FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) StorageReference(com.google.firebase.storage.StorageReference) Intent(android.content.Intent) ActivityResultContracts(androidx.activity.result.contract.ActivityResultContracts) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImageView(android.widget.ImageView) View(android.view.View) TextView(android.widget.TextView) DocumentSnapshot(com.google.firebase.firestore.DocumentSnapshot) UploadTask(com.google.firebase.storage.UploadTask) Button(android.widget.Button) FirebaseStorage(com.google.firebase.storage.FirebaseStorage) TextView(android.widget.TextView) ImageView(android.widget.ImageView) LinearLayout(android.widget.LinearLayout) Nullable(androidx.annotation.Nullable)

Example 12 with FirebaseFirestore

use of com.google.firebase.firestore.FirebaseFirestore in project House-Organizer by House-Organizer.

the class FirebaseTestsHelper method createTestHouseholdOnFirestore.

public static void createTestHouseholdOnFirestore() throws ExecutionException, InterruptedException {
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    Task<QuerySnapshot> t = db.collection("household").get();
    Tasks.await(t);
    if (!t.getResult().getDocuments().isEmpty())
        return;
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    Map<String, Object> houseHold = new HashMap<>();
    List<String> residents = Arrays.asList(user.getEmail());
    houseHold.put("name", TEST_HOUSEHOLD_NAME);
    houseHold.put("owner", user.getEmail());
    houseHold.put("num_members", 1);
    houseHold.put("residents", residents);
    Task task = db.collection("households").add(houseHold);
    Tasks.await(task);
}
Also used : Task(com.google.android.gms.tasks.Task) FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) HashMap(java.util.HashMap) FirebaseUser(com.google.firebase.auth.FirebaseUser) QuerySnapshot(com.google.firebase.firestore.QuerySnapshot)

Example 13 with FirebaseFirestore

use of com.google.firebase.firestore.FirebaseFirestore in project noChange by Khalidtoak.

the class AppViewModel method getAllPayment.

public LiveData<ArrayList<Payment>> getAllPayment(String type, String searchWord) {
    FirebaseFirestore firestore = FirebaseFirestore.getInstance();
    MutableLiveData<ArrayList<Payment>> response = new MutableLiveData<>();
    firestore.collection(Constant.USER_COLLECTION).document(FirebaseAuth.getInstance().getCurrentUser().getUid()).collection(Constant.PAYMENT_COLLECTION).orderBy("timestamp").whereEqualTo("type", type).whereGreaterThanOrEqualTo("name", searchWord).get().addOnSuccessListener(res -> {
        response.postValue((ArrayList<Payment>) res.toObjects(Payment.class));
    }).addOnFailureListener(e -> {
        e.printStackTrace();
        Log.i("Could not fetch data", "Could not fetch data");
        response.postValue(null);
    });
    return response;
}
Also used : MutableLiveData(androidx.lifecycle.MutableLiveData) FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) LiveData(androidx.lifecycle.LiveData) Constant(com.group1.swepproject.user.nochange.data.Constant) Application(android.app.Application) NonNull(androidx.annotation.NonNull) AndroidViewModel(androidx.lifecycle.AndroidViewModel) Log(android.util.Log) FirebaseAuth(com.google.firebase.auth.FirebaseAuth) ArrayList(java.util.ArrayList) FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) ArrayList(java.util.ArrayList) MutableLiveData(androidx.lifecycle.MutableLiveData)

Example 14 with FirebaseFirestore

use of com.google.firebase.firestore.FirebaseFirestore in project M3 by iatharva.

the class CreateNewAccount method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create_new_account);
    EmailField = findViewById(R.id.EmailField);
    PasswordField = findViewById(R.id.PasswordField);
    FNameField = findViewById(R.id.FNameField);
    LNameField = findViewById(R.id.LNameField);
    DateField = findViewById(R.id.DateField);
    AddAccountBtn = findViewById(R.id.AddAccountBtn);
    // Get Date DialogBox
    DateField.setOnClickListener(v -> {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        DatePickerDialog dialog = new DatePickerDialog(CreateNewAccount.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, mDateSetListener, year, month, day);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();
    });
    // Set Date in proper format
    mDateSetListener = (view, year, month, dayOfMonth) -> {
        month = month + 1;
        String date = dayOfMonth + "-" + month + "-" + year;
        DateField.setText(date);
    };
    // Add Account in Firebase
    AddAccountBtn.setOnClickListener(view -> {
        // Get all the data from UI
        Email = EmailField.getText().toString().trim();
        Password = PasswordField.getText().toString().trim();
        FName = FNameField.getText().toString().trim();
        LName = LNameField.getText().toString().trim();
        DateOfBirth = DateField.getText().toString().trim();
        // Validations
        if (TextUtils.isEmpty(Email)) {
            Toast.makeText(getApplicationContext(), "Please enter email", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(Password)) {
            Toast.makeText(getApplicationContext(), "Please enter password", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(FName)) {
            Toast.makeText(getApplicationContext(), "Please enter your name", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(LName)) {
            Toast.makeText(getApplicationContext(), "Please enter your last name", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(DateOfBirth)) {
            Toast.makeText(getApplicationContext(), "Select your date of birth", Toast.LENGTH_SHORT).show();
            return;
        }
        // Firebase operations
        fAuth = FirebaseAuth.getInstance();
        final FirebaseFirestore db = FirebaseFirestore.getInstance();
        fAuth.createUserWithEmailAndPassword(Email, Password).addOnCompleteListener(task -> {
            if (task.isSuccessful()) {
                UID = Objects.requireNonNull(fAuth.getCurrentUser()).getUid();
                Map<String, Object> user = new HashMap<>();
                user.put("Uid", UID);
                user.put("Email", Email);
                user.put("FName", FName);
                user.put("LName", LName);
                user.put("Dob", DateOfBirth);
                user.put("IsPaid", "0");
                // Insert and check if user is data is inserted successfully and user is created
                db.collection("Users").document(UID).set(user).addOnCompleteListener(task1 -> {
                    if (task1.isSuccessful()) {
                        // Success Case
                        createCountLogs(UID);
                        AddAccountBtn.setText(R.string.create_account);
                        Toast.makeText(CreateNewAccount.this, "Account created succesfully!", Toast.LENGTH_LONG).show();
                        Intent i = new Intent(CreateNewAccount.this, IntroScreen1.class);
                        startActivity(i);
                    } else {
                        // Failure Case
                        AddAccountBtn.setText(R.string.create_account);
                        String errorMessage = Objects.requireNonNull(task1.getException()).getMessage();
                        Toast.makeText(CreateNewAccount.this, "Error: " + errorMessage, Toast.LENGTH_LONG).show();
                    }
                });
            } else {
                // Exception Case
                Toast.makeText(CreateNewAccount.this, "Error! " + Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    });
}
Also used : FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) ColorDrawable(android.graphics.drawable.ColorDrawable) DatePickerDialog(android.app.DatePickerDialog) HashMap(java.util.HashMap) Calendar(java.util.Calendar) Intent(android.content.Intent)

Example 15 with FirebaseFirestore

use of com.google.firebase.firestore.FirebaseFirestore 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) {
    /**
     * Basic layout, will have to ensure user enters info and that the info is correct later
     */
    EditText usernameEdit = (EditText) findViewById(R.id.username_text);
    String username = usernameEdit.getText().toString();
    EditText nameEdit = (EditText) findViewById(R.id.name_text);
    String name = nameEdit.getText().toString();
    EditText emailEdit = (EditText) findViewById(R.id.email_text);
    String email = emailEdit.getText().toString();
    EditText cityEdit = (EditText) findViewById(R.id.city_region);
    String cityRegion = cityEdit.getText().toString();
    FirebaseFirestore db;
    // Access a Cloud FireStore instance from Activity
    db = FirebaseFirestore.getInstance();
    final CollectionReference collectionReference = db.collection("Players");
    HashMap<String, String> data = new HashMap<>();
    data.put("score", "0");
    // create new document
    collectionReference.document(username).set(data).addOnSuccessListener(new OnSuccessListener<Void>() {

        @Override
        public void onSuccess(Void unused) {
        }
    }).addOnFailureListener(new OnFailureListener() {

        @Override
        public void onFailure(@NonNull Exception e) {
        }
    });
    singletonPlayer.player.setUsername(username);
    // collectionReference.document(username).update("scannedcodes", FieldValue.arrayUnion("array"));
    usernameEdit.setText("");
    Intent intent = new Intent(getApplicationContext(), UserMenu.class);
    intent.putExtra("userMenu_act", (String) null);
    startActivity(intent);
}
Also used : EditText(android.widget.EditText) FirebaseFirestore(com.google.firebase.firestore.FirebaseFirestore) HashMap(java.util.HashMap) Intent(android.content.Intent) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) CollectionReference(com.google.firebase.firestore.CollectionReference) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Aggregations

FirebaseFirestore (com.google.firebase.firestore.FirebaseFirestore)21 FirebaseAuth (com.google.firebase.auth.FirebaseAuth)6 HashMap (java.util.HashMap)6 Intent (android.content.Intent)5 Log (android.util.Log)4 FirebaseUser (com.google.firebase.auth.FirebaseUser)4 View (android.view.View)3 NonNull (androidx.annotation.NonNull)3 DocumentReference (com.google.firebase.firestore.DocumentReference)3 DocumentSnapshot (com.google.firebase.firestore.DocumentSnapshot)3 QuerySnapshot (com.google.firebase.firestore.QuerySnapshot)3 Constant (com.group1.swepproject.user.nochange.data.Constant)3 Test (org.junit.Test)3 Application (android.app.Application)2 Bitmap (android.graphics.Bitmap)2 Location (android.location.Location)2 Bundle (android.os.Bundle)2 MediaStore (android.provider.MediaStore)2 EditText (android.widget.EditText)2 TextView (android.widget.TextView)2