Reputation: 65
I have a class that uses static method from other class
public class ArticleFragment extends Fragment {
...
// use static method to get text from file
String articleString = FileRead.readRawTextFile();
article.setText(articleString);
...
}
then I have class with the method
public class FileRead extends Application {
private static Context ctx;
@Override
public void onCreate() {
super.onCreate();
ctx = this;
}
public static Context getContext(){
return ctx;
}
public static String readRawTextFile()
{
InputStream inputStream = null;
StringBuilder text = new StringBuilder();
try {
//**** E R R O R ***********************
inputStream = FileRead.getContext().getResources().openRawResource(R.raw.plik);
//***************************************
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
while (( line = buffreader.readLine()) != null) {
text.append(line);
text.append('\n');
}
return text.toString();
} catch (Exception e) {
Log.e("APP", "*** "+e, e);
return null;
}
}
}
I get error NullPointerException. File is in res/raw. I think there is a problem with context but don't know why.
Upvotes: 1
Views: 420
Reputation: 495
donfuxx is right; FileRead.getContext()
is null.
However we can still get context! Pass it in as a parameter for readRawTextFile()
.
So it becomes:
public static String readRawTextFile(Context context);
then change the FileRead.getContext()
to
inputStream = context.getResources().openRawResource(R.raw.plik);
then change your method call to this:
String articleString = FileRead.readRawTextFile(context);
replacing context with
Upvotes: 1