jpgerb
jpgerb

Reputation: 1120

Unable to use a returned variable

I've been playing with different methods of saving String arrays to SharedPreference. I have not found a good method yet, but I am trying to convert them in to a string separated by "," . Here is my problem, I am not sure how to use a return statement.. I know that a return ends the method and returns you back to your previous spot.

Here is my method I'm calling to create the string:

public static String convertArrayToString(String[] array){
    String str = "";
    for (int i = 0;i<array.length; i++) {
        str = str+array[i];
        // Do not append comma at the end of last element
        if(i<array.length-1){
            str = str+",";
        }
    }
    return str;
}

Once it returns back to onCreate, I'm trying to figure out how to save the "str" that is passed back. When I use the variable "str" it doesn't know what it is.

I'm looking for a simple explanation on how to use a returned variable if someone would please help. Thank you!

Upvotes: 0

Views: 49

Answers (1)

ashatte
ashatte

Reputation: 5538

The method returns a String once it has finished executing. So inside onCreate, define a new String variable to store the result of that method:

String result = convertArrayToString(someArray);

Read more about return values here, and variable scope here.

Upvotes: 3

Related Questions