【发布时间】:2019-11-20 05:21:04
【问题描述】:
您好,我正在开发 Android Studio,但遇到了一个似乎无法解决的简单但奇怪的问题。我已经将两个字符串数组定义为 xml 资源文件,包括在下面。
我有一个作为控制器的单例类,我尝试使用 xml 文件中定义的那些字符串数组填充两个字符串数组列表。编译器似乎对编写的代码没有任何问题,甚至很乐意将这两个字符串数组作为自动完成的一部分提供。只有当代码运行时,我才会收到以下错误
android.content.res.Resources$NotFoundException
此时我已经尝试清理和重建项目,使缓存失效并重新启动 AS,并且我还尝试重命名 xml 中的字符串数组并重新编译代码。最初,我创建了一个新的 xml 资源文件来存储这些字符串数组,但目前我已将它们移到字符串资源文件中,但无论哪种方式都不起作用。
这些都不起作用,我真的很困惑问题可能是什么。我很感激你们可以提供的任何帮助。提前致谢。
这是字符串 xml 资源文件的相关位。
<resources>
<string-array name="randomTriviaQuestionsArray">
<item>As far as has ever been reported, no-one has ever seen an ostrich bury its head in the sand.</item>
<item>Approximately one quarter of human bones are in the feet.</item>
<item>Popeye’s nephews were called Peepeye, Poopeye, Pipeye and Pupeye.</item>
<item>In ancient Rome, a special room called a vomitorium was available for diners to purge food in during meals.</item>
<item>The average person will shed 10 pounds of skin during their lifetime.</item>
<item>Sneezes regularly exceed 100 m.p.h.</item>
<item>A slug’s blood is green.</item>
<item>The Great Wall Of China is visible from the moon.</item>
<item>Virtually all Las Vegas gambling casinos ensure that they have no clocks.</item>
<item>The total surface area of two human lungs have a surface area of approximately 70 square metres.</item>
</string-array>
<string-array name="randomTriviaAnswersArray">
<item>True.</item>
<item>True – 52 bones in the feet and 206 in the whole body.</item>
<item>True.</item>
<item>False – It was the name for the entranceway to a stadium, nothing more.</item>
<item>False – they will shed approximately 40.</item>
<item>True</item>
<item>True</item>
<item>False – at a low orbit the Great Wall is visible, but no man-made structure is visible from outer space or the moon.</item>
<item>True</item>
<item>True</item>
</string-array>
</resources>
这是在运行时发生错误的代码。
public void setupQuestionBank(String questionFileName){
List<String> qList;
List<String> aList;
switch(questionFileName){
case "randomTrivia":
qList = Arrays.asList(Resources.getSystem()
.getStringArray(
R.array.randomTriviaQuestionsArray));
aList = Arrays.asList(Resources.getSystem()
.getStringArray(
R.array.randomTriviaAnswersArray));
break;
default:
qList = new ArrayList<>();
aList = new ArrayList<>();
}
编辑:感谢 DevMike01,这是此问题的解决方案。使用 Activity 或 Fragment 的 Context 对象来访问资源。
public void setupQuestionBank(String questionFileName){
List<String> qList;
List<String> aList;
switch(questionFileName, Context context){
case "randomTrivia":
qList = Arrays.asList(context.getResources()
.getStringArray(
R.array.randomTriviaQuestionsArray));
aList = Arrays.asList(context.getResources()
.getStringArray(
R.array.randomTriviaAnswersArray));
break;
default:
qList = new ArrayList<>();
aList = new ArrayList<>();
}
【问题讨论】:
标签: java android android-studio