简体   繁体   中英

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. I am accessing it through an Arraylist (in a separate java file. arraylist is not inside the activity or fragment).

I tried both String.valueOf and Integer.toString (refer below ss):

在此处输入图片说明

but the results for the both are the same(please refer below ss):

在此处输入图片说明

the left items are supposed to be a string value from my string.xml but I don't know how and why. I also tried Resources.getString but it crashes the app.

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. 在此处输入图片说明

sorry I'm really not good in development but I'm willing to listen and learn.

Add a context argument to your function:

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).

Then you just need to pass a Context object to it.

From an Activity:

Category.getCategories(this);

From a Fragment:

Category.getCategories(getActivity());

In the future, please paste your code as text . It's actually a lot easier than taking a screenshot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM