문제

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.

도움이 되었습니까?

해결책

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

  • this or this.getContext() - if you are calling method within an activity
  • getActivity() - if you calling this within a fragment (Beware: do a null check before using. getActivity() will return null if the fragment is not attached to an activity)
  • _varWithContextIn - if you are calling this within say an setOnClickListener where "this" becomes the onClickListener you are creating.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top