androiduser-interfaceerror-handling

Error Handling for Programmatically Created UI Elements in Android


I am developing an Android application that uses multiple UI elements (e.g., Button, TextView, etc.), and I want to perform error handling for these elements. (Note: These elements aren't created using XML files; everything is done programmatically.)

For example, while setting the Font Variation Settings for any TextView here, they have clearly mentioned that if it fails to set it will raise the Exception.

Similarly when I am trying to create the UI elements which when created programmatically something as shown below:

public fun CreateObject (pContext : Context) : Unit
{
    val button_elem : Button
   
    // If this call fails how should this be taken care of? 
    button_elem = Button (pContext) // Please consider the context as not null 
}

It's a constructor it will not return any value, but it might throw some exception in some rare scenario (for example Out of memory) but nothing such is mentioned in the document here.

Or does Android guarantee that these APIs will never fail? Require some detailed answers to these questions?


Solution

  • Or does Android guarantee that these APIs will never fail?

    No. Almost every line of your code could fail, such as with the OutOfMemoryError that you cite.

    // If this call fails how should this be taken care of?

    Let the app crash. If you get an OutOfMemoryError when trying to instantiate a Button, your process' heap is beyond repair, and anything else that you try to do will also trigger OutOfMemoryErrors.