0

What is wrong with my code? I get this error every time I run my code. Trying to download a .txt file, and then display the text in the toast. That is all I want!

                                                              : FATAL EXCEPTION: main    Process: nnsoft.nsomuhtest, PID: 18706
                                                                  java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
                                                                      at android.widget.Toast.<init>(Toast.java:138)
                                                                      at android.widget.Toast.makeText(Toast.java:385)

code:

 @Override
    protected void onPostExecute(String unused) {
        StringBuilder text = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(AnnouncementsDirectory));
            String line;
            while ((line = br.readLine()) != null) {
                text.append(line);
                text.append('\n');
            }
            br.close();
            Toast.makeText(context, text, Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Toast.makeText(context, "error reading ver file", Toast.LENGTH_LONG).show();
        }
    }
  • `context` is null. Show where you initialize it. – Daniel Nugent Oct 25 '17 at 21:08
  • That's the declaration. Where do you assign it to a valid Context? – Daniel Nugent Oct 25 '17 at 21:09
  • the problem is that `context` is null. Assign it to your Activity or Application context, and it will work. – Daniel Nugent Oct 25 '17 at 21:59
  • @DanielNugent how bro? I don't know how that works and I need to deliver this assignment to school tomorrow. and this is a class btw, it does not extent anything –  Oct 25 '17 at 22:00
  • Replace context with ActviityName.this – Sagar Patel Oct 26 '17 at 04:30
  • You should get the application context but using `Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();` – ClassA Oct 27 '17 at 14:54
  • @ClassA I am using a class, which does not extent anything. So I won't be able to use that. –  Oct 27 '17 at 15:04
  • Exactly my point, you are using a class with no context.. You need to pass the ApplicationContext to your class. Look at this - https://stackoverflow.com/a/5498816/8199772 – ClassA Oct 27 '17 at 15:14
  • @ClassA I used https://stackoverflow.com/a/5498771/8780097 this answer, but it did not work, my toast still says 'cannot resolve getapplicationcontext()"" –  Oct 27 '17 at 17:18

0 Answers0