Android getResource in non activity class from Non Activity class?

I got the following method in the non Activity class, my code is below.

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 the NON_ACTIVITY LIKE THIS class **

 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 } 

How to use resources / context from non-activity class? I cannot use context in the constructor, since I also call a method from the non Activity class. so i cant set read.setContent (this); where I got the setContext method in my ReadtextByLineNo class, thanks for the help.

Please help me get the context / resource in the sample class and example using code.

+4
source share
1 answer
 public class ReadTextByLineNo { private static Context context; public static void setContext(Context mcontext) { if (context == null) context = mcontext; } } 

when your application starts, just initialize this context by calling

 ReadTextByLineNo.setContext(getApplicationContext()); 

from your main activity.

Enjoy ...

+6
source

Source: https://habr.com/ru/post/1388986/


All Articles