0
votes

How to auto increment unique number in android studio using firebase real-time database Like unique id : HDTICKET00001, HDTICKET00002 HDTICKET00003

Now changed unique id format to eg.HDTICKET5000001,HDTICKET5000002

This code working with system emulator perfectly

if used physical device as emulator first ticket generated correctly after app automatically closed

How to solve the same..

firebaseDatabase = FirebaseDatabase.getInstance(); databaseReference = firebaseDatabase.getReference(); Query query = databaseReference.child("TICKET_DETAIL").orderByChild("TICKET_NO").limitToLast(1); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {

                        if (snapshot.getValue()!=null){

                            String reslt = snapshot.getValue().toString();
                            String [] role = reslt.split(",");
                            String tiketno = role[4];

                            String [] ref = tiketno.split("HDTICKET",2);

                            int number = Integer.parseInt(ref[1])+1;                               


                            final String Tktno = "HDTICKET"+number;

                            HashMap<String,Object> hashMap = new  HashMap<>();
                            hashMap.put("TICKET_NO",Tktno);
                            hashMap.put("TICKET_DATE",ticketdt);
                            hashMap.put("UID",usrid);
                            hashMap.put("MESSAGE",msg);
                            hashMap.put("TICKET_STATUS",ticktstatus);
                            hashMap.put("DONE_BY",doneby);
                            hashMap.put("CLOSED_DATE",donedate);

                            databaseReference.child("TICKET_DETAIL")
                                    .child(Tktno)
                                    .setValue(hashMap)
                                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                                        @Override
                                        public void onSuccess(Void unused) {
                                            //Toast.makeText(RaiseTicket.this, "Ticket Generated successfully", Toast.LENGTH_SHORT).show();
                                            RaiseTicket.this.finish();
                                            Intent sucess = new Intent(RaiseTicket.this, RaiseTicketsuccess.class);
                                            String user =  Tktno;
                                            sucess.putExtra("TICKET#",user);
                                            startActivity(sucess);
                                        }
                                    })
                                    .addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull @NotNull Exception e) {
                                            Toast.makeText(RaiseTicket.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    });
                        } else {

                            final String Tktno = "HDTICKET5000001";
                            HashMap<String,Object> hashMap = new  HashMap<>();
                            hashMap.put("TICKET_NO",Tktno);
                            hashMap.put("TICKET_DATE",ticketdt);
                            hashMap.put("UID",usrid);
                            hashMap.put("MESSAGE",msg);
                            hashMap.put("TICKET_STATUS",ticktstatus);
                            hashMap.put("DONE_BY",doneby);
                            hashMap.put("CLOSED_DATE",donedate);

                            databaseReference.child("TICKET_DETAIL")
                                    .child(Tktno)
                                    .setValue(hashMap)
                                    .addOnSuccessListener(new OnSuccessListener<Void>() {
                                        @Override
                                        public void onSuccess(Void unused) {
                                            //Toast.makeText(RaiseTicket.this, "Ticket Generated successfully", Toast.LENGTH_SHORT).show();
                                            RaiseTicket.this.finish();

                                            Intent sucess = new Intent(RaiseTicket.this, RaiseTicketsuccess.class);
                                            String user =  Tktno;
                                            sucess.putExtra("TICKET#",user);
                                            startActivity(sucess);
                                        }
                                    })
                                    .addOnFailureListener(new OnFailureListener() {
                                        @Override
                                        public void onFailure(@NonNull @NotNull Exception e) {
                                            Toast.makeText(RaiseTicket.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    });
                        }
                    }
                    @Override
                    public void onCancelled(@NonNull @NotNull DatabaseError error) {

                    }
                });
2
I heavily discourage the use of incremental IDs if anything, they should be a place holder as a property of the object, not the parent identifier which should be a unique IDDIGI Byte

2 Answers

1
votes

There is no build in method to to it. Also don't use such values as keys in your lists. If you need such incremental numbers build your own logic for it. The best way is to use a cloud function and add the incremental field when a new element in the list is created.

I can show you here an example from our company where we need incremental numbers for your logistic tasks and a prefix leter before them. Here is the code:

if (!eventSnapshot.child("cmr").exists()) {
  ////console.log(`No cmr in task!`)
  const lastCMRRef = admin.database().ref(`/cmr/${terminalUid}`);

  lastCMRRef
    .transaction((number) => {
      return (number || 0) + 1;
    })
    .then(({ committed, snapshot }) => {
      if (committed) {
        const cmr = snapshot.val();
        const formatedCMR = `${terminal.name}${`000000${cmr}`.slice(-6)}`;

        let update = { cmr: formatedCMR };

        return eventSnapshot.ref.update(update);
      }
    });
}

It's reduced here just for the incrementing. Don't frget that it is running in a cloud function. That way we automate the process regardless of the backend. The only downside is that it has a little bit of lag between creation and getting that incremental number.

Important is to use a transaction for increasing the incremental value.

0
votes

Founded the Error This error happening in the code of arraying String tiketno = role[4]; because this code arraying result place is 4th in the system emulator but physical device arraying place is 5th Now i have changed to String tiketno = role[5]; it's working good..