I have a code inside myActivity.class
InputStream inputStream = getApplicationContext().getResources().openRawResource(R.raw.text);
BufferedReader buff = new BufferedReader(new InputStreamReader(inputStream));
String s;
ArrayList <String> list = new ArrayList <String>();
try
{ while((s = buff.readLine()) != null)
{
list.add(s);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I want to move that part of code to separate java.class, but here I face a problem, how I can to access a raw file by InputStream without using getApplicationContext()?
For instance:
public class MyArrayList extends ArrayList<String>
{
private InputStream in = ???; // how to declare InpuStream without Context???
private BufferedReader buff = new BufferedReader(new InputStreamReader(in));;
private String s;
private MyArrayList array;
public MyArrayList ()
{
try
{
while ((s = buff.readLine()) != null)
{
array.add(s);
}
} catch (IOException e)
{
e.printStackTrace();
} finally
{
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I have tried
InputStream in = Resources.getSystem().openRawResource(R.raw.text);
but it gave me NullPointerException
So my question is: Does exist some way to initialize InputStream with raw file outside Activity ?
how I can to access a raw file by InputStream without using getApplicationContext()?
First, you do not need getApplicationContext()
in your existing code. Deleting it will work just fine, and it saves an unnecessary call.
Beyond that -- and assuming that you really think that an ArrayList
should be responsible for I/O -- MyArrayList
needs you to pass in one of the following:
the InputStream
, or
the Resources
(so you can call openRawResource()
on it), or
a suitable Context
(so you can call getResources()
on it) (and which, depending on the lifetime of MyArrayList
, could be one of several possible objects)