0

Does anyone know how to retrieve data on these qr codes and use them to update collections on my google firestore database. This would be very helpful. Below is the code I am using and because ML kit is in its beta etc I cannot find any tutorials on how to do this:

Here is the code below: What I am looking for is code to use said QR code and update fields in one of my collections on the database. If there is any pointers out there in how to do this it would be most welcomed. I have heard talk of arrays being used but as I am very new to programming in general I haven't covered this topic yet.

public class StudentAccount extends AppCompatActivity {


private static final int CHOOSE_IMAGE = 101;
public static final int CAMERA_REQUEST_CODE = 10;
public static final int PROFILE_PIC_REQUEST_CODE = 20;

private Button button, signout;

private FirebaseAuth mAuth;
TextView username;

ImageView imageView;
EditText editText;
Uri uriProfileImage;
ProgressBar progressBar;
String profileImageUrl;


ListView listView;

private List<String> userList = new ArrayList<>();


private final int BARCODE_RECO_REQ_CODE = 200;

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

    mAuth = FirebaseAuth.getInstance();
    signout = (Button) findViewById(R.id.SIGNOUT3);
    username = (TextView) findViewById(R.id.welcomeText2);

    //Check if user i already logged in or not

    if (mAuth.getCurrentUser() == null){
        finish();
        startActivity(new Intent(getApplicationContext(),SignInActivity.class));
    }

    //Fetching display name of current user and setting to activity
    FirebaseUser user = mAuth.getCurrentUser();
    if (user != null){
        username.setText("Welcome " +user.getEmail());
    }

    signout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mAuth.signOut();
            finish();
            startActivity(new Intent(getApplicationContext(), MainActivity.class));
        }
    });


    imageView = findViewById(R.id.imageView);
    progressBar = findViewById(R.id.progressbar);
    mAuth = FirebaseAuth.getInstance();

    button =  findViewById(R.id.VIEW_ATTENDANCE);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            openViewMyAttendance();
        }
    });



    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showImageChooser();

        }
    });

    findViewById(R.id.buttonSave).setOnClickListener( new View.OnClickListener(){

        @Override
        public void onClick(View view) {
            saveUserInformation();
        }

        private void saveUserInformation() {


            FirebaseUser user = mAuth.getCurrentUser();

            if (user != null && profileImageUrl != null){
                UserProfileChangeRequest profile = new UserProfileChangeRequest.Builder()
                        .setPhotoUri(Uri.parse(profileImageUrl)).build();

                user.updateProfile(profile).addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                      if (task.isSuccessful()) {
                          Toast.makeText(StudentAccount.this, "Profile Updated", Toast.LENGTH_SHORT).show();
                      }
                    }
                });
            }
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data != null && data.getData() !=null){
        uriProfileImage = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
            imageView.setImageBitmap(bitmap);

            uploadImageToFirebaseStorage();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    if (requestCode == BARCODE_RECO_REQ_CODE){
        if (resultCode == RESULT_OK){
            Bitmap photo = (Bitmap)data.getExtras().get("data");
            barcodeRecognition(photo);
        }
    }
}

private void barcodeRecognition(Bitmap photo) {
    FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(photo);
    FirebaseVisionBarcodeDetector detector = FirebaseVision.getInstance()
            .getVisionBarcodeDetector();
    Task<List<FirebaseVisionBarcode>> result = detector.detectInImage(image)
            .addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionBarcode>>() {
                @Override
                public void onSuccess(List<FirebaseVisionBarcode> barcodes) {

                    for (FirebaseVisionBarcode barcode: barcodes) {
                        Rect bounds = barcode.getBoundingBox();
                        Point[] corners = barcode.getCornerPoints();

                        String rawValue = barcode.getRawValue();

                        int valueType = barcode.getValueType();
                        Toast.makeText(StudentAccount.this, rawValue, Toast.LENGTH_SHORT).show();

                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                   Toast.makeText(StudentAccount.this, "Something went wrong", Toast.LENGTH_SHORT).show();
                }
            });
}


private void uploadImageToFirebaseStorage() {
    final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference
            ("profilepics/"+System.currentTimeMillis() + ".jpg");

    if (uriProfileImage != null){
        progressBar.setVisibility(View.VISIBLE);
        profileImageRef.putFile(uriProfileImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                progressBar.setVisibility(View.GONE);

                profileImageUrl = taskSnapshot.getUploadSessionUri().toString();

            }
        })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(StudentAccount.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

}

private void loadUserInformation() {
    if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        updateProfilePermissions();
    } else {
        String[] permissionRequested = {Manifest.permission.READ_EXTERNAL_STORAGE};
        requestPermissions(permissionRequested, PROFILE_PIC_REQUEST_CODE);
    }
}

private void updateProfilePermissions() {
    FirebaseUser user = mAuth.getCurrentUser();
    if (user.getPhotoUrl() != null) {
        Glide.with(this).load(user.getPhotoUrl().toString()).into(imageView);
    }

}


private void showImageChooser(){
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Profile Image"),CHOOSE_IMAGE);
}


@Override
protected void onPause(){
    super.onPause();
}


public void barcodeReco(View v) {
    if(checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
        callsCamera();
    } else {
        String[] permissionRequested = {Manifest.permission.CAMERA};
        requestPermissions(permissionRequested, CAMERA_REQUEST_CODE);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == CAMERA_REQUEST_CODE){
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
            callsCamera();
        } else {
            Toast.makeText(this, getString(R.string.unable_to_invoke_camera), Toast.LENGTH_LONG).show();
        }
    } else if (requestCode == PROFILE_PIC_REQUEST_CODE){
        if (grantResults [0] == PackageManager.PERMISSION_GRANTED){
            loadUserInformation();
        } else {
            Toast.makeText( this, getString(R.string.Unable_to_update_profile), Toast.LENGTH_LONG).show();
        }
    }
}

private void callsCamera() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent,BARCODE_RECO_REQ_CODE);
}

public void openViewMyAttendance () {
    Intent intent = new Intent(this, ViewMyAttendance.class);
    startActivity(intent);
}

}

Here is a piece of code i have used to manually update fields in the database. I am struggling to change this code to use qr code to update the fields.

   public void saveAttendance(View v) {
    String sessionID = editTextSessionID.getText().toString();
    String studentID = editTextStudentID.getText().toString();

    Attendance attendance = new Attendance(sessionID, studentID);

    attendanceRef2.add(attendance).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
        @Override
        public void onSuccess(DocumentReference documentReference) {
            Toast.makeText(InputManualAttendance.this, "Attendance Record Updated", Toast.LENGTH_SHORT).show();
        }
    });
}

I have made a seperate Attendance class with get and set methods and made reference to them via this code below, here is where i input to firestore:

   private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference attendanceRef2 = db.collection("Attendance");
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    What is the problem with this code? – Alex Mamo Aug 03 '18 at 11:05
  • There is no problem with this code I am just showing the code to see if there is anything I can add to it in order to use qr codes once scanned to update my firestore database. Is there a way to do this –  Aug 03 '18 at 11:08
  • Ok but I cannot see something in your code that indicates that you have tried somethig. Please share what you have tried so far. – Alex Mamo Aug 03 '18 at 11:18
  • The code above is what I have tried and it works to add the data to the fields manually although I am new to this and I have been struggling to make the transition to updating via qr code –  Aug 03 '18 at 11:28
  • You said that you are trying to place the data in Firestore. Where did do that? – Alex Mamo Aug 03 '18 at 11:28
  • Above is the way I am inserting the info to my Firestore database –  Aug 03 '18 at 11:38
  • Ok, thanks for updating. When using the code in your updated question, what is the bahaviour? Do you have an error? – Alex Mamo Aug 03 '18 at 11:39
  • There is no error when manually entering data into the text fields and clicking a button to add the data to Firestore. I am just struggling with a way to transition the same data to my Firestore via scanning a QR code –  Aug 03 '18 at 11:41
  • What is the exact data that you want to store in the Firestore database? Of which type? – Alex Mamo Aug 03 '18 at 12:25
  • Two string values one which contains a sessionID and the other which contains the studentID, both these fields are connected to other collections within the database –  Aug 03 '18 at 12:34
  • I understand but when you are using `add(attendance)` is the `attendance` not writen to the database? – Alex Mamo Aug 03 '18 at 12:46
  • It is written to the database but I am looking to avoid manual input like this and just scan to update these fields based on the user who is logged in –  Aug 03 '18 at 12:49
  • Have you tried to call `saveAttendance` method in the moment you are done getting the data from scan operation? – Alex Mamo Aug 03 '18 at 12:52
  • I haven't tried this but the saveAttendance method is an onClick method to another button, how could I change the method in order to suit the barcodeRecognition method() –  Aug 03 '18 at 13:02
  • So once you have done with the bar recognition. on button click call that method, If I understood correctly. – Alex Mamo Aug 03 '18 at 13:06
  • Sorry currently the method to input manually is on another activity/class. How exactly would I modify this for it to be placed within the barcodeRecognition method –  Aug 03 '18 at 13:13
  • There is no need to move in the current activity, make it `static` and call from the actual ativity. – Alex Mamo Aug 03 '18 at 13:14
  • The method contains no static fields which cannot be made static –  Aug 03 '18 at 13:16
  • You can wait for other answers/comments but I think your problem is to broad to be solved here, sorry. – Alex Mamo Aug 03 '18 at 13:18

0 Answers0