来自非活动类的非活动类中的Android getResource?

时间:2012-01-02 21:40:40

标签: 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;
}
  

**我从这样的非活动类别中调用此方法**

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类调用该方法。 所以我无法设置read.setContent(this);我在ReadtextByLineNo类中获得了setContext方法,感谢您的帮助。

请帮助我在课程样本中获取上下文/资源,并通过代码获得示例

1 个答案:

答案 0 :(得分:6)

public class ReadTextByLineNo  {
    private static Context context;

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

当您的应用程序启动时,只需通过调用

来初始化此上下文
ReadTextByLineNo.setContext(getApplicationContext());

来自您的主要活动..

...享受