Есть ли способ включить i + 1 в a для l oop в функции класса трансляции? - PullRequest
1 голос
/ 27 января 2020

Я пытаюсь провести l oop через строковый массив, содержащий числа, и проанализировать эти значения в целочисленную коллекцию, отображающую возвращаемое значение в широковещательную рассылку, например, «Работа из ---, возвращаемое значение».

Я разбил строку на строковый массив с помощью .split(',') и попытался l oop через этот массив при анализе значений строки в целые числа. Я могу получить возвращаемое значение из for l oop, если смогу напрямую ввести индекс parseInt(FilterDataValues[1]) или любой индексированный индекс, но как только я добавлю i parseInt(FilterDataValues[i+1]) или parseInt(FilterDataValues[i]), я не смогу получить возвращаемое значение. L oop прекрасно работает в более простом l oop, поэтому я не слишком уверен, что происходит. Пожалуйста, помогите мне любая помощь будет хорошо

 public String sortingList(Context context)
    {
        String filterData = "";
        StimulusDatabase td = new StimulusDatabase(context);

        Cursor result = td.getAllData();
        while (result.moveToNext())
        {
            filterData = (result.getString(23));
        }

        if(filterData.isEmpty())
        {
            return "";
        }
        else
        {
            String[] FilterDataValues = filterData.split(",");

            for(int i = 0; i <= FilterDataValues.length; i++)
            {
                FilterOptions.add(parseInt(FilterDataValues[i+1]));
            }

//            for(int i = 0; i <= FilterDataValues.length; i++)
//            {
//                FilterOptions.add(i+1));
//            }

            return filterData;
        }
    }

Вывод всего кода не приводит к появлению уведомления даже через 20/30 минут

Вывод при использовании закомментированного кода (0 2,6 являются индексами столбцов)

A word from Martin Luther King Jr
0,2,6

Весь класс ниже

package com.example.MentalHealthStateManagement.Application.Notifications;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.util.Log;

import com.example.MentalHealthStateManagement.Application.Database.StimulusDatabase;
import com.example.MentalHealthStateManagement.R;
import com.example.MentalHealthStateManagement.StateHandler.CheckIn;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import androidx.core.app.NotificationManagerCompat;

import static java.lang.Integer.parseInt;

public class Trigger_Receiver extends BroadcastReceiver
{
    private static final String CHANNEL_ID = "M.H.S.M daily check-in registry";
    private static final String TAG = "Trigger Receiver: ";

    private String[] authors;
    private String sortStatement;
    private List<Integer> FilterOptions = new ArrayList<>();
    private int notificationID = 135;

    @Override
    public void onReceive(Context context, Intent intent)
    {
        sortStatement = sortingList(context);
        authors = getAuthors(context).split("#");
        String[] quotes = getQuotes(context).split("#");

        int randomNum = randomPosition();

        // Create an exclusive intent for the user's daily check-in
        intent = new Intent(context, CheckIn.class);

        // Create the TaskStack Builder and add the Main Activity, which inflates the back stack
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addNextIntentWithParentStack(intent);
        PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

        // Checks if the API Level is 26 or greater
        Notification.Builder notification = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            notification = new Notification.Builder(context, CHANNEL_ID)
                    .setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
                    .setContentTitle("A word from " + authors[randomNum])
                    .setContentText(sortingList(context))//quotes[randomNum]
                    .setStyle(new Notification.BigTextStyle().bigText(sortingList(context)))
                    .setContentIntent(pendingIntent)
                    .setAutoCancel(true);
        }

        NotificationManagerCompat notificationManger = NotificationManagerCompat.from(context);
        assert notification != null;
        notificationManger.notify(notificationID, notification.build());
        notificationID++;
        Log.i("Trigger_Receiver", "Trigger successful");
    }

    //Gets the authors for the specified trigger
    public String getAuthors(Context context)
    {
        StringBuilder authors = new StringBuilder();
        StimulusDatabase td = new StimulusDatabase(context);
       // List<Integer> AuthorsToBeFiltered = NumberFilterValue;

        Cursor result = td.getAllData();

            while (result.moveToNext())
            {
                authors = new StringBuilder(result.getString(2) + " " + result.getString(4) + " "
                        + result.getString(6) + " " + result.getString(8) + " " +
                            result.getString(10) + " " + result.getString(12) + " "
                        + result.getString(14) + " " + result.getString(16) + " " +
                            result.getString(18) + " " + result.getString(20));
            }

//            while (result.moveToNext())
//            {
//                if(!AuthorsToBeFiltered.isEmpty())
//                {
//                    for(int i = 0; i<AuthorsToBeFiltered.size(); i++)
//                    {
//                        if(AuthorsToBeFiltered.get(i) % 2 == 0)
//                        {
//                            authors.append(result.getString(i));
//                        }
//                    }
//                }
//                else
//                {
//                    authors = new StringBuilder(result.getString(2) + " " + result.getString(4) + " " + result.getString(6) + " " + result.getString(8) + " " +
//                            result.getString(10) + " " + result.getString(12) + " " + result.getString(14) + " " + result.getString(16) + " " +
//                            result.getString(18) + " " + result.getString(20));
//                }
//            }

        return authors.toString();
    }

    //Gets the quotes for the specified trigger
    public String getQuotes(Context context)
    {
        StringBuilder quotes = new StringBuilder();
        StimulusDatabase td = new StimulusDatabase(context);
        //List<Integer> AuthorsToBeFiltered = NumberFilterValue;

        Cursor result = td.getAllData();

                while (result.moveToNext())
                {
                    quotes.append(result.getString(1)).append(" ").append(result.getString(3))
                            .append(" ").append(result.getString(5)).append(" ").append(result.getString(7))
                            .append(" ").append(result.getString(9)).append(" ").append(result.getString(11))
                            .append(" ").append(result.getString(13)).append(" ").append(result.getString(15))
                            .append(" ").append(result.getString(17)).append(" ").append(result.getString(19));
                }

//            while (result.moveToNext())
//            {
//                if(!AuthorsToBeFiltered.isEmpty())
//                {
//                    for(int i = 0; i<AuthorsToBeFiltered.size(); i++)
//                    {
//                        if(AuthorsToBeFiltered.get(i) % 2 == 0)
//                        {
//                            quotes.append(result.getString(i-1));
//                        }
//                    }
//                }
//                else
//                {
//                    quotes.append(result.getString(1)).append(" ").append(result.getString(3))
//                            .append(" ").append(result.getString(5)).append(" ").append(result.getString(7))
//                            .append(" ").append(result.getString(9)).append(" ").append(result.getString(11))
//                            .append(" ").append(result.getString(13)).append(" ").append(result.getString(15))
//                            .append(" ").append(result.getString(17)).append(" ").append(result.getString(19));
//                }
//            }

        return quotes.toString();
    }

    //A random number used to gather different quotes and authors
    //P.S. each quote belongs to appropriate author due to the delimiter settings preformed in the StimulusSetup class
    public Integer randomPosition()
    {
        int randomNum = 0;
        // Ensures the API level 26 or greater
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        {
            randomNum = ThreadLocalRandom.current().nextInt(0, authors.length + 1);
        }
        else
        {
            Log.d(TAG,"Incompatible device, API lower than lollipop");
        }
        return randomNum;
    }

    public String sortingList(Context context)
    {
        String filterData = "";
        StimulusDatabase td = new StimulusDatabase(context);

        Cursor result = td.getAllData();
        while (result.moveToNext())
        {
            filterData = (result.getString(23));
        }

        if(filterData.isEmpty())
        {
            return "";
        }
        else
        {
            String[] FilterDataValues = filterData.split(",");

            for(int i = 0; i <= FilterDataValues.length; i++)
            {
                FilterOptions.add(parseInt(FilterDataValues[i+1]));
            }

//  `         Working loop
//            for(int i = 0; i <= FilterDataValues.length; i++)
//            {
//                FilterOptions.add(i+1));
//            }

            return filterData;
        }
    }
}

1 Ответ

0 голосов
/ 27 января 2020

Обратите внимание, что в l oop вы звоните

FilterOptions.add(parseInt(FilterDataValues[i+1]));

, что должно завершиться с ошибкой в ​​последнем целом числе l oop, потому что будет попытка чтения значения с позиции, которая не существует в этом массиве. Я думаю, вы можете найти IndexOutOfBoundException в LogCat.

Это, вероятно, причина того, почему вы не можете получить возвращаемое значение, так как метод должен вызывать исключение.

...