android.content.res.Resources$NotFoundException: String resource ID #0x1

2023-11-13

在Android开发中如果出现android.content.res.Resources$NotFoundException: String resource ID #0x1这样的错误,你想也不用想,一定是Textview控件显示数据出了问题:mTextview.setText(这里的传入的数据一定写成int类型了)。我们需要做的是eg:mTextview.setText(1+""),也就是参数转化成字符串,接下来我们看一源码:


如果控件TextView添加的数据写成 eg:mTextview.setText(1)时,也就是传入的是数字,源码分析如下:

/**
 * Sets the text to be displayed using a string resource identifier.
 *
 * @param resid the resource identifier of the string resource to be displayed
 *
 * @see #setText(CharSequence)
 *
 * @attr ref android.R.styleable#TextView_text
 */
@android.view.RemotableViewMethod
public final void setText(@StringRes int resid) {
    setText(getContext().getResources().getText(resid));
    mTextFromResource = true;
}


从该方法的注释我们可以看到参数 resid要是一个string的类型。接着我们往下看getText():


/**
 * Return the string value associated with a particular resource ID.  The
 * returned object will be a String if this is a plain string; it will be
 * some other type of CharSequence if it is styled.
 * {@more}
 *
 * @param id The desired resource identifier, as generated by the aapt
 *           tool. This integer encodes the package, type, and resource
 *           entry. The value 0 is an invalid identifier.
 *
 * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
 *
 * @return CharSequence The string data associated with the resource, plus
 *         possibly styled text information.
 */
@NonNull public CharSequence getText(@StringRes int id) throws NotFoundException {
    CharSequence res = mResourcesImpl.getAssets().getResourceText(id);
    if (res != null) {
        return res;
    }
    throw new NotFoundException("String resource ID #0x"
            + Integer.toHexString(id));
}


 

上面的意思大概是:返回与特定资源ID相关联的字符串值。返回的对象将是一个字符串,如果这是一个普通的字符串;@param id :所需的资源标识符,由aapt工具生成。这个整数编码了包、类型和资源条目,值0是无效标识符。接着继续往下看类AssetManager:


 

 
/**
 * Retrieves the string value associated with a particular resource
 * identifier for the current configuration.
 *检索与特定资源相关联的字符串值当前配置的标识符。
 * @param resId the resource identifier to load
 * @return the string value, or {@code null}
 */
@Nullable
final CharSequence getResourceText(@StringRes int resId) {
    synchronized (this) {
        final TypedValue outValue = mValue;
        if (getResourceValue(resId, 0, outValue, true)) {
            return outValue.coerceToString();
        }
        return null;
    }
}

返回字符序列CharSequence。那么是如何 检索与特定资源相关联的字符串 值。

继续看源码:




 
/**
 * Populates {@code outValue} with the data associated a particular
 * resource identifier for the current configuration.
 *
 * @param resId the resource identifier to load
 * @param densityDpi the density bucket for which to load the resource
 * @param outValue the typed value in which to put the data
 * @param resolveRefs {@code true} to resolve references, {@code false}
 *                    to leave them unresolved
 * @return {@code true} if the data was loaded into {@code outValue},
 *         {@code false} otherwise
 */
final boolean getResourceValue(@AnyRes int resId, int densityDpi, @NonNull TypedValue outValue,
        boolean resolveRefs) {
    synchronized (this) {
        final int block = loadResourceValue(resId, (short) densityDpi, outValue, resolveRefs);
        if (block < 0) {
            return false;
        }

        // Convert the changing configurations flags populated by native code.
        outValue.changingConfigurations = ActivityInfo.activityInfoConfigNativeToJava(
                outValue.changingConfigurations);

        if (outValue.type == TypedValue.TYPE_STRING) {
            outValue.string = mStringBlocks[block].get(outValue.data);
        }
        return true;
    }
}

/** Returns true if the resource was found, filling in mRetStringBlock and
 *  mRetData. */
private native final int loadResourceValue(int ident, short density, TypedValue outValue,
        boolean resolve);

如果找到对应的资源,则返回true。在这里我们也看到了native方法,

肯定是c/c++去做事了,我们不去考虑。如果找不到返回null,

我们从如下代码就可以知道:



@Nullable
final CharSequence getResourceText(@StringRes int resId) {
    synchronized (this) {
        final TypedValue outValue = mValue;
        if (getResourceValue(resId, 0, outValue, true)) {
            return outValue.coerceToString();
        }
        return null;
    }
}


如果找到对应的资源,我们就经过一系列的方法转化成字符序列,

代码如下:


/**
 * Regardless of the actual type of the value, 
try to convert it to a
 * string value.  For example, a color type will be converted 
to a
 * string of the form #aarrggbb.
 * 
 * @return CharSequence The coerced string value.  
If the value is
 *         null or the type is not known, null is returned.
 */
public final CharSequence coerceToString()
{
    int t = type;
    if (t == TYPE_STRING) {
        return string;
    }
    return coerceToString(t, data);
}
    2.------------------------------------------

/**
 * Perform type conversion as per {@link #coerceToString()} on an
 * explicitly supplied type and data.
 * 
 * @param type The data type identifier.
 * @param data The data value.
 * 
 * @return String The coerced string value.  If the value is
 *         null or the type is not known, null is returned.
 */
public static final String coerceToString(int type, int data)
{
    switch (type) {
    case TYPE_NULL:
        return null;
    case TYPE_REFERENCE:
        return "@" + data;
    case TYPE_ATTRIBUTE:
        return "?" + data;
    case TYPE_FLOAT:
        return Float.toString(Float.intBitsToFloat(data));
    case TYPE_DIMENSION:
        return Float.toString(complexToFloat(data)) + DIMENSION_UNIT_STRS[
            (data>>COMPLEX_UNIT_SHIFT)&COMPLEX_UNIT_MASK];
    case TYPE_FRACTION:
        return Float.toString(complexToFloat(data)*100) + FRACTION_UNIT_STRS[
            (data>>COMPLEX_UNIT_SHIFT)&COMPLEX_UNIT_MASK];
    case TYPE_INT_HEX:
        return "0x" + Integer.toHexString(data);
    case TYPE_INT_BOOLEAN:
        return data != 0 ? "true" : "false";
    }

    if (type >= TYPE_FIRST_COLOR_INT && type <= TYPE_LAST_COLOR_INT) {
        return "#" + Integer.toHexString(data);
    } else if (type >= TYPE_FIRST_INT && type <= TYPE_LAST_INT) {
        return Integer.toString(data);
    }

    return null;
}
...........................


如果控件TextView添加的数据写成 eg:mTextview.setText(1+"")时,也就是传入的是字符串,源码分析如下:

next1.
/**
 * Sets the text to be displayed. TextView <em>does not</em> accept
 * HTML-like formatting, which you can do with text strings in XML resource files.
 * To style your strings, attach android.text.style.* objects to a
 * {@link android.text.SpannableString}, or see the
 * <a href="{@docRoot}guide/topics/resources/available-resources.html#stringresources">
 * Available Resource Types</a> documentation for an example of setting
 * formatted text in the XML resource file.
 * <p/>
 * When required, TextView will use {@link android.text.Spannable.Factory} to create final or
 * intermediate {@link Spannable Spannables}. Likewise it will use
 * {@link android.text.Editable.Factory} to create final or intermediate
 * {@link Editable Editables}.
 *
 * @param text text to be displayed
 *
 * @attr ref android.R.styleable#TextView_text
 */
@android.view.RemotableViewMethod
public final void setText(CharSequence text) {
    setText(text, mBufferType);
}


next2.

设置要显示的文本

/**
 * Sets the text to be displayed and the {@link android.widget.TextView.BufferType}.
 * <p/>
 * When required, TextView will use {@link android.text.Spannable.Factory} to create final or
 * intermediate {@link Spannable Spannables}. Likewise it will use
 * {@link android.text.Editable.Factory} to create final or intermediate
 * {@link Editable Editables}.
 *
 * @param text text to be displayed
 * @param type a {@link android.widget.TextView.BufferType} which defines whether the text is
 *              stored as a static text, styleable/spannable text, or editable text
 *
 * @see #setText(CharSequence)
 * @see android.widget.TextView.BufferType
 * @see #setSpannableFactory(Spannable.Factory)
 * @see #setEditableFactory(Editable.Factory)
 *
 * @attr ref android.R.styleable#TextView_text
 * @attr ref android.R.styleable#TextView_bufferType
 */
public void setText(CharSequence text, BufferType type) {
    setText(text, type, true, 0);

    if (mCharWrapper != null) {
        mCharWrapper.mChars = null;
    }
}

next3.

private void setText(CharSequence text, BufferType type,
                     boolean notifyBefore, int oldlen) {
    mTextFromResource = false;
    if (text == null) {
        text = "";
    }

    // If suggestions are not enabled, remove the suggestion spans from the text
    if (!isSuggestionsEnabled()) {
        text = removeSuggestionSpans(text);
    }

    ............

    .................

    .........


notifyViewAccessibilityStateChangedIfNeeded(AccessibilityEvent.CONTENT_CHANGE_TYPE_TEXT);

if (needEditableForNotification) {
    sendAfterTextChanged((Editable) text);
} else {
    // Always notify AutoFillManager - it will return right away if autofill is disabled.
    notifyAutoFillManagerAfterTextChangedIfNeeded();
}

// SelectionModifierCursorController depends on textCanBeSelected, which depends on text
if (mEditor != null) mEditor.prepareCursorControllers();

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

android.content.res.Resources$NotFoundException: String resource ID #0x1 的相关文章

随机推荐

  • 文件服务器如何保存,文件保存服务器

    文件保存服务器 内容精选 换一换 环境 centos jdk1 8 vsftpd nginx spring boot dockerftp上传附件 上传的附件有两种方式回显 在下面再详细说明此处省略ftp服务器 docker服务器nginx服
  • SQL模糊查询变量参数

    Transactional Modifying Query value select from 表名 where name like 1 nativeQuery true List
  • FindObjectOfType函数

    介绍 在Unity游戏引擎中 FindObjectOfType函数用于在场景中查找指定类型的单个活动对象 它可以通过提供类型参数来查找一个激活状态的场景对象 并返回第一个找到的对象实例 这个函数在需要查找某个特定类型的对象时非常有用 尤其是
  • BUG:阿里巴巴图标库引入链接后,icon有时候会不显示的话svg下载到本地使用

    忽然icon图标就不显示 但是代码 icon链接地址都没有发生变化 解决办法 将icon图标下载到本地 记住前后引用本地的名字要保持一致
  • C++中的代码重用与其他

    当初始化列表包含多个项目时 这些项目被初始化的顺序为他们被声明的顺序 而不是他们在初始化列表中的顺序 1 私有继承 使用私有继承 基类的公有成员和保护成员都将称为派生类的私有成员 使用公有继承 基类的公有方法将称为派生类的公有方法 使用私有
  • 开源框架RuoYi-Vue学习之集成redis/集成验证码

    1 请参见项目代码地址 文章目录 一 集成redis 二 验证码功能 图形验证码 数学验证码 三 使用postman测试验证码 四 存在的问题 使用redis工具查看为二进制数据 对开发者不友好 4 1 注意 4 2 解决方法 gt 配置序
  • ​LeetCode刷题实战267:回文排列II

    算法的重要性 我就不多说了吧 想去大厂 就必须要经过基础知识和业务逻辑面试 算法面试 所以 为了提高大家的算法能力 这个公众号后续每天带大家做一道算法题 题目就从LeetCode上面选 今天和大家聊的问题叫做 回文排列II 我们先来看题面
  • Chrome启动参数大全

    原文地址 https www cnblogs com yikemogutou articles 12624113 html 序号 条件 说明 1 报告伪分配跟踪 伪跟踪从当前活动的跟踪事件派生 2 prefetch 1 prefetch 启
  • 【无标题】Unable to convert type java.lang.Character of 8 to type of java.lang.CharSequence

    服务器内部错误org mybatis spring MyBatisSystemException nested exception is org apache ibatis exceptions PersistenceException E
  • GitHub 80k星Python神级学习路线,从青铜到王者,赶紧收藏!

    Python 为什么这么火 有很多原因 列举几点 语法简单易学 其他语言 5 行代码才能实现的东西 Python 一行搞定 可以少写很多代码 因此不少同学拿 Python 刷算法题 但注意要理解算法本身哦 类库生态丰富 想做什么功能基本都有
  • 程序计数器的作用--简单易懂

    3 程序计数器 什么是程序计数器 它是干什么用的 java中程序计数器是用寄存器实现的 它的作用是寻找下一个要执行的程序 当我们的java程序被编译成二进制字节码文件后 如下图 右面 是我们写的代码 左面是二进制字节码形式 class 它们
  • FFmpeg 控制台窗口的隐藏和正常退出

    FFmpeg无疑是音视频界的翘首 很多企业或个人都会拿来使用 具体怎么使用 在此不做赘述 这里仅仅讲述如何用C 调用ffmpeg指令 以及调用的控制台窗口的正常关闭 录像或转码等情况下 非正常关闭 直接导致文件损坏 不可用 一 指令的执行
  • PID控制原理详解(一)

    PID的理解 关于理解PID控制算法最典型的一个例子就是一个漏水的水缸的问题 网上有很多讲解PID的帖子会讲到这个例子 这里我也把我自己对于PID的理解用这个例子阐述一遍 有个漏水的水缸 而且漏水的速度还不是恒定的 然后我们还有个水桶 我们
  • BES2300x笔记(14) -- 提示音模块

    哈喽大家好 这是该系列博文的第十四篇 篇 lt lt 系列博文索引 快速通道 gt gt 一 前言 提示音 的这个模块 代码量确实不小啊 这一篇 我们就来梳理一下 提示音相关接口的调用逻辑吧 二 代码调用逻辑 app voice repor
  • To see the full stack trace of the errors, re-run Maven with the -e switch.

    问题描述 微服务项目中其它模块不能依赖common模块中的依赖 而common中是有依赖的 然后重新对common进行install发现报错 原因分析 经过查找是由于common中的pom xml中有一个依赖被引入了两次 删掉其中一个即可
  • 461. 汉明距离

    题目描述 两个整数间的汉明距离是指 这两个数字对应二进制位不同的位置的数目 给定两个整数 x 和 y 计算它们间的汉明距离 注意 0 x y lt 2 31 样例 示例 输入 x 1 y 4 输出 2 解释 1 0 0 0 1 4 0 1
  • 从0到1,一文掌握用户画像标签体系

    一 标签体系概览 1 什么是对象 2 什么是标签 标签是人为设定的 根据业务场景需求 对目标对象运用一定的算法得到的高度精炼的特征标识 标签是对对象某个维度特征的描述与刻画 是某一种用户特征的符号表示 每一种标签都规定了我们观察认识描述对象
  • Redis第二十二讲 Redis高可用集群节点通信机制

    两个端口 在哨兵系统中 节点分为数据节点和哨兵节点 前者存储数据 后者实现额外的控制功能 在集群中 没有数据节点与非数据节点之分 所有的节点都存储数据 也都参与集群状态的维护 为此 集群中的每个节点 都提供了两个 TCP端口 普通端口 即我
  • 电脑上面的word文档被删除了怎么办?分享四种亲测恢复方法

    不小心把电脑里面的word文档删除了 当你需要用到这些被误删的文档后 怎么找回呢 根本不知道从何入手的小伙伴不用担心 因为办法总比困难多多 下面就让小编为大家分享word文档恢复的方法 方法均以win10系统为例进行操作 大家跟着操作将其恢
  • android.content.res.Resources$NotFoundException: String resource ID #0x1

    在Android开发中如果出现android content res Resources NotFoundException String resource ID 0x1这样的错误 你想也不用想 一定是Textview控件显示数据出了问题