Android中如何在非Activity类中获取资源?

4

我在一个非 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 


}

如何在非活动类中使用资源/上下文?由于我还从非活动类中调用该方法,因此无法在构造函数中使用上下文。所以我不能设置read.setContent(this);在我的ReadtextByLineNo类中有一个setContext方法,感谢您的帮助。

请帮助我通过代码示例获取类样本和示例中的上下文/资源。

1个回答

6
public class ReadTextByLineNo  {
    private static Context context;

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

当您的应用程序启动时,只需调用该上下文进行初始化,即可开始操作。
ReadTextByLineNo.setContext(getApplicationContext());

从您的主活动中...

享受...


我没有在Activity中调用该方法,所以如何在非Activity类中使用它?ReadTextByLineNo.setContext(getApplicationContext()); - optimus
兄弟,不要从非 Activity 中调用此方法,只需从任何其他活动中调用此方法以设置上下文,现在别告诉我你的应用程序中没有任何 Activity。: D,请从您的第一个 Activity 中调用它,以便设置上下文,这很简单... - AAnkit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接