Can I declare an array to Firebase Remote config?
Asked Answered
G

6

29

I am a novice to Android and Firebase. Is it possible to declare an array inside the the Parameter key of Firebase Remote Config? enter image description here

I want to provide some promotions to some specific models/mobile devices. So if I could declare an array of models(i,e, Samsung J5, Xiaomi Note2 etc) I could easily enable promotions on those models. Please help me.

Grover answered 13/2, 2017 at 10:34 Comment(4)
You can pass it as a string and later convert to array in client side by splitting it.Retaretable
I would recommend to add a new pair of parameter - value like this: Parameter key:model_for_promotion Value: Samsung J5, Xiaomi Note2.Pungy
@Dexter, you mean I need to add parameters for every single model ?Grover
@Pungy , got some idea from your suggestion. Let me try first. thnxGrover
G
39

The Remote Config has recently added the option to save a key-value list by saving it to a JSON format.

enter image description here

Sample usage:

1.Json stored in Remote Configs:

 [
      {
        "lesson": "1",
        "versionCode": 2
      },
      {
        "lesson": "2",
        "versionCode": 4
      },
      {
        "lesson": "3",
        "versionCode": 1
      }
 ]

2.Kotlin model

data class Lesson(val lesson: Int, val versionCode: Int)

3.Retrieve json

String object = FirebaseRemoteConfig.getInstance().getString("test_json");
Gson gson = new GsonBuilder().create();
List<Lesson> lessons = gson.fromJson(object, new TypeToken<List<Lesson>>(){}.getType());
Groyne answered 20/1, 2019 at 18:55 Comment(7)
How should I read it? String? Value? ByteArray? key : ARRAY_CODE value: {"leccion":"1","versionCode":2} mFirebaseRemoteConfig.getString(ARRAY_CODE);Boiler
I tried to read as String but I could not parse it correctly? Do you have the code that you are using to parse String to JSON, how are you extracting the difference objects? Example: [{"lesson":"1","versionCode":2}, {"lesson":"2","versionCode":4} , {"lesson":"3","versionCode":1}]Boiler
@Boiler I have updated my answer with sample usage of your exampleGroyne
@Groyne Can you please kindly elaborate more? I use Java and List<Lesson> cannot be resolved in Android Studio. Should I create Lesson class first?Sightly
Yes, you should first create Lesson class in Java similar to what I posted for Kotlin (just use Java language instead of Kotlin) @SightlyGroyne
@Groyne I have posted a quite similar question. Please kindly have a look. #70012580Sightly
To call a String "object" is a really bad practice and make the code hard to read and wrong in Kotlin.Static
A
14

All of the values in Firebase Remote Config are ultimately stored as strings. Booleans, numbers, etc, are all boiled down to strings. The SDK will just parse that string value when you ask for as some other type.

There are no "native" arrays in Remote Config. If you want a series of ordered values in a Remote Config parameter, you should represent it in a way that can be parsed from the string value (such as JSON or some simple delimited strings).

Aholla answered 13/2, 2017 at 16:34 Comment(0)
C
5

Same as Doug's answer, but with code.

This is in Swift, but you should still get the drift.

For arrays, use a delimited string e.g.

"iron,wood,gold" and split it into an array of string using .components(separatedBy: ",")

For dictionaries, use a "doubly" delimited string e.g.

"iron:50, wood:100, gold:2000"

convert it into a dictionary using

    var actualDictionary = [String: Int]()

    // Don't forget the space after the comma
    dictionaryString.components(separatedBy: ", ").forEach({ (entry) in
    let keyValueArray = entry.components(separatedBy: ":")
            return actualDictionary[keyValueArray[0]] = Int(keyValueArray[1])
    })

    return actualDictionary
Chime answered 22/11, 2017 at 12:42 Comment(0)
C
2

I like N Kuria's answer, but that requires the whitespace in your json to be exact. If you want something a little more fault tolerant, here is code to read in an array of ints via JSONSerialization.

Let's say you had this array of ints in your json:

 {
     "array": [1, 5, 4, 3]
 }
func getArray() -> [Int] {

    let jsonString = "{\"array\": [1, 5, 4, 3]}"
    let array = [Int]()

    guard let data = jsonString.data(using: .utf8) else { return array }
    if let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) {
        guard let theArray = json as? [String: [Int]] else { return array }
        return theArray.first?.value ?? array

        // If you were reading in objects instead of ints, you would do
        // for (key, value) in theArray { /* append values to array */ }
    }

    return array
}

Alternatively, if you were reading in values of a class type, you could just enumerate the dictionary and append to an array with each iteration. (See the comment beneath the first return.)

Carpo answered 8/3, 2019 at 18:57 Comment(0)
V
0

Firebase stores arrays as objects with integers as key names. You can get an array returned from remote config if you use the Data Type JSON and use an object with sequential keys. For example...

Default Value:

{
  "0": "A",
  "1": "B",
  "2": "C",
  "3": "D",
}

Gets returned as ["A","B","C","D"]

Note they have to be sequential keys! So if the value was:

{
  "0": "A",
  "2": "B",
  "3": "C",
  "4": "D",
}

It would get returned as ["A", undefined, "B", "C","D"]

You can read more about Arrays in Firebase here => https://firebase.blog/posts/2014/04/best-practices-arrays-in-firebase

Viole answered 23/3, 2022 at 20:47 Comment(0)
B
-1

I would also recommend JSON - as you can have some sort of error detection in parsing the JSON. With splitting, you'll never know if that resulted into a correct array.

Branks answered 18/12, 2017 at 18:31 Comment(1)
this has to be given as a comment,not an answer ... so downvotingDeccan

© 2022 - 2024 — McMap. All rights reserved.