我在非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类调用该方法.
所以我无法设置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());
来自你的主要活动..
请享用…
标签:android,resources,android-manifest
来源: https://codeday.me/bug/20190530/1184987.html