Symptom
Calling this.resourceManager.getStringResource($r('app.string.PlayCount').id) returns an error.
Error message: Resource id invalid
Error code: 9001001
SourceCode: returnResource = this.context.resourceManager.getStringSync(id)
Possible Causes
The provided ID does not exist; the corresponding context is not created.
Solution
Create a context for the target module using its module name, and then use getStringByNameSync to obtain the resource by name. This ensures the correct resource is accessed with the appropriate context. The sample code is as follows:
import { common, application } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { JSON } from '@kit.ArkTS';
@Entry
@Component
struct Index {
private context = this.getUIContext().getHostContext() as common.UIAbilityContext;
build() {
Column() {
Button()
.onClick(() => {
// Create a context based on the module name
let moduleName: string = 'library';
application.createModuleContext(this.context, moduleName)
.then((data: common.Context) => {
console.info(`CreateModuleContext success, data: ${JSON.stringify(data)}`);
if (data !== null) {
this.getUIContext().getPromptAction().showToast({
message: ('get Context success')
});
}
// Then run getStringByNameSync to obtain the string corresponding to the specified resource name
try {
let str = data.resourceManager.getStringByNameSync('shared_desc');
console.info(`getStringByNameSync, data: ${JSON.stringify(str)}`);
} catch (error) {
let code = (error as BusinessError).code;
let message = (error as BusinessError).message;
console.error(`getStringByNameSync failed, error code: ${code}, message: ${message}.`);
}
})
.catch((err: BusinessError) => {
console.error(`CreateModuleContext failed, err code:${err.code}, err msg: ${err.message}`);
});
})
}
}
} Reference
Context (Stage Model), Obtaining the Context of Other Modules in the Current Application, getStringByNameSync