[英]Arraylist in a separate java file neither an activity or fragment, how to get the string value from string.xml?
Good day, I would like to know or ask for help.美好的一天,我想知道或寻求帮助。 I'm having a hard time getting the string value from my app's string.xml.我很难从我的应用程序的 string.xml 中获取字符串值。 I am accessing it through an Arraylist (in a separate java file. arraylist is not inside the activity or fragment).我通过 Arraylist 访问它(在一个单独的 java 文件中。arraylist 不在活动或片段中)。
I tried both String.valueOf and Integer.toString (refer below ss):我尝试了 String.valueOf 和 Integer.toString (请参阅下面的 ss):
but the results for the both are the same(please refer below ss):但两者的结果是相同的(请参考下面的 ss):
the left items are supposed to be a string value from my string.xml but I don't know how and why.左边的项目应该是我的 string.xml 中的字符串值,但我不知道如何以及为什么。 I also tried Resources.getString but it crashes the app.我也试过 Resources.getString 但它使应用程序崩溃。
Do you have any idea that I can try in solving this problem?你知道我可以尝试解决这个问题吗? Thank you, it will be very much appreciated and sorry for the time answering my question.谢谢,非常感谢您花时间回答我的问题。
EDIT: Here's the code(please see ss below) and I also tried the getString() suggestion.编辑:这是代码(请参阅下面的 ss),我也尝试了 getString() 建议。
sorry I'm really not good in development but I'm willing to listen and learn.对不起,我真的不擅长开发,但我愿意倾听和学习。
Add a context
argument to your function:为您的函数添加context
参数:
public static ArrayList<CategoryObject> getCategories(Context context) {
final ArrayList<CategoryObject> categoryObjects = new ArrayList<>();
final Resources resources = context.getResources();
CategoryObject categoryObject = new CategoryObject();
categoryObject.setCategoryTitle(resources.getString(R.string.psi));
categoryObject.setItem1(resources.getString(R.string.psi1));
categoryObject.setItem2(resources.getString(R.string.psi2));
categoryObject.setItem3(resources.getString(R.string.psi3));
categoryObject.setItem4(resources.getString(R.string.psi4));
categoryObjects.add(categoryObject);
return categoryObjects;
}
Notice that I changed your ArrayList variable name to use Java's camelCase standard ( CategoryObjects
--> `categoryObjects).请注意,我更改了您的 ArrayList 变量名称以使用 Java 的驼峰命名法标准( CategoryObjects
--> `categoryObjects)。
Then you just need to pass a Context object to it.然后你只需要向它传递一个 Context 对象。
From an Activity:从一个活动:
Category.getCategories(this);
From a Fragment:从片段:
Category.getCategories(getActivity());
In the future, please paste your code as text .以后,请将您的代码粘贴为text 。 It's actually a lot easier than taking a screenshot.这实际上比截取屏幕截图要容易得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.