vendredi 17 janvier 2020

Need help in generating a random number that doesn't exist in my preference

I need to generate a random number to use as request code for my pending intent, to use in alarm manager. The random number needs to be unique. I generate a unique number then check it if it exists in my hashmap I have used in my shared preference. If the number exists in the preference, I generate a different random number. I have used the following code for that:

 private int getRandNum() {
      // create instance of Random class
      Random rand = new Random();
      int requestCode;

      // Generate random integers in range 0 to 999
      requestCode = rand.nextInt(1000);

      HashMap<String, DataObject> map = preferencesHelper.getTaskDetails();
      if (map != null) {
          if (!map.isEmpty()) {
              for (Map.Entry<String, DataObject> stringLongEntry : map.entrySet()) {
                  DataObject dataObject = stringLongEntry.getValue();


                  if (requestCode == dataObject.getRequestCode()) {
                      requestCode = getRandNum();
                  }

              }

          }
      }
      return  requestCode;
  }

I'm trying to implement the functionality of cancelling the alarm on click of button. What is happening is that a different alarm gets cancelled when I implement the cancel functionality on click of button. I was wondering if that had something to do with generating a unique request code.

Please help me fix that.




Aucun commentaire:

Enregistrer un commentaire