来自非 Activity 类的非 Activity 类中的Android getResource?

标签 android resources android-manifest

我在非 Activity 类中获得了以下方法,我的代码如下。

public class ReadTextByLineNo  {

public void setContext(Context _context) {
    if (context == null) {
        context = _context;
    }
}
public String getTextByLine(int Filename,int LineNumber)
{


    String output="";
    String line="";
    int counter=1;
    try
    {
         InputStream in = context.getResources().openRawResource(Filename);
        //InputStream in = assetManager.open(Filename);
        if(in!=null)
        {
            InputStreamReader input = new InputStreamReader(in);
            BufferedReader buff = new BufferedReader(input);
            while((line=buff.readLine())!=null)
            {
                if(counter ==LineNumber){
                    output=line;
                }counter++;
            }in.close();
        }else{
            Log.e("Input STREAM PROBLEM", "TEXT IS NULL NULL NULL NULL NULL");
        }
    }catch(Exception e)
    {
        //log
    }

    return output;
}

**I am calling this method from an NON_ACTIVITY CLASS LIKE THIS **

class sample implements Isample
{
ReadTextByLineNo read = new ReadTextByLineNo();
String subMsg =  read.getTextByLine(R.raw.subtitle, storySceneId);
//the above string is to called from an activity called Layout 


}

如何使用来自非 Activity 类的资源/上下文?我不能在构造函数中使用上下文,因为我也在从非 Activity 类调用该方法。 所以我不能设置 read.setContent(this);我在 ReadtextByLineNo 类中获得 setContext 方法的地方,感谢您的帮助。

请帮助我获取类示例中的上下文/资源,并感谢代码示例

最佳答案

public class ReadTextByLineNo  {
    private static Context context;

    public static void setContext(Context mcontext) {
        if (context == null)
            context = mcontext;
    }
}

当您的应用程序启动时,只需通过调用初始化此上下文

ReadTextByLineNo.setContext(getApplicationContext());

从你的主要 Activity ..

享受...

关于来自非 Activity 类的非 Activity 类中的Android getResource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8705618/

相关文章:

image - 如何正确添加资源(*.res)文件到组件包中?

c# - 如何在Visual Studio中为不同的编译宏设置不同的资源?

Laravel,具有自定义策略方法的自定义 Controller 方法?

android - Android应用程序启动时如何启动Service?

java - 正在发送短信 : User 10074 does not have android. 权限.SEND_SMS

Android 应用内结算取消付款,应用未激活

java - 如果使用 .asBitmap(), Glide 监听器不起作用

android - 请求权限 READ_SMS 后,包安装程序在 Android M 中崩溃

Android选择 Activity 文字颜色

android - Activity B 在 Activity A 之前开始