0

The problem here is that I can't fetch the entire row from a single read... I have to make multiple reads. I am unable to implement a table_row object which can hold all the values of a row.

As an alternative I have tried to make a array of row data but I am unable to do so because "ondatachanged" is a async function; hence i am getting "null".

Please note if I use multiple objects to store the data of a single row then at last how can I map that all and make a final table.

I hereby attatch my lenghty code below

public int generate_pdf() throws IOException{

    fetch_cls_details();

    String pdf_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).toString();

    File file = new File(pdf_path,"attadence_AttandX.pdf");
    OutputStream outputStream = new FileOutputStream(file);

    PdfWriter writer = new PdfWriter(file);
    PdfDocument pdfDocument = new PdfDocument(writer);
    Document document = new Document(pdfDocument);

    document.setMargins(0,0,0,0);

    Drawable bg_pdf = getDrawable(R.drawable.bg);
    Bitmap bg_pdf_bitmap =((BitmapDrawable)bg_pdf ).getBitmap();
    ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
    bg_pdf_bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream1);
    byte[] bg_pdf_bitmap_data = stream1.toByteArray();
    ImageData imageData1 = ImageDataFactory.create(bg_pdf_bitmap_data);

    Image bg_pdf_img = new Image(imageData1);

    Drawable header_pdf = getDrawable(R.drawable.headerpdf);
    Bitmap header_bitmap =((BitmapDrawable)header_pdf ).getBitmap();
    ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
    header_bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream2);
    byte[] header_pdf_bitmap_data = stream2.toByteArray();
    ImageData imageData2 = ImageDataFactory.create(header_pdf_bitmap_data);

    Image header_pdf_img = new Image(imageData2);

    // class details table

    // we have to make 3 functions 1 for class details from header. 1 for attadence data 1 for calculation (not sure

    List l1 = new List();
    l1.add(cls_name_str);
    l1.add(sub_name_str);
    l1.add(sub_code_str);


    Table header_table = new Table(2);
    header_table.setMarginTop(30F);
    header_table.setFont(PdfFontFactory.createFont(StandardFonts.HELVETICA));

    header_table.addCell(new Cell().add(l1)
            .setPaddingLeft(30F)
            .setTextAlignment(TextAlignment.LEFT)
            .setBorder(Border.NO_BORDER)
            .setFontSize(18)
    );

    header_table.addCell(new Cell().add(new Paragraph(created_by_str))
            .setBorder(Border.NO_BORDER)
            .setPaddingLeft(270F)
            .setFontSize(30)
    );

    float[] col_width = {1,3,2,1,1,1};
    String[] body_header_val = {"#","Name","Phone","Present No","Total","percentage"};
    Table body_table = new Table(col_width);
    body_table.setWidth(UnitValue.createPercentValue(100));
    body_table.setFont(PdfFontFactory.createFont(StandardFonts.HELVETICA));

    for(int i = 0; i <= body_header_val.length-1; i++){
        body_table.addHeaderCell(new Cell().add(new Paragraph(body_header_val[i]))
                .setBorder(Border.NO_BORDER)
                .setPadding(5)
                .setBackgroundColor(new DeviceRgb(118, 179, 236))
                .setFontColor(ColorConstants.WHITE)
                .setTextAlignment(TextAlignment.CENTER)
        );
        Log.d("TABLE_VALUE", body_header_val[i]);
    }

    table_helper table_helper_obj = new table_helper();

    DatabaseReference root_ref,this_cls_data_ref,this_cls_header_ref;

    root_ref = FirebaseDatabase.getInstance().getReference();
    this_cls_header_ref = root_ref.child("classroom_header").child(room_id);
    this_cls_data_ref = root_ref.child(room_id).child("attedance_data");

    // lets map data into array first then we will loop dis array to print in table with customizations
    ArrayList<String[]> full_table_data_array = new ArrayList<>();
    String[] table_row = new String[6];
    table_row[4] = String.valueOf(total_cls_taken);

    this_cls_data_ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if(snapshot.exists()){
                Log.d(TAG+"_PDF", "snapshot "+snapshot.toString());
                long no_of_child = snapshot.getChildrenCount();
                Log.d(TAG+"_PDF", "NO of child =  "+no_of_child);
                DatabaseReference user_profile_ref;
                user_profile_ref = root_ref.child("userprofile");
                //main pt

                    for (DataSnapshot snapshot1 : snapshot.getChildren())
                    {
                        String UID;
                        int serial_no = 1;

                        body_table.addCell(new Cell().add(new Paragraph(String.valueOf(serial_no)))
                                .setBorder(Border.NO_BORDER)
                                .setPadding(5)
                                .setBackgroundColor(ColorConstants.WHITE)
                                .setFontColor(ColorConstants.BLACK)
                                .setTextAlignment(TextAlignment.CENTER)
                        );
                        table_helper_obj.setSerial_no(String.valueOf(serial_no));
                        Log.d(TAG3, "ROW"+serial_no +"#"+serial_no);
                        UID = snapshot1.getKey();

                        int finalSerial_no = serial_no;
                        int finalSerial_no1 = serial_no;
                        user_profile_ref.child(UID).addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot snapshot) {
                                String u_name,u_phn;
                                if (snapshot.exists()){
                                    u_name = (String) snapshot.child("name").getValue();
                                    u_phn = (String) snapshot.child("phone").getValue();
                                    Log.d(TAG2, "USERNAME "+u_name+"\tPHONE "+u_phn+"of "+UID);
                                    body_table.addCell(new Cell().add(new Paragraph(String.valueOf(u_name)))
                                            .setBorder(Border.NO_BORDER)

                                            .setBackgroundColor(ColorConstants.WHITE)
                                            .setFontColor(ColorConstants.BLACK)
                                            .setTextAlignment(TextAlignment.CENTER)
                                    );
                                    body_table.addCell(new Cell().add(new Paragraph(String.valueOf(u_phn)))
                                            .setBorder(Border.NO_BORDER)

                                            .setBackgroundColor(ColorConstants.WHITE)
                                            .setFontColor(ColorConstants.BLACK)
                                            .setTextAlignment(TextAlignment.CENTER)
                                    );
                                    table_helper_obj.setName(u_name);
                                    table_helper_obj.setPhn(u_phn);

                                    Log.d(TAG3, "ROW"+ finalSerial_no +"Name"+ u_name);
                                    Log.d(TAG3, "ROW"+ finalSerial_no +"PHONE"+ u_phn);
                                }else{
                                    Toast.makeText(getApplicationContext(), "USER_DETAILS FOR PDF NOT FOUND", Toast.LENGTH_SHORT).show();
                                }
                            }
                            @Override
                            public void onCancelled(@NonNull DatabaseError error) {

                            }
                        });

                        Query q1 = this_cls_data_ref.child(UID).orderByValue().equalTo("PRESENT");
                        int finalSerial_no2 = serial_no;

                        q1.addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot snapshot) {
                                int total_present_no;
                                total_present_no = (int)snapshot.getChildrenCount();

                                body_table.addCell(new Cell().add(new Paragraph(String.valueOf(total_present_no))).setBorder(Border.NO_BORDER).setBackgroundColor(ColorConstants.WHITE).setFontColor(ColorConstants.BLACK).setTextAlignment(TextAlignment.CENTER));

                                table_helper_obj.setTotal_present(String.valueOf(total_present_no));
                                Log.d(TAG3, "ROW"+ finalSerial_no2 +"TOTAL PRESENT"+String.valueOf(total_present_no));
                                float percentage = ((float) total_present_no / Float.parseFloat(total_cls_taken)) * 100;
                                body_table.addCell(new Cell().add(new Paragraph(String.valueOf(percentage))).setBorder(Border.NO_BORDER).setBackgroundColor(ColorConstants.WHITE).setFontColor(ColorConstants.BLACK).setTextAlignment(TextAlignment.CENTER));

                                table_helper_obj.setPercentage(String.valueOf(percentage));
                                Log.d(TAG3, "ROW"+ finalSerial_no2 +"PERCENTAGE"+percentage);
                            }

                            @Override
                            public void onCancelled(@NonNull DatabaseError error) {

                            }
                        });
                        serial_no++;

                    }
                 }
            else
                {
                Toast.makeText(ClassroomDashboard.this, "attadance data is empty for this classroom "+room_id, Toast.LENGTH_SHORT).show();
            }

            }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
            Toast.makeText(ClassroomDashboard.this, "unable to read attadance data node", Toast.LENGTH_SHORT).show();
        }
    });
   
    body_table.addCell(new Cell().add(new Paragraph("blimey")).setBorder(Border.NO_BORDER).setBackgroundColor(ColorConstants.WHITE).setFontColor(ColorConstants.BLACK).setTextAlignment(TextAlignment.CENTER));
    document.add(bg_pdf_img.setFixedPosition(0,0));
    document.add(header_pdf_img);
    document.add(header_table);
    document.add(body_table);

    document.close();

    Toast.makeText(this, "PDF created successfully in "+pdf_path, Toast.LENGTH_SHORT).show();
    return 1;
}
tripleee
  • 175,061
  • 34
  • 275
  • 318
  • You will have to ensure that all nested database calls are done before you close out the document. This becomes a lot easier if you isolate the database loading in a separate function with its own (simpler) callback, as shown here: https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Dec 31 '21 at 16:22
  • can you please guide me on how to use call back and how can i isolate database calls in a seperate function because that function can not return any value – Millennium Chowdhury Jan 02 '22 at 08:32
  • The question I linked shows how to define a custom callback, and how to them use that. Using it will be similar to how you already pass a `ValueEventListener` to the database now, it'll just typically be less code since you can tweak the custom callback to your specific use-case. --- If you're having a hard time making the approach from my linked answer work for you, edit your question to show what you've tried with that approach. – Frank van Puffelen Jan 02 '22 at 16:21
  • thanks a lot sir i have made it work – Millennium Chowdhury Jan 03 '22 at 17:40
  • Good to hear @Millenium. – Frank van Puffelen Jan 03 '22 at 17:50

0 Answers0