Home » Android » android – What's the difference between TypedArray.getInteger() and TypedArray.getInt()?

android – What's the difference between TypedArray.getInteger() and TypedArray.getInt()?

Posted by: admin June 16, 2020 Leave a comment


Looking at the source code for TypedArray (link), I cannot seem to figure out what the difference between these two methods is. getInt() is basically the same as getInteger(), but with a small addition at the end that I don’t understand. Can someone explain it to me?

The reason I need to know the difference is I am implementing a custom Preference subclass, and to get the default value I need to override onGetDefaultValue(), which grabs an integer from a TypedArray. Example:

protected Object onGetDefaultValue(TypedArray a, int index)
    return a.getInteger(index, DEFAULT_VALUE);

Here I’m using getInteger(), but if getInt() is better, then I will use that.

How to&Answers:

They simply have different “all else fails” cases. They both return an int for a valid int and defValue for null. The difference is how they handle the case of neither of those.

From the link:

 * Copyright (C) 2008 The Android Open Source Project
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * See the License for the specific language governing permissions and
 * limitations under the License.

TypedValue v = mValue;
if (getValueAt(index, v)) {
    Log.w(Resources.TAG, "Converting to int: " + v);
    return XmlUtils.convertValueToInt(
        v.coerceToString(), defValue);
Log.w(Resources.TAG, "getInt of bad type: 0x"
      + Integer.toHexString(type));
return defValue;

This is the extra you are referring to. It appears to be converting an unknown value to a string then to an integer. This could be useful if you had "12" or some equivalent value stored.

Additionally getInteger throws an exception if it is not null and not an int. In contrast if all else fails getInt returns the default value.

Also note that the behavior of them in this odd case is different enough that calling one superior to the other in every case would be incorrect. The best solution is the one that matches your expectations for failure.