0

I have a recursive function, but I would like to add (and save) previous data in a ArrayList.

I am currently doing this but it doesn't save:

  private ArrayList<String> checkNextPage(String urlGoogleToken){

    ArrayList<String> listTokenFunction = new ArrayList<String>();

    try
    {
        /* I AM DOING SOME STUFF */

        if (jsonObj.has("next_page_token")){
            String next_page_token = (String) jsonObj.get("next_page_token");
            listTokenFunction.add(next_page_token); // I WANT TO SAVE THIS LIST
            String result = urlGoogleToken.split("&pagetoken=")[0];
            String urlGoogleMaps2 = result+"&pagetoken="+next_page_token; 
            checkNextPage(urlGoogleMaps2); // CALL THE FUNCTION
        } else {
            System.out.println("ELSE");
        }
    } catch (Exception e) {
            e.printStackTrace();
       }

    return listTokenFunction;
}

Thanks for your help!

2 Answers 2

2

In your code, each recursive call to the method is creating its own ArrayList as a local variable. One way to solve this problem is changing the method so that it takes an (initially empty) ArrayList as input and fills it. Each recursive call will take the list as input and add to it.

private void checkNextPage(ArrayList<String> listTokenFunction, String urlGoogleToken){

   // initialize if null
   if(listTokenFunction == null) {
       listTokenFunction = new ArrayList<String>();
   }

   try
   {
       /* I AM DOING SOME STUFF */

       if (jsonObj.has("next_page_token")){
          String next_page_token = (String) jsonObj.get("next_page_token");
          listTokenFunction.add(next_page_token); // I WANT TO SAVE THIS LIST
          String result = urlGoogleToken.split("&pagetoken=")[0];
          String urlGoogleMaps2 = result+"&pagetoken="+next_page_token; 
          checkNextPage(urlGoogleMaps2, listTokenFunction); // CALL THE FUNCTION
       } else {
          System.out.println("ELSE");
       }
   } catch (Exception e) {
          e.printStackTrace();
   }

}

The method can have a void return type since the list will be filled internally and there is no need to return it.

Sign up to request clarification or add additional context in comments.

Comments

2

You create a new ArrayList within your method. ArrayList<String> listTokenFunction = new ArrayList<String>();, so the 'old' list is lost and when you ad an entry, it will always be the first one. Try initializing that Arraylist outside of your method as a class variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.