【问题标题】:Looping through lists while passing values to a function在将值传递给函数时循环遍历列表
【发布时间】:2019-01-01 15:28:59
【问题描述】:

编辑:

我有包含多个值的列表,我正在尝试遍历这些值并将它们作为参数传递给函数。但是,只有一个值被传递给该方法。

这是我目前所拥有的:

for (x = 0; x < time.length; x++) 
    {
      checkTime(time[x], x);
    }

我不确定我错过了什么。

这是我传递值的函数:

 public void checkTime(String time, int channel){
     //displayNotif is a function that displays notifications to the user
     //the format is displayNotif(channel, message, title)
     displayNotif(channel, "The time is: " + time, "Time Notification"); }

由于它可能发生得如此之快,我尝试传递另一个动态值以确保通过不同渠道显示通知,但我仍然只收到一个输出/通知。

public void displayNotif(Integer c, String msg, String title){
            notificationChannel();
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, TIME_CHANNEL);
            builder.setSmallIcon(R.drawable.ic_sms_notif);
            Bitmap bit = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
            builder.setLargeIcon(bit);
            builder.setContentTitle(title);
            builder.setContentText(msg);
            builder.setStyle(new NotificationCompat.BigTextStyle()
                    .bigText(msg));
            builder.setPriority(NotificationCompat.PRIORITY_MAX);
            builder.setAutoCancel(true);
            NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
            notificationManagerCompat.notify(s, builder.build());
        }

我也尝试了以下方法,它显示了所有值:

for (x = 0; x < time.length; x++) 
    {
      displayNotif(x, "Time is: " + time[x], "Time");
    }

【问题讨论】:

  • 实际和预期的行为是什么?
  • 尝试记录 time.length 值以查看是否导致问题
  • 时间数组的实际大小是多少。数组的大小可能是一个
  • 那个值总是最后一个值吗?
  • 预期行为是所有值都应通过循环传递给函数,以便函数可以返回/显示输出。我通过吐司显示了time.length的值,值是正确的。

标签: java android loops arraylist


【解决方案1】:

我确信还有其他方法可以解决此问题,但目前我的解决方案似乎还可以。顺便说一句,感谢所有回答我问题的人。

这就是我所做的:

  1. 我将列表传递给函数内部循环遍历值并将它们一一传递给函数。 //时间是列表 checkTime(时间);

  2. 我在函数内部做了循环,得到了我需要的结果。

这是我的代码:

public void checkTime(String[] time)
{
   for(int x = 0; x < time.length; x++){
   displayNotif(x, "The time is: " + time[x], "Time Notification");      
   }         
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    • 2018-02-02
    • 2021-12-10
    • 2016-07-19
    • 2022-11-12
    相关资源
    最近更新 更多