Home > Software engineering >  Android context not getting the right localization resource
Android context not getting the right localization resource

Time:12-29

Description: I have an app that adds saves and displays Activity objects, and displays a Toast message on doing so. I also have two languages that the program operates with, for which resource files have been provided.

Problem: Translation works perfectly for all UI elements, except the Toast messages that I display on success. I'm giving it an application context, but if I switch the language, it will end up displaying the Toast in the other language, while the other UI is using the proper language. The resources don't contain the same string for both languages. What am I doing wrong?

Here's a section of the Activity saving code:

 private void uploadActivities(FirebaseFirestore db, ArrayList<ActivityModel> activities) {
        for (int i = 0; i < allRecurringActivities.size(); i  ) {
            db.collection("Project").document(Prefs.getString("iD",
                    GlobalObject.FIRESTORE_ID))
                    .collection("activities")
                    .document(activities.get(i).getId())
                    .set(activities.get(i))
                    .addOnSuccessListener(unused -> {
                        Toast.makeText(context, ""  
                                context.getApplicationContext().getResources().getString(R.string.success)  
                                "!", Toast.LENGTH_SHORT).show();
                        for (ActivityModel allRecurringActivity : allRecurringActivities) {
                            AlarmUtils.setAlarm(context, allRecurringActivity);
                        }
                            }
                    )
                    .addOnFailureListener(e -> Log.d("uploadActivities", "FAILED"));
        }
    }

CodePudding user response:

Use an Activity as a Context for user-facing elements such as strings, not Application.

Many resource-overriding mechanisms such as in-app language switchers work by updating the resources in the Activity. Other Contexts are not updated. It's not evident in the question that you are using in-app language switching (though that would explain the behavior) - without that an Application also would access the same resources. But generally, Activity is the right context to use for user interfaces.

  • Related