我在非 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/