How to Get Value from JSON in Firebase Remote Config
Asked Answered
R

2

6

I am a novice to Android app development and Firebase.

I want to know how can I get the value (String & Int) in the JSONArray file stored in Firebase Remote Config.

I use Firebase Remote Config with the final goal to compare my app's version code and priority level with the one stored in Firebase Remote Config to determine the initiation of App Update notification, but so far I am still unable to get the Remote Config value.

I tried to parse the JSON using Volley (jsonParse in MainActivity2 class), but it also didn't work. (Error bad URL)

I have several times tried to implement previous answers, but maybe because of my misunderstanding, all those came to no avail.

Can I declare an array to Firebase Remote config?

Can I get JSONObject from Default value of Firebase Remote Config

FirebaseRemoteConfig getString is empty

I also have read this interesting article about implementing in-app update notifications with some specific criteria using Remote Config, but unfortunately for me, the codes are written in Kotlin.

https://engineering.q42.nl/android-in-app-updates/

test_json file stored in Firebase Remote Config.

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

MainActivity2 class

        remoteConfig = FirebaseRemoteConfig.getInstance();
        FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
                .setFetchTimeoutInSeconds(2000)
                .build();
        remoteConfig.setConfigSettingsAsync(configSettings);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                remoteConfig.fetchAndActivate().addOnCompleteListener(new OnCompleteListener<Boolean>() {
                    @Override
                    public void onComplete(@NonNull Task<Boolean> task) {
                        if (task.isSuccessful()) {
                            String object = remoteConfig.getString("test_json");
                            //jsonParse(object);
                            Gson gson = new GsonBuilder().create();
                            ArrayList<Lessons> lessons = gson.fromJson(object, 
                                 new TypeToken<List<Lessons>>(){}.getType());

                        } else {
                            Toast.makeText(MainActivity2.this, "Fetch Failed!", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });

        private void jsonParse(String object) {
                JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, object, null,
                    new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray = response.getJSONArray("condition");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject condition = jsonArray.getJSONObject(i);

                                String versionCode = condition.getString("versionCode");
                                int priorityLevel = condition.getInt("priorityLevel");

                                textView.append(versionCode + "\n\n");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

        mQueue.add(request);
    }

Lessons class

public class Lessons {
    String versionCode;
    Int priorityLevel;
}

Any help would be greatly appreciated.

Thank you.

Roller answered 17/11, 2021 at 21:57 Comment(5)
When you log remoteConfig.getString("test_json") itself, what do you see?Capacitance
@Capacitance Hi, I have modified test_json file so it is shaped as an array. Now, how can I extract the value (String & Int) from the method above?Roller
why does Lessons class contain ` String lesson;` ? it only has 2 fields in the jsonChristian
@Christian Sorry. I have updated the MainActivity2 class.Roller
@Christian But I still can not get the data from the method above. Any other codes I should insert?Roller
B
4

For me worked like that

import com.google.gson.annotations.SerializedName

data class VersionData(
    @SerializedName("name")
    val name: String,
    @SerializedName("age")
    var age: Int,
    @SerializedName("isFemale")
    var isFemale: Boolean
)

init {
    remoteConfig.fetchAndActivate()
}

private val _mutableLiveData = MutableLiveData<VersionData>()
val remoteLiveData: LiveData<VersionData> = _mutableLiveData
fun remoteConfiguration() {
    val gson = Gson()
    val remote = remoteConfig.fetchAndActivate()
    remote.addOnSuccessListener{
        val stringJson = remoteConfig.getString("json_object_name")
       if(stringJson.isNotEmpty()){
         val jsonModel = gson.fromJson(stringJson, VersionData::class.java)
          _mutableLiveData.value = VersionData(
              name = jsonModel.name,
              age = jsonModel.age,
              isFemale = jsonModel.isFemale
          )
       }else{
          // probably your remote param not exists
        }           
    }
}

so observe in compose

val localLifecycle = LocalLifecycleOwner.current
myViewModel.remoteLiveData.observe(localLifecycle){
 Log.d("remoteLiveData", "remoteLiveData: $it")
}

enter image description here

Barboza answered 7/10, 2022 at 0:4 Comment(2)
Great example. Thanks. What do I do if my json is a simple collection of country codes? ["AE", "SE", "US"]. How do I define that in VersionData, please?Herzig
Never mind, it seems I can just do val jsonModel = gson.fromJson(countriesJson, ArrayList::class.java), and won't need to define VersionData.Herzig
P
1

I recommend you use Gson.

data class Lessons(
    val versionCode: String? = null,
    val priorityLevel: Int? = null
)

and then, use getValue() or getString() to get the data.

val list = Gson().fromJson(getValue("test_json").asString(), Array<Lessons>::class.java)

In my case, getString() also worked.

val list = Gson().fromJson(getString("test_json"), Array<Lessons>::class.java)

This is simpler.

Popularity answered 27/3, 2022 at 9:51 Comment(1)
Hi. Thank you for your answer. Let me try it.Roller

© 2022 - 2024 — McMap. All rights reserved.